I am using the Google API Client to access the Directory API. My code is as follows:
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('G Suite Directory API');
$client->setScopes(Google_Service_Directory::ADMIN_DIRECTORY_USER);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
.....
//this is where google creates the initial token
}
}
}
My problem revolves around this line:
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
When I initially authorise the client, I get a token.json that contains a refresh token. After an hour, the token expires and it creates a new token. This new token however does not include a refresh token. So it will only ever refresh once and then stop working after 2 hours.
Is there a setting I'm missing?
I had to add $client->setApprovalPrompt('force'); in order for the initial token to include a refresh token.
You should keep reusing the refresh token you got initially to get new access token every hour (which you'd then use in each API request). Refresh tokens generally don't expire.