Sample code for 30+ languages & platforms
Ruby 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 Ruby Downloads

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

token = Chilkat::CkJsonObject.new()
success = token.LoadFile("gmail-token.json")
if (success != true)
    print "Could not read gmail-token.json from the private working directory." + "\n";
    exit
end

if ((token.JsonTypeOf("refresh_token") != 1) or (token.StringOfEquals("refresh_token","",true) == true))
    print "Authorize the account for offline access first." + "\n";
    exit
end

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 != true)
    print "Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent." + "\n";
    exit
end

fresh = Chilkat::CkJsonObject.new()
success = fresh.Load(oauth.accessTokenResponse())
if (success != true)
    print "Could not parse the refresh response." + "\n";
    exit
end

if ((fresh.JsonTypeOf("access_token") != 1) or (fresh.StringOfEquals("access_token","",true) == true))
    print "The refresh response did not contain an access token." + "\n";
    exit
end

if ((fresh.JsonTypeOf("refresh_token") != 1) or (fresh.StringOfEquals("refresh_token","",true) == true))
    fresh.UpdateString("refresh_token",token.stringOf("refresh_token"))
end

if ((fresh.HasMember("scope") != true) and (token.JsonTypeOf("scope") == 1))
    fresh.UpdateString("scope",token.stringOf("scope"))
end

success = fresh.WriteFile("gmail-token.json")
if (success != true)
    print "Could not save the refreshed credentials." + "\n";
    exit
end

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