【问题标题】:Using a Service Account, getAccessToken() is returning null使用服务帐户,getAccessToken() 返回 null
【发布时间】:2013-08-15 17:49:24
【问题描述】:

我正在运行以下 PHP 代码,使用此处找到的客户端库:https://code.google.com/p/google-api-php-client/。我没有收到任何此代码的任何错误,但是当我调用 getAccessToken() 时,它返回 null。

我已在我的个人日历上允许访问此服务帐户,并已通过 API 控制台授予对项目的完全访问权限。

有什么想法吗?

require_once 'google-api-php-client/src/Google_Client.php';

const CLIENT_ID = 'blahblahblah';
const SERVICE_ACCOUNT_NAME = 'blahblahblah@developer.gserviceaccount.com';
const KEY_FILE = 'path/to/privatekey.p12';

$google_client = new Google_Client(); // created only to initialized static dependencies
$client = new Google_OAuth2(); // you really just need Google_OAuth2

$key = file_get_contents(KEY_FILE);  

$client->setAssertionCredentials(
    new Google_AssertionCredentials(
        SERVICE_ACCOUNT_NAME,
        array('https://www.googleapis.com/auth/calendar'),
        $key
    )
);

var_dump($client->getAccessToken());

【问题讨论】:

    标签: php google-api oauth-2.0 google-oauth google-api-php-client


    【解决方案1】:

    由于某种原因,这似乎有效:

    require_once 'google-api-php-client/src/Google_Client.php';
    
    const CLIENT_ID = 'blahblahblah';
    const SERVICE_ACCOUNT_NAME = 'blahblahblah@developer.gserviceaccount.com';
    const KEY_FILE = 'path/to/privatekey.p12';
    const CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar";
    
    $key = file_get_contents(KEY_FILE);
    $auth = new Google_AssertionCredentials(
        SERVICE_ACCOUNT_NAME,
        array(CALENDAR_SCOPE),
        $key
    );
    
    $client = new Google_Client();
    $client->setScopes(array(CALENDAR_SCOPE));
    $client->setAssertionCredentials($auth);
    $client->getAuth()->refreshTokenWithAssertion();
    $accessToken = $client->getAccessToken();
    
    $client->setClientId(CLIENT_ID);
    

    如果有人可以解释为什么这有效,请编辑此答案或发表评论!

    【讨论】:

    • 也不确定。我在gist.github.com/fulldecent/6728257 使用您的代码,并且仅供参考,不需要 setScopes 行
    • getAccessToken() 返回当前访问令牌,直到您调用 refreshTokenWithAssertion()(初始化它)或 setAccessToken()(如果您恢复了您想要使用的以前的访问令牌,它才存在)。
    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 2016-03-18
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 2015-01-18
    相关资源
    最近更新 更多