带有PHP服务帐户的Google OAuth 2.0:"无效的令牌格式错误"

时间:2016-09-30 13:36:01

标签: php oauth-2.0 google-api-php-client google-admin-sdk service-accounts

我已经创建了我的服务帐户,获得了private_key并委托了域范围的权限。

以下是我的代码尝试使用服务帐户进行身份验证但获得相同的"无效的令牌格式错误":

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('admin@domain.com');
$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/

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:10)

问题是过时的谷歌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;
}

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

干得好google ...这些是我从以下代码中获取的过时且不可靠的文档页面:

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

还有一件事:如果您需要使用 Google表格,您可能需要添加帐户服务ID(xxxxxxxxxx@xxxxxxxxxxxxxx.iam.gserviceaccount.com )到谷歌工作表文档,你想从中提取信息。