通过refresh_token获取新的access_token非常不可靠

时间:2016-11-28 15:37:47

标签: php youtube youtube-api google-oauth youtube-data-api

因此,我尝试刷新访问令牌。 当访问令牌过期时,我运行refreshToken()并传递refresh_token以从Google获取新的access_token。

有时它似乎有用,但其他后面我收到错误消息 invalid_grant 。似乎我无法重新授权访问我的YouTube频道,但我可以通过超过几天的时间。

我做错了什么必不可少的事?

if ($client->getAccessToken()) {      
    if($client->isAccessTokenExpired()) {
        $newToken = $client->getAccessToken();

        //Run refreshToken() and pass in the refresh token to get a fresh access token.
        $client->refreshToken($newToken['refresh_token']);

        //Take old key object and replace everything except for refresh_token    
        $newKey = $client->getAccessToken();

        $newKeyWithRefreshToken = json_decode($oldKey);
        $newKeyWithRefreshToken->access_token = $newKey['access_token'];
        $newKeyWithRefreshToken->token_type = $newKey['token_type'];
        $newKeyWithRefreshToken->expires_in = $newKey['expires_in'];
        $newKeyWithRefreshToken->created = $newKey['created'];

        //save to db
        DB::getInstance()->update('channel', $channelId , array(
            'credentials' => json_encode($newKeyWithRefreshToken)
        ));

1 个答案:

答案 0 :(得分:0)

在您获得Google授权期间,您将收到一个将在一小时或3600秒后过期的令牌,过期是正常的。所以你需要的是一个刷新令牌来获得一个新的工作令牌。

以下是您需要的步骤:

$token = $client->getAccessToken();
$authObj = json_decode($token);
if(isset($authObj->refresh_token)) {
save_refresh_token($authObj->refresh_token);
}

保存此refresh_token很重要,然后您可以使用

更新它
$client->refreshToken($your_saved_refresh_token);

然后将新的访问令牌设置为会话:

$_SESSION['access_token'] = $client->getAccessToken();

有关详细信息,请查看此SO question