Reputation: 18338
I have been searching around and reading the php library to figure out the best way to have permanent authentication after the first initial oAuth request.
The code below seems to work fine, but my question is in regards to
$client->refreshToken($refresh_token);
EDIT: I read some more of the code and this does NOT appear to be the correct way. I tried using my refresh token when calling setAccessToken
, but that didn't work either. Is this documented anywhere?
Is this the correct way to set the refresh token? Will this token expire?
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client_id = 'CLIENT ID';
$client_secret = 'CLIENT SECRET';
$refresh_token = 'REFRESH TOKEN';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri('http://redirecturl.com');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setAccessType('offline');
$client->refreshToken($refresh_token);
?>
Upvotes: 0
Views: 4135
Reputation: 486
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!
Upvotes: 1