0

So I'm trying to get refreshing the access token to work. When the access token is expired, I run refreshToken() and pass the refresh_token to get a new access_token from Google.

Sometimes it seems to work, but otherwhiles I get the error message invalid_grant after that. Seems like I can't pass more than a few days without re-authorising access to my YouTube channel.

Anything essential I am doing wrong?

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)
        ));
Noniq
  • 161
  • 4
  • 12

1 Answers1

0

During your authorization with Google, you will receive a token that will expire in one hour or 3600 seconds and it is normal to be expired. So what you need is a refresh token to get a new working token.

Here are the steps that you need:

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

It is important to save this refresh_token, then you can update it with

$client->refreshToken($your_saved_refresh_token);

And then set your new access token to the session:

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

For more information, check this SO question.

Community
  • 1
  • 1
KENdi
  • 7,205
  • 2
  • 14
  • 26
  • Hi KENdi, first of all, thanks for your answer. Maybe I wasn't clear enough, but I have no problem getting a refresh_token and using it to get a new access_token. It just stops working for me somehow every few days saying my credentials are now invalid. ("invalid_grant") – Noniq Nov 29 '16 at 22:21