Sample code for 30+ languages & platforms
Tcl

Refresh a Square OAuth2 Access Token

See more Square Examples

Refreshes a Square OAuth2 access token. When an access token expires, HTTPS requests will receive a 401 status response indicating failure. When this happens, your application can run this code to refresh the access token, and then retry the request using the new access token. Refreshing an access token does not need user interaction (i.e. does not need to display a browser to have the user interactive authorize access).

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.

# It is assumed we previously obtained an OAuth2 access token.
# This example loads the JSON access token file 
# saved by this example: Get Square OAuth2 Access Token

set jsonToken [new_CkJsonObject]

set success [CkJsonObject_LoadFile $jsonToken "qa_data/tokens/square.json"]
if {$success != 1} then {
    puts "Failed to load square.json"
    delete_CkJsonObject $jsonToken
    exit
}

# The access token JSON looks like this:

# {
#   "access_token": "EAAAE...depV",
#   "token_type": "bearer",
#   "expires_at": "2020-09-04T23:30:18Z",
#   "merchant_id": "MLQA83866KSR5",
#   "refresh_token": "EQAAEE...jeVfD6MV"
# }

set oauth2 [new_CkOAuth2]

CkOAuth2_put_TokenEndpoint $oauth2 "https://connect.squareupsandbox.com/oauth2/token"

# Replace these with actual values.
CkOAuth2_put_ClientId $oauth2 "APPLICATION_ID"
CkOAuth2_put_ClientSecret $oauth2 "APPLICATION_SECRET"

# Get the "refresh_token"
CkOAuth2_put_RefreshToken $oauth2 [CkJsonObject_stringOf $jsonToken "refresh_token"]

# Send the HTTP POST to refresh the access token..
set success [CkOAuth2_RefreshAccessToken $oauth2]
if {$success != 1} then {
    puts [CkOAuth2_lastErrorText $oauth2]
    delete_CkJsonObject $jsonToken
    delete_CkOAuth2 $oauth2
    exit
}

CkJsonObject_UpdateString $jsonToken "access_token" [CkOAuth2_accessToken $oauth2]

# Save the new JSON access token response to a file.
set sbJson [new_CkStringBuilder]

CkJsonObject_put_EmitCompact $jsonToken 0
CkJsonObject_EmitSb $jsonToken $sbJson
CkStringBuilder_WriteFile $sbJson "qa_data/tokens/square.json" "utf-8" 0

puts "OAuth2 token refreshed!"
puts "New Access Token = [CkOAuth2_accessToken $oauth2]"

delete_CkJsonObject $jsonToken
delete_CkOAuth2 $oauth2
delete_CkStringBuilder $sbJson