PowerBuilder Requires Chilkat v11.0.0+
PowerBuilder
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 PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_Token
oleobject loo_Oauth
oleobject loo_Fresh
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
destroy loo_Token
MessageBox("Error","Connecting to COM object failed")
return
end if
li_Success = loo_Token.LoadFile("gmail-token.json")
if li_Success <> 1 then
Write-Debug "Could not read gmail-token.json from the private working directory."
destroy loo_Token
return
end if
if (loo_Token.JsonTypeOf("refresh_token") <> 1) OR (loo_Token.StringOfEquals("refresh_token","",1) = 1) then
Write-Debug "Authorize the account for offline access first."
destroy loo_Token
return
end if
loo_Oauth = create oleobject
li_rc = loo_Oauth.ConnectToNewObject("Chilkat.OAuth2")
loo_Oauth.TokenEndpoint = "https://oauth2.googleapis.com/token"
loo_Oauth.ClientId = "YOUR_DESKTOP_CLIENT_ID"
loo_Oauth.ClientSecret = "YOUR_DESKTOP_CLIENT_SECRET"
loo_Oauth.RefreshToken = loo_Token.StringOf("refresh_token")
li_Success = loo_Oauth.RefreshAccessToken()
if li_Success <> 1 then
Write-Debug "Refresh failed. Check the OAuth client and grant. A revoked or expired grant requires fresh consent."
destroy loo_Token
destroy loo_Oauth
return
end if
loo_Fresh = create oleobject
li_rc = loo_Fresh.ConnectToNewObject("Chilkat.JsonObject")
li_Success = loo_Fresh.Load(loo_Oauth.AccessTokenResponse)
if li_Success <> 1 then
Write-Debug "Could not parse the refresh response."
destroy loo_Token
destroy loo_Oauth
destroy loo_Fresh
return
end if
if (loo_Fresh.JsonTypeOf("access_token") <> 1) OR (loo_Fresh.StringOfEquals("access_token","",1) = 1) then
Write-Debug "The refresh response did not contain an access token."
destroy loo_Token
destroy loo_Oauth
destroy loo_Fresh
return
end if
if (loo_Fresh.JsonTypeOf("refresh_token") <> 1) OR (loo_Fresh.StringOfEquals("refresh_token","",1) = 1) then
loo_Fresh.UpdateString("refresh_token",loo_Token.StringOf("refresh_token"))
end if
if (loo_Fresh.HasMember("scope") <> 1) AND (loo_Token.JsonTypeOf("scope") = 1) then
loo_Fresh.UpdateString("scope",loo_Token.StringOf("scope"))
end if
li_Success = loo_Fresh.WriteFile("gmail-token.json")
if li_Success <> 1 then
Write-Debug "Could not save the refreshed credentials."
destroy loo_Token
destroy loo_Oauth
destroy loo_Fresh
return
end if
Write-Debug "Refreshed the access token."
destroy loo_Token
destroy loo_Oauth
destroy loo_Fresh