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

Visual FoxPro
LOCAL lnSuccess
LOCAL loToken
LOCAL loOauth
LOCAL loFresh

lnSuccess = 0

*  Assumes Chilkat is unlocked. See Global Unlock Sample.

loToken = CreateObject('Chilkat.JsonObject')
lnSuccess = loToken.LoadFile("gmail-token.json")
IF (lnSuccess <> 1) THEN
    ? "Could not read gmail-token.json from the private working directory."
    RELEASE loToken
    CANCEL
ENDIF

IF ((loToken.JsonTypeOf("refresh_token") <> 1) OR (loToken.StringOfEquals("refresh_token","",1) = 1)) THEN
    ? "Authorize the account for offline access first."
    RELEASE loToken
    CANCEL
ENDIF

loOauth = CreateObject('Chilkat.OAuth2')
loOauth.TokenEndpoint = "https://oauth2.googleapis.com/token"
loOauth.ClientId = "YOUR_DESKTOP_CLIENT_ID"
loOauth.ClientSecret = "YOUR_DESKTOP_CLIENT_SECRET"
loOauth.RefreshToken = loToken.StringOf("refresh_token")
lnSuccess = loOauth.RefreshAccessToken()
IF (lnSuccess <> 1) THEN
    ? "Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent."
    RELEASE loToken
    RELEASE loOauth
    CANCEL
ENDIF

loFresh = CreateObject('Chilkat.JsonObject')
lnSuccess = loFresh.Load(loOauth.AccessTokenResponse)
IF (lnSuccess <> 1) THEN
    ? "Could not parse the refresh response."
    RELEASE loToken
    RELEASE loOauth
    RELEASE loFresh
    CANCEL
ENDIF

IF ((loFresh.JsonTypeOf("access_token") <> 1) OR (loFresh.StringOfEquals("access_token","",1) = 1)) THEN
    ? "The refresh response did not contain an access token."
    RELEASE loToken
    RELEASE loOauth
    RELEASE loFresh
    CANCEL
ENDIF

IF ((loFresh.JsonTypeOf("refresh_token") <> 1) OR (loFresh.StringOfEquals("refresh_token","",1) = 1)) THEN
    loFresh.UpdateString("refresh_token",loToken.StringOf("refresh_token"))
ENDIF

IF ((loFresh.HasMember("scope") <> 1) AND (loToken.JsonTypeOf("scope") = 1)) THEN
    loFresh.UpdateString("scope",loToken.StringOf("scope"))
ENDIF

lnSuccess = loFresh.WriteFile("gmail-token.json")
IF (lnSuccess <> 1) THEN
    ? "Could not save the refreshed credentials."
    RELEASE loToken
    RELEASE loOauth
    RELEASE loFresh
    CANCEL
ENDIF

? "Refreshed the access token."

RELEASE loToken
RELEASE loOauth
RELEASE loFresh