Sample code for 30+ languages & platforms
Tcl Requires Chilkat v11.5.0+

Box: Refresh and Save Rotated OAuth Tokens

See more Box Examples

Refresh the user token saved by the authorization example. Box refresh tokens are single-use and expire after 60 days. Serialize refreshes for a token pair and save the replacement immediately; do not run concurrent refresh jobs.

See the Box API guide for setup and the complete workflow.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Requires Chilkat 11.5.0 or later and a previously unlocked Chilkat bundle.
#  See Global Unlock Sample.
#  Guide: Box API Guide.

set success 0

set tokens [new_CkJsonObject]

set success [CkJsonObject_LoadFile $tokens "qa_data/tokens/box_oauth.json"]
if {$success != 1} then {
    puts [CkJsonObject_lastErrorText $tokens]
    delete_CkJsonObject $tokens
    exit
}

set oauth2 [new_CkOAuth2]

CkOAuth2_put_TokenEndpoint $oauth2 "https://api.box.com/oauth2/token"
CkOAuth2_put_ClientId $oauth2 "BOX_CLIENT_ID"
CkOAuth2_put_ClientSecret $oauth2 "BOX_CLIENT_SECRET"
CkOAuth2_put_RefreshToken $oauth2 [CkJsonObject_stringOf $tokens "refresh_token"]
set success [CkOAuth2_RefreshAccessToken $oauth2]
if {$success != 1} then {
    puts [CkOAuth2_lastErrorText $oauth2]
    delete_CkJsonObject $tokens
    delete_CkOAuth2 $oauth2
    exit
}

set success [CkJsonObject_Load $tokens [CkOAuth2_accessTokenResponse $oauth2]]
if {$success != 1} then {
    puts [CkJsonObject_lastErrorText $tokens]
    delete_CkJsonObject $tokens
    delete_CkOAuth2 $oauth2
    exit
}

#  The previous refresh token is now invalid. Preserve this response even if
#  your normal token-store write fails. Do not retry with the old refresh token.
set success [CkJsonObject_WriteFile $tokens "qa_data/tokens/box_oauth.json"]
if {$success != 1} then {
    puts [CkJsonObject_lastErrorText $tokens]
    delete_CkJsonObject $tokens
    delete_CkOAuth2 $oauth2
    exit
}

puts "New access and refresh tokens saved. Do not log their values."

delete_CkJsonObject $tokens
delete_CkOAuth2 $oauth2