我已经创建了我的服务帐户,获得了 private_key 并委派了域范围的权限。
这是我的代码尝试使用服务帐户进行身份验证但收到相同的“无效 token 格式错误”:
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/
任何帮助将不胜感激。谢谢!
最佳答案
问题是过时的 google 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();根本...
谷歌干得好......这些是我从以下代码中获取的过时且不可靠的文档页面:
https://developers.google.com/admin-sdk/directory/v1/quickstart/php
和
https://developers.google.com/api-client-library/php/auth/service-accounts
还有一件事 : 万一你需要玩 谷歌表格 ,您可能需要将帐户服务 ID (xxxxxxxxxx@xxxxxxxxxxxxxx.iam.gserviceaccount.com) 添加到要从中提取信息的 google 表格文档中。
关于php - 带有 PHP : "Invalid token format error" 服务帐户的 Google OAuth 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39792859/