PHP Requires Chilkat v11.0.0+
PHP
Refresh a Gmail OAuth access token
See more GMail REST API Examples
Use the refresh token and the same Desktop app client that issued it. Run in the private directory used by the authorization example. Preserve the refresh token if Google omits it from the response. Refreshing continues the existing grant. Request additional scopes through interactive authorization.
Chilkat PHP Downloads
<?php
use Chilkat2\JsonObject;
use Chilkat2\OAuth2;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$token = new JsonObject();
try {
$token->LoadFile('gmail-token.json');
} catch (\Chilkat2\Exception $e) {
echo "Could not read gmail-token.json from the private working directory.\n";
exit;
}
if (($token->JsonTypeOf('refresh_token') != 1) || ($token->StringOfEquals('refresh_token', '', true))) {
echo "Authorize the account for offline access first.\n";
exit;
}
$oauth = new OAuth2();
$oauth->TokenEndpoint = 'https://oauth2.googleapis.com/token';
$oauth->ClientId = 'YOUR_DESKTOP_CLIENT_ID';
$oauth->ClientSecret = 'YOUR_DESKTOP_CLIENT_SECRET';
$oauth->RefreshToken = $token->StringOf('refresh_token');
try {
$oauth->RefreshAccessToken();
} catch (\Chilkat2\Exception $e) {
echo "Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent.\n";
exit;
}
$fresh = new JsonObject();
try {
$fresh->Load($oauth->AccessTokenResponse);
} catch (\Chilkat2\Exception $e) {
echo "Could not parse the refresh response.\n";
exit;
}
if (($fresh->JsonTypeOf('access_token') != 1) || ($fresh->StringOfEquals('access_token', '', true))) {
echo "The refresh response did not contain an access token.\n";
exit;
}
if (($fresh->JsonTypeOf('refresh_token') != 1) || ($fresh->StringOfEquals('refresh_token', '', true))) {
$fresh->UpdateString('refresh_token', $token->StringOf('refresh_token'));
}
if ((!$fresh->HasMember('scope')) && ($token->JsonTypeOf('scope') == 1)) {
$fresh->UpdateString('scope', $token->StringOf('scope'));
}
try {
$fresh->WriteFile('gmail-token.json');
} catch (\Chilkat2\Exception $e) {
echo "Could not save the refreshed credentials.\n";
exit;
}
echo "Refreshed the access token.\n";