Sample code for 30+ languages & platforms
CkPerl Requires Chilkat v11.0.0+

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.

Google documentation

Chilkat CkPerl Downloads

CkPerl
use chilkat();

$success = 0;

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

$token = chilkat::CkJsonObject->new();
$success = $token->LoadFile("gmail-token.json");
if ($success != 1) {
    print "Could not read gmail-token.json from the private working directory." . "\r\n";
    exit;
}

if (($token->JsonTypeOf("refresh_token") != 1) or ($token->StringOfEquals("refresh_token","",1) == 1)) {
    print "Authorize the account for offline access first." . "\r\n";
    exit;
}

$oauth = chilkat::CkOAuth2->new();
$oauth->put_TokenEndpoint("https://oauth2.googleapis.com/token");
$oauth->put_ClientId("YOUR_DESKTOP_CLIENT_ID");
$oauth->put_ClientSecret("YOUR_DESKTOP_CLIENT_SECRET");
$oauth->put_RefreshToken($token->stringOf("refresh_token"));
$success = $oauth->RefreshAccessToken();
if ($success != 1) {
    print "Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent." . "\r\n";
    exit;
}

$fresh = chilkat::CkJsonObject->new();
$success = $fresh->Load($oauth->accessTokenResponse());
if ($success != 1) {
    print "Could not parse the refresh response." . "\r\n";
    exit;
}

if (($fresh->JsonTypeOf("access_token") != 1) or ($fresh->StringOfEquals("access_token","",1) == 1)) {
    print "The refresh response did not contain an access token." . "\r\n";
    exit;
}

if (($fresh->JsonTypeOf("refresh_token") != 1) or ($fresh->StringOfEquals("refresh_token","",1) == 1)) {
    $fresh->UpdateString("refresh_token",$token->stringOf("refresh_token"));
}

if (($fresh->HasMember("scope") != 1) and ($token->JsonTypeOf("scope") == 1)) {
    $fresh->UpdateString("scope",$token->stringOf("scope"));
}

$success = $fresh->WriteFile("gmail-token.json");
if ($success != 1) {
    print "Could not save the refreshed credentials." . "\r\n";
    exit;
}

print "Refreshed the access token." . "\r\n";