I am using the google sheets API with PHP and followed the quick start guide that can be found over here https://developers.google.com/sheets/quickstart/php
When I do authorize properly and store the follow json file in a speicfied path
{
"access_token": "xxxxxxx",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "xxxxxx",
"created": 1472731452
}
After this expires the following gets triggered in my code
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken(
$client->getRefreshToken()
);
$this->filesystem
->put(
self::CREDENTIALS,
json_encode($client->getAccessToken())
);
}
Now my issue is when that code gets triggered it will update my file to something like the following.
{
"access_token": "xxxxxxx",
"token_type": "Bearer",
"expires_in": 3600,
"created": 1472731452
}
As you can see there is no refresh token anymore. When this token expires I start getting the following error
[LogicException]
refresh token must be passed in or set as part of setAccessToken
Which is perfactly understandable because I don't have the refresh token there anymore.
My question is why is the refresh token getting removed? I am call the same methods as the one in the quick start guide https://developers.google.com/sheets/quickstart/php
I am talking specificaly about this part in the guide
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
The
refresh_token
is only provided on the first authorization from the user. Subsequent authorizations, such as the kind you make while testing an OAuth2 integration, will not return therefresh_token
again. :)refresh_token
.Alternatively, you can add the query parameter
prompt=consent
to the OAuth redirect (see Google's OAuth 2.0 for Web Server Applications page).This will prompt the user to authorize the application again and will always return a
refresh_token
.Your refresh token expired because the lifespan set in your code was 3600 seconds only/1 hour.
Using a refresh token
A refresh token is obtained in offline scenarios during the first authorization code exchange. In these cases, your application may obtain a new access token by sending a refresh token to the Google OAuth 2.0 Authorization server.
To obtain a new access token this way, your application sends an HTTPS POST request to https://www.googleapis.com/oauth2/v4/token. The request must include the following parameters:
Such a request will look similar to the following:
Check this SO thread for additional reference. Hope this helps!