0

我已經創建了我的服務帳戶,得到了private_key和委託域的廣泛權限。谷歌OAuth 2.0服務帳戶與PHP:「無效的令牌格式錯誤」

這裏是我的代碼試圖與服務帳戶進行身份驗證,但得到了同樣的「令牌無效格式錯誤」:

session_start(); 
include_once 'google-api-php/vendor/autoload.php'; 

function getClient() { 
$client = new Google_Client(); 
$client->setApplicationName('theName'); 
$client->setScopes('https://www.googleapis.com/auth/admin.directory.user.readonly'); 
$client->setAccessType('offline'); 
$client->setSubject('[email protected]'); 
$client->setAuthConfig('private_key.json'); 

// Load previously authorized credentials from a file. 
$credentialsPath = 'private_key.json'; 
if (file_exists($credentialsPath)) { 
    $accessToken = json_decode(file_get_contents($credentialsPath), true); 
} 
else { 
    // Request authorization from the user. 
    $authUrl = $client->createAuthUrl(); 
    printf("Open the following link in your browser:\n%s\n", $authUrl); 
    print 'Enter verification code: '; 
    $authCode = trim(fgets(STDIN)); 

    // Exchange authorization code for an access token. 
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); 

    // Store the credentials to disk. 
    if(!file_exists(dirname($credentialsPath))) { 
     mkdir(dirname($credentialsPath), 0700, true); 
    } 
    file_put_contents($credentialsPath, json_encode($accessToken)); 
    printf("Credentials saved to %s\n", $credentialsPath); 
} 

$client->setAccessToken($accessToken); 

// Refresh the token if it's expired. 
if ($client->isAccessTokenExpired()) { 
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); 
    file_put_contents($credentialsPath, json_encode($client->getAccessToken())); 
} 
return $client; 
} 

這裏是什麼,我之前從$的accessToken得到截圖

$client->setAccessToken($accessToken); 

與錯誤本身:

https://postimg.org/image/ajgan5y27/

任何幫助將不勝感激。謝謝!

回答

7

問題是過時的谷歌API文件。 原來的「getClient」功能只需要對這種情況下任何人合作的新版本有麻煩:

function getClient() { 
    $client = new Google_Client(); 
    $client->setAuthConfig('private_key.json'); 
    $client->setApplicationName('theName'); 
    $client->setScopes(Google_Service_Sheets::SPREADSHEETS_READONLY); 
    return $client; 
} 

不需要$客戶 - > setAccessToken();在所有...

幹得好谷歌......這些都是過時的和不可靠的文檔頁面我把這個代碼:

https://developers.google.com/admin-sdk/directory/v1/quickstart/phphttps://developers.google.com/api-client-library/php/auth/service-accounts

一件事:萬一您需要使用Google表格,您可能需要將帳戶服務ID([email protected])添加到您要從中提取信息的Google表單文檔。

+0

這應該被接受爲正確答案。 – Alexey

相關問題