Search code examples
phpgoogle-apigoogle-oauthgoogle-api-php-clientgoogle-api-client

refresh token with google api client not working


In my website i have an upload button for upload files to google drive via api.

Here is my code:

$auth_code      = GOOGLEDRIVE_AUTH_CODE;
$access_token   = GOOGLEDRIVE_ACCESS_TOKEN;
$refresh_token  = GOOGLEDRIVE_REFRESH_TOKEN;
$client_id      = 'Google_App_Client_ID';
$client_secret  = 'Google_App_Client_Secret';
$redirect_uri   = 'Redirct_Url';

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);

if (isset($access_token) && $access_token) {
    $client->setAccessToken($access_token);
    if ($client->isAccessTokenExpired()) {
        $refresh_token = $client->getRefreshToken();
        $client->refreshToken($refresh_token);
        $access_token = $client->getAccessToken();
        $co->save('GDRIVE_ACCESS_TOKEN',$access_token);
        $co->save('GDRIVE_REFRESH_TOKEN',$refresh_token);
    }
} else {
    $authUrl = $client->createAuthUrl();
}

this line throws an error

$client->refreshToken($refresh_token);

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

Reading up on the error message it sounds like the token refresh isn’t working all of a sudden. Like I said, this upload tool has been working fine for months.

Any Idea ?

Thanks, Midhun


Solution

  • Invalid_grant

    1. Your server’s clock is not in sync with NTP. (Solution: check the server time if its incorrect fix it. )

    If its not that then there is no fix besides asking the user to authenticate again. Possible causes for the refresh token to have expired.

    1. The user has revoked your access.
    2. the refresh token hasn't been used in six months to request a new access token.
    3. The refresh token limit has been exceeded. Applications can request multiple refresh tokens. For example, this is useful in situations where a user wants to install an application on multiple machines. In this case, two refresh tokens are required, one for each installation. When the number of refresh tokens exceeds the limit, older tokens become invalid. If the application attempts to use an invalidated refresh token, an invalid_grant error response is returned. The limit for each unique pair of OAuth 2.0 client and is 25 refresh tokens (note that this limit is subject to change). If the application continues to request refresh tokens for the same Client/Account pair, once the 26th token is issued, the 1st refresh token that was previously issued will become invalid. The 27th requested refresh token would invalidate the 2nd previously issued token and so on.