Google Oauth2: Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'

Viewed 6313

I have the following code running on my localhost to try and authenticate with Google Oauth2. After authenticating, it appears to work for a while. Then after a certain amount of time I'm getting this classic error:

Error refreshing the OAuth2 token, message: '{
"error" : "invalid_grant"
}'

I've looked at the previous times this issue was posted to StackOverflow, but the suggested solutions didn't seem to work for me.

I believe the access token is updated correctly (see code below). I also believe the server clock is synchronized correctly. What am I doing wrong?


    //$token retrieved from database
    $token = {"access_token":"xxx.xxx_xxxx-xxx","token_type":"Bearer","expires_in":3600,"refresh_token":"1\/xXxXxxxxxXXXxx","created":145490000}

    $google = new Google_Client();
    $google->setAccessType('offline');
    $google->setClientId($client_id);
    $google->setClientSecret($client_secret);
    $google->setRedirectUri($client_redirect_uri);
    $google->setAccessToken($token);
    if($google->isAccessTokenExpired()) {
      $google->refreshToken($token);
    }
    $token = $google->getAccessToken();
    $google->setAccessToken($token);

    //Some Database code to save the new $token
    ...

    $result = new \Google_Service_YouTube($google);
1 Answers
Related