php - Google API - Refresh Token

480

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();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
$client->setAccessType('offline');

$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'];

$client->setAccessToken(json_encode($token));

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

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

{ "error" : "invalid_grant" }

495

Answer

Solution:

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');
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setAccessType('offline'); 
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));
// 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() ) :
    $client->refreshToken($refresh_token_from_db);
    $new_access_token = $client->getAccessToken();

    //now save your new access token to your db

endif;
261

Answer

Solution:

    $client->refreshToken($refreshToken);
    $newtoken=$client->getAccessToken();
    echo $newtoken."</br>";

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

Source

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.