[Php] How to refresh token with Google API client?


Answers

The problem is in the refresh token:

[refresh_token] => 1\/lov250YQTMCC9LRQbE6yMv-FiX_Offo79UXimV8kvwY

When a string with a '/' gets json encoded, It is escaped with a '\', hence you need to remove it.

The refresh token in your case should be:

1/lov250YQTMCC9LRQbE6yMv-FiX_Offo79UXimV8kvwY

What i'm assuming you've done is that you've printed the json string which google sent back and copied and pasted the token into your code because if you json_decode it then it will correctly remove the '\' for you!

Question

I've been playing around with the Google Analytics API (V3) and have run into som errors. Firstly, everything is set up correct and worked with my testing account. But when I want to grab data from another profile ID (Same Google Accont/GA Account) I get an 403 Error. The strange thing is that data from some GA accounts will return data whilst other generate this error.

I've revoked the token and authenticated one more time, and now it seems like I can grab data from all of my accounts. Problem solved? Not. As the access key will expire, I will run into the same issue again.

If I have understood things right, one could use the resfreshToken to get a new authenticationTooken.

The problem is, when I run:

$client->refreshToken(refresh_token_key) 

the following error is returned:

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

I’ve checked the code behind the refreshToken method and tracked the request back to the “apiOAuth2.php” file. All parameters are sent correctly. The grant_type is hard coded to ‘refresh_token’ within the method, so it’s hard for me to understand what’s wrong. The parameter array looks like this:

Array ( [client_id] => *******-uqgau8uo1l96bd09eurdub26c9ftr2io.apps.googleusercontent.com [client_secret] => ******** [refresh_token] => 1\/lov250YQTMCC9LRQbE6yMv-FiX_Offo79UXimV8kvwY [grant_type] => refresh_token )

The procedure is as follows.

$client = new apiClient();
$client->setClientId($config['oauth2_client_id']);
$client->setClientSecret($config['oauth2_client_secret']);
$client->setRedirectUri($config['oauth2_redirect_uri']);
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
$client->setState('offline');

$client->setAccessToken($config['token']); // The access JSON object.

$client->refreshToken($config['refreshToken']); // Will return error here

Is this a bug, or have I completely misunderstood something?




here is the snippet to set token, before that make sure the access type should be set to offline

if (isset($_GET['code'])) {
  $client->authenticate();
  $_SESSION['access_token'] = $client->getAccessToken();
}

To refresh token

$google_token= json_decode($_SESSION['access_token']);
$client->refreshToken($google_token->refresh_token);

this will refresh your token, you have to update it in session for that you can do

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



Go to your Google API Console ( https://code.google.com/apis/console/ ) and revoke your Client Secret under Client ID for installed applications.

Be sure to also update your code with the new Client Secret




Authentication on google: OAuth2 keeps returning 'invalid_grant'

You should reuse the access token you get after the first successful authentication. You will get an invalid_grant error if your previous token has not expired yet. Cache it somewhere so you can reuse it.




Google Drive API refresh token — Is this the correct way to authenticate with php client library?

I believe your call to:

$client->refreshToken($refresh_token);

is what is generating your HTTP request to Google to issue you another access token. It is not setting your refresh token.

You need to store your access token & refresh token in a DB or session that you obtained on your very first request. Google issues limited refresh tokens.

There is some code here regarding how to assess whether your token has expired or not (3rd answer down):

How to refresh token with Google API client?

Once your access token has expired (1 hr), then you make the call to:

$client->refreshToken($refresh_token);

And store the resulting new access token & expiration data. You essentially repeat this process every hour.

As an FYI: Theoretically, refresh tokens "never" expire. I have found in my own coding that this is not true. After extended periods of not hitting the Google API (weekend), I have gotten the dreaded:

{
"error": "invalid_token",
"error_description": "Invalid Value"
}

I have found that I have to code around this by wiping out the access & refresh tokens (resetting the session or DB), and make a programmatic call to revoke the expired access token (ruby).

GET 'https://accounts.google.com/o/oauth2/revoke?token=' + access_token

You must then start the entire OAuth2 flow again from scratch. Hopefully this problem won't plague you as it has me!




I got this error before because I was trying to authenticate twice.

Since you have this line:

if (isset($_GET['code']))

It will try to authenticate when the code is in the query string regardless of whether you're already authenticated. Try checking whether the SESSION token is present before trying to (re)authenticate.