Sample code for 30+ languages & platforms
DataFlex Requires Chilkat v11.0.0+

Schwab OAuth 2.0: Refresh an access token

See more Schwab Examples

Run Authorize a desktop application first. Use the same app credentials and saved grant. Schwab documents 30 minutes for the access token and seven days from creation for the refresh token. Schedule refreshes using the returned expires_in and the saved UTC acquisition time. After the refresh window expires, repeat browser sign-in and consent.

The example sends a form-encoded refresh grant with HTTP Basic client authentication. It saves the returned access token and lifetime, adopts a replacement refresh token when supplied, and retains the original grant time. Use the saved access token in the Authorization: Bearer header on Schwab API requests. Coordinate refreshes if multiple processes share the same record.

If you used the earlier file-based example, run desktop authorization once to populate the secret store. After updating your application to use that store, retire the old schwab-access-token.json file.

These examples use the current user’s Windows Credential Manager or Apple Keychain. On Linux or Android, configure a persistent Chilkat Secrets backend for both examples before running them. The local manager on those platforms uses process memory. Use the same secret name for the same app and Schwab authorization. Give each separate authorization its own name.

Schwab Trader API OAuth guide · Register a Schwab app

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoVault
    Variant vEntry
    Handle hoEntry
    Variant vTokens
    Handle hoTokens
    String sRefresh
    Handle hoHttp
    Variant vForm
    Handle hoForm
    Variant vResp
    Handle hoResp
    Handle hoProblem
    Handle hoReply
    String sAccess
    Integer iLifetime
    String sReplacement
    Handle hoNow
    String sTemp1
    Integer iTemp1
    Boolean bTemp1

    Move False To iSuccess

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    Move False To iSuccess

    Get Create (RefClass(cComChilkatSecrets)) To hoVault
    If (Not(IsComObjectCreated(hoVault))) Begin
        Send CreateComObject of hoVault
    End
    Set ComLocation Of hoVault To "local_manager"
    Set ComAutoSplit Of hoVault To True
    Get Create (RefClass(cComChilkatJsonObject)) To hoEntry
    If (Not(IsComObjectCreated(hoEntry))) Begin
        Send CreateComObject of hoEntry
    End
    Get ComUpdateString Of hoEntry "appName" "SchwabTrader" To iSuccess
    Get ComUpdateString Of hoEntry "service" "OAuth2" To iSuccess
    Get ComUpdateString Of hoEntry "username" "personal-desktop" To iSuccess
    Get Create (RefClass(cComChilkatJsonObject)) To hoTokens
    If (Not(IsComObjectCreated(hoTokens))) Begin
        Send CreateComObject of hoTokens
    End
    Get pvComObject of hoEntry to vEntry
    Get pvComObject of hoTokens to vTokens
    Get ComGetSecretJson Of hoVault vEntry vTokens To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not read the token record. Check the store and complete desktop authorization first."
        Procedure_Return
    End

    Get ComHasMember Of hoTokens "refresh_token" To bTemp1
    If (bTemp1 <> True) Begin
        Showln "No saved refresh token. Complete desktop authorization."
        Procedure_Return
    End

    Get ComStringOf Of hoTokens "refresh_token" To sRefresh
    If (sRefresh = "") Begin
        Showln "The saved refresh token is empty. Complete desktop authorization."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatHttp)) To hoHttp
    If (Not(IsComObjectCreated(hoHttp))) Begin
        Send CreateComObject of hoHttp
    End
    Set ComRequireSslCertVerify Of hoHttp To True
    Set ComBasicAuth Of hoHttp To True
    Set ComLogin Of hoHttp To "APP_KEY"
    Set ComPassword Of hoHttp To "APP_SECRET"
    Get Create (RefClass(cComChilkatHttpRequest)) To hoForm
    If (Not(IsComObjectCreated(hoForm))) Begin
        Send CreateComObject of hoForm
    End
    Set ComHttpVerb Of hoForm To "POST"
    Set ComContentType Of hoForm To "application/x-www-form-urlencoded"
    Send ComAddParam To hoForm "grant_type" "refresh_token"
    Send ComAddParam To hoForm "refresh_token" sRefresh
    Get Create (RefClass(cComChilkatHttpResponse)) To hoResp
    If (Not(IsComObjectCreated(hoResp))) Begin
        Send CreateComObject of hoResp
    End
    Get pvComObject of hoForm to vForm
    Get pvComObject of hoResp to vResp
    Get ComHttpReq Of hoHttp "https://api.schwabapi.com/v1/oauth/token" vForm vResp To iSuccess
    If (iSuccess <> True) Begin
        Get ComStatusCode Of hoResp To iTemp1
        If (iTemp1 = 0) Begin
            Showln "No HTTP response. Check connectivity before retrying."
            Procedure_Return
        End

    End

    Get ComStatusCode Of hoResp To iTemp1
    If (iTemp1 <> 200) Begin
        Get Create (RefClass(cComChilkatJsonObject)) To hoProblem
        If (Not(IsComObjectCreated(hoProblem))) Begin
            Send CreateComObject of hoProblem
        End
        Get ComBodyStr Of hoResp To sTemp1
        Get ComLoad Of hoProblem sTemp1 To iSuccess
        Get ComStatusCode Of hoResp To iTemp1
        Showln "Schwab rejected the refresh. HTTP " iTemp1
        If (iSuccess = True) Begin
            Get ComStringOfEquals Of hoProblem "error" "invalid_grant" True To bTemp1
            If (bTemp1 = True) Begin
                Showln "The grant is expired or invalid. Run desktop authorization again."
            End

            Get ComStringOfEquals Of hoProblem "error" "invalid_client" True To bTemp1
            If (bTemp1 = True) Begin
                Showln "Check the app key and secret. If the seven-day grant has expired, authorize again."
            End

        End

        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoReply
    If (Not(IsComObjectCreated(hoReply))) Begin
        Send CreateComObject of hoReply
    End
    Get ComBodyStr Of hoResp To sTemp1
    Get ComLoad Of hoReply sTemp1 To iSuccess
    If (iSuccess <> True) Begin
        Showln "Unexpected token response."
        Procedure_Return
    End

    Get ComHasMember Of hoReply "access_token" To bTemp1
    If (bTemp1 <> True) Begin
        Showln "The token response contained no access token."
        Procedure_Return
    End

    Get ComStringOf Of hoReply "access_token" To sAccess
    Get ComIntOf Of hoReply "expires_in" To iLifetime
    If ((sAccess = "") Or (iLifetime <= 0)) Begin
        Showln "The token response lacks a usable access token or lifetime."
        Procedure_Return
    End

    //  A refresh response can omit the refresh token. Update it only when a new value is supplied.
    Get ComHasMember Of hoReply "refresh_token" To bTemp1
    If (bTemp1 = True) Begin
        Get ComStringOf Of hoReply "refresh_token" To sReplacement
        If (sReplacement <> "") Begin
            Get ComUpdateString Of hoTokens "refresh_token" sReplacement To iSuccess
        End

    End

    Get Create (RefClass(cComCkDateTime)) To hoNow
    If (Not(IsComObjectCreated(hoNow))) Begin
        Send CreateComObject of hoNow
    End
    Get ComSetFromCurrentSystemTime Of hoNow To iSuccess
    Get ComGetAsTimestamp Of hoNow False To sTemp1
    Get ComUpdateString Of hoTokens "obtained_at_utc" sTemp1 To iSuccess
    Get ComUpdateString Of hoTokens "access_token" sAccess To iSuccess
    Get ComUpdateInt Of hoTokens "expires_in" iLifetime To iSuccess
    Get pvComObject of hoEntry to vEntry
    Get pvComObject of hoTokens to vTokens
    Get ComUpdateSecretJson Of hoVault vEntry vTokens To iSuccess
    If (iSuccess <> True) Begin
        Showln "Could not save the new credentials. Check the configured secret store."
        Procedure_Return
    End

    Showln "Saved credentials. Access token lifetime in seconds: " iLifetime


End_Procedure