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

PureBasic
IncludeFile "CkOAuth2.pb"
IncludeFile "CkJsonObject.pb"

Procedure ChilkatExample()

    success.i = 0

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

    success = 0

    tokens.i = CkJsonObject::ckCreate()
    If tokens.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoadFile(tokens,"qa_data/tokens/box_oauth.json")
    If success <> 1
        Debug CkJsonObject::ckLastErrorText(tokens)
        CkJsonObject::ckDispose(tokens)
        ProcedureReturn
    EndIf

    oauth2.i = CkOAuth2::ckCreate()
    If oauth2.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkOAuth2::setCkTokenEndpoint(oauth2, "https://api.box.com/oauth2/token")
    CkOAuth2::setCkClientId(oauth2, "BOX_CLIENT_ID")
    CkOAuth2::setCkClientSecret(oauth2, "BOX_CLIENT_SECRET")
    CkOAuth2::setCkRefreshToken(oauth2, CkJsonObject::ckStringOf(tokens,"refresh_token"))
    success = CkOAuth2::ckRefreshAccessToken(oauth2)
    If success <> 1
        Debug CkOAuth2::ckLastErrorText(oauth2)
        CkJsonObject::ckDispose(tokens)
        CkOAuth2::ckDispose(oauth2)
        ProcedureReturn
    EndIf

    success = CkJsonObject::ckLoad(tokens,CkOAuth2::ckAccessTokenResponse(oauth2))
    If success <> 1
        Debug CkJsonObject::ckLastErrorText(tokens)
        CkJsonObject::ckDispose(tokens)
        CkOAuth2::ckDispose(oauth2)
        ProcedureReturn
    EndIf

    ;  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.
    success = CkJsonObject::ckWriteFile(tokens,"qa_data/tokens/box_oauth.json")
    If success <> 1
        Debug CkJsonObject::ckLastErrorText(tokens)
        CkJsonObject::ckDispose(tokens)
        CkOAuth2::ckDispose(oauth2)
        ProcedureReturn
    EndIf

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


    CkJsonObject::ckDispose(tokens)
    CkOAuth2::ckDispose(oauth2)


    ProcedureReturn
EndProcedure