Sample code for 30+ languages & platforms
DataFlex Requires Chilkat v10.1.2+

Schwab OAuth 2.0: Authorize a desktop application

See more Schwab Examples

Use a Schwab Trader API app approved for your own desktop application. Register https://127.0.0.1:8182/ as its callback and enter exactly that URL in the code, including the trailing slash. Load your app key and secret from protected configuration. The browser handles Schwab sign-in, account selection, and consent.

Schwab requires HTTPS. Chilkat’s built-in OAuth listener speaks HTTP. For this example, run a loopback HTTPS reverse proxy on port 8182 that forwards the original path and query string to http://127.0.0.1:3017. Use a certificate trusted by the browser for 127.0.0.1. For example, start Caddy with the following Caddyfile and trust its local CA on the desktop:

https://127.0.0.1:8182 {
    bind 127.0.0.1
    tls internal
    reverse_proxy 127.0.0.1:3017
}

Keep callback query strings out of proxy logs. If you already use an application-controlled HTTPS callback relay, register its exact URL instead and forward the authorization response to the initiating desktop. After consent, use Refresh a Schwab access token during the seven-day refresh-token lifetime.

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 hoOauth
    String sUrl
    Integer iWaitedMs
    Integer iState
    Handle hoReply
    String sAccess
    Integer iLifetime
    String sRefresh
    Handle hoVault
    Variant vEntry
    Handle hoEntry
    Variant vTokens
    Handle hoTokens
    Handle hoNow
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

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

    Get Create (RefClass(cComChilkatOAuth2)) To hoOauth
    If (Not(IsComObjectCreated(hoOauth))) Begin
        Send CreateComObject of hoOauth
    End
    Set ComAuthorizationEndpoint Of hoOauth To "https://api.schwabapi.com/v1/oauth/authorize"
    Set ComTokenEndpoint Of hoOauth To "https://api.schwabapi.com/v1/oauth/token"
    Set ComClientId Of hoOauth To "APP_KEY"
    Set ComClientSecret Of hoOauth To "APP_SECRET"
    Set ComUseBasicAuth Of hoOauth To True
    Set ComCodeChallenge Of hoOauth To False

    //  The registered HTTPS callback forwards to this desktop's HTTP listener.
    Set ComAppCallbackUrl Of hoOauth To "https://127.0.0.1:8182/"
    Set ComLocalHost Of hoOauth To "127.0.0.1"
    Set ComListenPort Of hoOauth To 3017
    Get ComStartAuth Of hoOauth To sUrl
    Get ComLastMethodSuccess Of hoOauth To bTemp1
    If (bTemp1 <> True) Begin
        Showln "Could not start authorization. Check the callback settings and free the listener port."
        Procedure_Return
    End

    Get ComLaunchBrowser Of hoOauth sUrl To iSuccess
    If (iSuccess <> True) Begin
        Get ComCancel Of hoOauth To iSuccess
        Showln "Could not open the system browser."
        Procedure_Return
    End

    //  Allow time for sign-in, MFA, and account selection.
    Move 0 To iWaitedMs
    While ((iWaitedMs < 300000) And ((ComAuthFlowState(hoOauth)) < 3))
        Send ComSleepMs To hoOauth 100
        Move (iWaitedMs + 100) To iWaitedMs
    Loop

    Get ComAuthFlowState Of hoOauth To iState
    If (iState < 3) Begin
        Get ComCancel Of hoOauth To iSuccess
        Showln "Authorization timed out. Check the HTTPS callback and try again."
        Procedure_Return
    End

    If (iState = 4) Begin
        Showln "Authorization was declined."
        Procedure_Return
    End

    If (iState <> 3) Begin
        Showln "Authorization failed. Check app approval, credentials, and the exact callback URL."
        Procedure_Return
    End

    Get Create (RefClass(cComChilkatJsonObject)) To hoReply
    If (Not(IsComObjectCreated(hoReply))) Begin
        Send CreateComObject of hoReply
    End
    Get ComAccessTokenResponse Of hoOauth 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

    Get ComHasMember Of hoReply "refresh_token" To bTemp1
    If (bTemp1 <> True) Begin
        Showln "No refresh token in the authorization response."
        Procedure_Return
    End

    Get ComStringOf Of hoReply "refresh_token" To sRefresh
    If (sRefresh = "") Begin
        Showln "The refresh token is empty."
        Procedure_Return
    End

    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 ComUpdateString Of hoTokens "refresh_token" sRefresh To iSuccess
    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 "authorized_at_utc" sTemp1 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