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

Xbase++
LOCAL nSuccess
LOCAL oToken
LOCAL oOauth
LOCAL oFresh

nSuccess := 0

//  Assumes Chilkat is unlocked. See Global Unlock Sample.

oToken := CreateObject("Chilkat.JsonObject")
nSuccess := oToken:LoadFile("gmail-token.json")
IF (nSuccess != 1)
    ? "Could not read gmail-token.json from the private working directory."
    oToken:destroy()
    RETURN
ENDIF

IF ((oToken:JsonTypeOf("refresh_token") != 1) .OR. (oToken:StringOfEquals("refresh_token", "", 1) == 1))
    ? "Authorize the account for offline access first."
    oToken:destroy()
    RETURN
ENDIF

oOauth := CreateObject("Chilkat.OAuth2")
oOauth:TokenEndpoint := "https://oauth2.googleapis.com/token"
oOauth:ClientId := "YOUR_DESKTOP_CLIENT_ID"
oOauth:ClientSecret := "YOUR_DESKTOP_CLIENT_SECRET"
oOauth:RefreshToken := oToken:StringOf("refresh_token")
nSuccess := oOauth:RefreshAccessToken()
IF (nSuccess != 1)
    ? "Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent."
    oToken:destroy()
    oOauth:destroy()
    RETURN
ENDIF

oFresh := CreateObject("Chilkat.JsonObject")
nSuccess := oFresh:Load(oOauth:AccessTokenResponse)
IF (nSuccess != 1)
    ? "Could not parse the refresh response."
    oToken:destroy()
    oOauth:destroy()
    oFresh:destroy()
    RETURN
ENDIF

IF ((oFresh:JsonTypeOf("access_token") != 1) .OR. (oFresh:StringOfEquals("access_token", "", 1) == 1))
    ? "The refresh response did not contain an access token."
    oToken:destroy()
    oOauth:destroy()
    oFresh:destroy()
    RETURN
ENDIF

IF ((oFresh:JsonTypeOf("refresh_token") != 1) .OR. (oFresh:StringOfEquals("refresh_token", "", 1) == 1))
    oFresh:UpdateString("refresh_token", oToken:StringOf("refresh_token"))
ENDIF

IF ((oFresh:HasMember("scope") != 1) .AND. (oToken:JsonTypeOf("scope") == 1))
    oFresh:UpdateString("scope", oToken:StringOf("scope"))
ENDIF

nSuccess := oFresh:WriteFile("gmail-token.json")
IF (nSuccess != 1)
    ? "Could not save the refreshed credentials."
    oToken:destroy()
    oOauth:destroy()
    oFresh:destroy()
    RETURN
ENDIF

? "Refreshed the access token."

oToken:destroy()
oOauth:destroy()
oFresh:destroy()