首页 文章

谷歌php api身份验证例外

提问于
浏览
1

我正在尝试使用Outh2验证Google服务帐户,但不断收到此错误 -

异常 - 刷新OAuth2令牌时出错,消息:'{“error”:“access_denied”,“error_description”:“请求的客户端未经授权” . }”

我已经按照https://developers.google.com/api-client-library/php/auth/service-accounts的每条指令进行了操作 . 我也从谷歌管理控制台授权服务帐户,但仍然没有运气 . 任何人都可以建议如果下面的代码有任何错误 -

$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 */    
}

谢谢 .

2 回答

  • 0

    Try this

    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());
    
  • 0

    最后想出来,必须确保$ user_to_impersonate与$ client_email相同,并且该电子邮件地址还具有对电子表格的编辑权限 .

    $user_to_impersonate = $client_email
    

相关问题