Google php api 身份验证异常

Google php api authentication exception

我正在尝试使用 Outh2 验证 google 服务帐户,但一直收到此错误 -

Exception - Error refreshing the OAuth2 token, message: '{ "error" : "access_denied", "error_description" : "Requested client not authorized." }'

我已遵守 https://developers.google.com/api-client-library/php/auth/service-accounts 的所有指示 我也确实从 google 管理控制台授权了服务帐户,但仍然没有成功。如果下面的代码有什么问题,谁能提出建议 -

$client_email = aab123@developer.gserviceaccount.com';
        $private_key = file_get_contents('private_key_file_location.p12');
        $scopes = array('https://spreadsheets.google.com/feeds');
        $user_to_impersonate = 'user@example.com';
        $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, 
                                                            $private_key, 'notasecret',
                                                           'http://oauth.net/grant_type/jwt/1.0/bearer',
                                                           $user_to_impersonate);

        $client = new Google_Client();

        $client->setApplicationName('Portal Assessment Module');
        $client->setAccessType('offline');

        $client->setAssertionCredentials($credentials);
        if ($client->getAuth()->isAccessTokenExpired()) {
            $client->getAuth()->refreshTokenWithAssertion($credentials);    /* Exception 
is being triggered here */    
}

谢谢。

试试这个

require_once realpath(dirname(__FILE__).'/google-api-php-client/src/Google/autoload.php');

define('SCOPES', implode(' ', array(Google_Service_Appsactivity::DRIVE)));

$credentials = new Google_Auth_AssertionCredentials(
    $client_email,
    SCOPES,
    $private_key
);

$client = new Google_Client();
$client->setAssertionCredentials($credentials);

if ($client->getAuth()->isAccessTokenExpired())
{
    $client->getAuth()->refreshTokenWithAssertion();
}

print_r($client->getAccessToken());

终于弄明白了,必须确保 $user_to_impersonate 与 $client_email 相同,并且该电子邮件地址对电子表格具有编辑权限。

$user_to_impersonate = $client_email