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

Xojo Plugin
Dim success As Boolean
success = False

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False

Dim oauth As New Chilkat.OAuth2
oauth.AuthorizationEndpoint = "https://api.schwabapi.com/v1/oauth/authorize"
oauth.TokenEndpoint = "https://api.schwabapi.com/v1/oauth/token"
oauth.ClientId = "APP_KEY"
oauth.ClientSecret = "APP_SECRET"
oauth.UseBasicAuth = True
oauth.CodeChallenge = False

//  The registered HTTPS callback forwards to this desktop's HTTP listener.
oauth.AppCallbackUrl = "https://127.0.0.1:8182/"
oauth.LocalHost = "127.0.0.1"
oauth.ListenPort = 3017
Dim url As String
url = oauth.StartAuth()
If (oauth.LastMethodSuccess <> True) Then
    System.DebugLog("Could not start authorization. Check the callback settings and free the listener port.")
    Return
End If

success = oauth.LaunchBrowser(url)
If (success <> True) Then
    success = oauth.Cancel()
    System.DebugLog("Could not open the system browser.")
    Return
End If

//  Allow time for sign-in, MFA, and account selection.
Dim waitedMs As Int32
waitedMs = 0
While (waitedMs < 300000) And (oauth.AuthFlowState < 3)
    oauth.SleepMs 100
    waitedMs = waitedMs + 100
Wend
Dim state As Int32
state = oauth.AuthFlowState
If (state < 3) Then
    success = oauth.Cancel()
    System.DebugLog("Authorization timed out. Check the HTTPS callback and try again.")
    Return
End If

If (state = 4) Then
    System.DebugLog("Authorization was declined.")
    Return
End If

If (state <> 3) Then
    System.DebugLog("Authorization failed. Check app approval, credentials, and the exact callback URL.")
    Return
End If

Dim reply As New Chilkat.JsonObject
success = reply.Load(oauth.AccessTokenResponse)
If (success <> True) Then
    System.DebugLog("Unexpected token response.")
    Return
End If

If (reply.HasMember("access_token") <> True) Then
    System.DebugLog("The token response contained no access token.")
    Return
End If

Dim access As String
access = reply.StringOf("access_token")
Dim lifetime As Int32
lifetime = reply.IntOf("expires_in")
If ((access = "") Or (lifetime <= 0)) Then
    System.DebugLog("The token response lacks a usable access token or lifetime.")
    Return
End If

If (reply.HasMember("refresh_token") <> True) Then
    System.DebugLog("No refresh token in the authorization response.")
    Return
End If

Dim refresh As String
refresh = reply.StringOf("refresh_token")
If (refresh = "") Then
    System.DebugLog("The refresh token is empty.")
    Return
End If

Dim vault As New Chilkat.Secrets
vault.Location = "local_manager"
vault.AutoSplit = True
Dim entry As New Chilkat.JsonObject
success = entry.UpdateString("appName","SchwabTrader")
success = entry.UpdateString("service","OAuth2")
success = entry.UpdateString("username","personal-desktop")
Dim tokens As New Chilkat.JsonObject
success = tokens.UpdateString("refresh_token",refresh)
Dim now As New Chilkat.CkDateTime
success = now.SetFromCurrentSystemTime()
success = tokens.UpdateString("authorized_at_utc",now.GetAsTimestamp(False))
success = tokens.UpdateString("obtained_at_utc",now.GetAsTimestamp(False))
success = tokens.UpdateString("access_token",access)
success = tokens.UpdateInt("expires_in",lifetime)
success = vault.UpdateSecretJson(entry,tokens)
If (success <> True) Then
    System.DebugLog("Could not save the new credentials. Check the configured secret store.")
    Return
End If

System.DebugLog("Saved credentials. Access token lifetime in seconds: " + Str(lifetime))