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

Le *_*oom 1 php oauth-2.0 google-api-php-client service-accounts google-admin-sdk

我创建了我的服务帐户,获得了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;
}
Run Code Online (Sandbox Code Playgroud)

这里是我之前从$ accessToken获得的截图

$client->setAccessToken($accessToken);
Run Code Online (Sandbox Code Playgroud)

错误本身:

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

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

Le *_*oom 11

问题是过时的谷歌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;
}
Run Code Online (Sandbox Code Playgroud)

不需要$ 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)添加到要从中提取信息的Google工作表文档中.