php - Google API - Refresh Token


I'm trying to get a new access_token after he expired. I already keep in the bank the information I receive in return the first client access:

{"access_token": "TOKEN", "refresh_token": "TOKEN", "token_type", "Bearer", "expires_in": 3600, "created ": 1320790426}

After that token expires I need to apply for a new one, I am doing this way:

$client = new Google_Client();

$token['access_token']  = $db->dados[0]['use_access_token'];
$token['refresh_token'] = $db->dados[0]['use_refresh_token'];
$token['token_type']    = $db->dados[0]['use_token_type'];
$token['expires_in']    = $db->dados[0]['use_expires_in'];
$token['created']       = $db->dados[0]['use_created'];


if ($client->isAccessTokenExpired()) {
    echo "Expired !";
    //$accessToken = $client->authenticate($authCode);
} else {

The problem is that always returns this error: Error refreshing the OAuth2 token, message:

{ "error" : "invalid_grant" }




My failure was because I messed up my own clientID, but I'm posting this script here anyways because it took me forever to find the correct answer that was small, efficient and effective (the below is strictly after a token and refresh have been already saved to your db):

$client = new Google_Client();
$client->setApplicationName('APP NAME');
// my app is for google calendar.

$access_token_from_db = 'XXXXXX';
$refresh_token_from_db = 'XXXXX';
$_tokenArray['access_token'] = $access_token_from_db

//must be set as json
$client->setAccessToken( json_encode($_tokenArray) );

//check if token expired:
if ( $client->isAccessTokenExpired() ) :
    $new_access_token = $client->getAccessToken();

    //now save your new access token to your db




    echo $newtoken."</br>";

People are also looking for solutions to the problem: php - how to delete a row in database using codeigniter


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.