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

Tcl

load ./chilkat.dll

set success 0

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
set success 0

set vault [new_CkSecrets]

CkSecrets_put_Location $vault "local_manager"
CkSecrets_put_AutoSplit $vault 1
set entry [new_CkJsonObject]

CkJsonObject_UpdateString $entry "appName" "SchwabTrader"
CkJsonObject_UpdateString $entry "service" "OAuth2"
CkJsonObject_UpdateString $entry "username" "personal-desktop"
set tokens [new_CkJsonObject]

set success [CkSecrets_GetSecretJson $vault $entry $tokens]
if {$success != 1} then {
    puts "Could not read the token record. Check the store and complete desktop authorization first."
    delete_CkSecrets $vault
    delete_CkJsonObject $entry
    delete_CkJsonObject $tokens
    exit
}

if {[CkJsonObject_HasMember $tokens "refresh_token"] != 1} then {
    puts "No saved refresh token. Complete desktop authorization."
    delete_CkSecrets $vault
    delete_CkJsonObject $entry
    delete_CkJsonObject $tokens
    exit
}

set refresh [CkJsonObject_stringOf $tokens "refresh_token"]
if {$refresh == ""} then {
    puts "The saved refresh token is empty. Complete desktop authorization."
    delete_CkSecrets $vault
    delete_CkJsonObject $entry
    delete_CkJsonObject $tokens
    exit
}

set http [new_CkHttp]

CkHttp_put_RequireSslCertVerify $http 1
CkHttp_put_BasicAuth $http 1
CkHttp_put_Login $http "APP_KEY"
CkHttp_put_Password $http "APP_SECRET"
set form [new_CkHttpRequest]

CkHttpRequest_put_HttpVerb $form "POST"
CkHttpRequest_put_ContentType $form "application/x-www-form-urlencoded"
CkHttpRequest_AddParam $form "grant_type" "refresh_token"
CkHttpRequest_AddParam $form "refresh_token" $refresh
set resp [new_CkHttpResponse]

set success [CkHttp_HttpReq $http "https://api.schwabapi.com/v1/oauth/token" $form $resp]
if {$success != 1} then {
    if {[CkHttpResponse_get_StatusCode $resp] == 0} then {
        puts "No HTTP response. Check connectivity before retrying."
        delete_CkSecrets $vault
        delete_CkJsonObject $entry
        delete_CkJsonObject $tokens
        delete_CkHttp $http
        delete_CkHttpRequest $form
        delete_CkHttpResponse $resp
        exit
    }

}

if {[CkHttpResponse_get_StatusCode $resp] != 200} then {
    set problem [new_CkJsonObject]

    set success [CkJsonObject_Load $problem [CkHttpResponse_bodyStr $resp]]
    puts "Schwab rejected the refresh. HTTP [CkHttpResponse_get_StatusCode $resp]"
    if {$success == 1} then {
        if {[CkJsonObject_StringOfEquals $problem "error" "invalid_grant" 1] == 1} then {
            puts "The grant is expired or invalid. Run desktop authorization again."
        }

        if {[CkJsonObject_StringOfEquals $problem "error" "invalid_client" 1] == 1} then {
            puts "Check the app key and secret. If the seven-day grant has expired, authorize again."
        }

    }

    delete_CkSecrets $vault
    delete_CkJsonObject $entry
    delete_CkJsonObject $tokens
    delete_CkHttp $http
    delete_CkHttpRequest $form
    delete_CkHttpResponse $resp
    delete_CkJsonObject $problem
    exit
}

set reply [new_CkJsonObject]

set success [CkJsonObject_Load $reply [CkHttpResponse_bodyStr $resp]]
if {$success != 1} then {
    puts "Unexpected token response."
    delete_CkSecrets $vault
    delete_CkJsonObject $entry
    delete_CkJsonObject $tokens
    delete_CkHttp $http
    delete_CkHttpRequest $form
    delete_CkHttpResponse $resp
    delete_CkJsonObject $problem
    delete_CkJsonObject $reply
    exit
}

if {[CkJsonObject_HasMember $reply "access_token"] != 1} then {
    puts "The token response contained no access token."
    delete_CkSecrets $vault
    delete_CkJsonObject $entry
    delete_CkJsonObject $tokens
    delete_CkHttp $http
    delete_CkHttpRequest $form
    delete_CkHttpResponse $resp
    delete_CkJsonObject $problem
    delete_CkJsonObject $reply
    exit
}

set access [CkJsonObject_stringOf $reply "access_token"]
set lifetime [CkJsonObject_IntOf $reply "expires_in"]
if {expr [$access == ""]  ||  [$lifetime <= 0]} then {
    puts "The token response lacks a usable access token or lifetime."
    delete_CkSecrets $vault
    delete_CkJsonObject $entry
    delete_CkJsonObject $tokens
    delete_CkHttp $http
    delete_CkHttpRequest $form
    delete_CkHttpResponse $resp
    delete_CkJsonObject $problem
    delete_CkJsonObject $reply
    exit
}

#  A refresh response can omit the refresh token. Update it only when a new value is supplied.
if {[CkJsonObject_HasMember $reply "refresh_token"] == 1} then {
    set replacement [CkJsonObject_stringOf $reply "refresh_token"]
    if {$replacement != ""} then {
        CkJsonObject_UpdateString $tokens "refresh_token" $replacement
    }

}

set now [new_CkDateTime]

CkDateTime_SetFromCurrentSystemTime $now
CkJsonObject_UpdateString $tokens "obtained_at_utc" [CkDateTime_getAsTimestamp $now 0]
CkJsonObject_UpdateString $tokens "access_token" $access
CkJsonObject_UpdateInt $tokens "expires_in" $lifetime
set success [CkSecrets_UpdateSecretJson $vault $entry $tokens]
if {$success != 1} then {
    puts "Could not save the new credentials. Check the configured secret store."
    delete_CkSecrets $vault
    delete_CkJsonObject $entry
    delete_CkJsonObject $tokens
    delete_CkHttp $http
    delete_CkHttpRequest $form
    delete_CkHttpResponse $resp
    delete_CkJsonObject $problem
    delete_CkJsonObject $reply
    delete_CkDateTime $now
    exit
}

puts "Saved credentials. Access token lifetime in seconds: $lifetime"

delete_CkSecrets $vault
delete_CkJsonObject $entry
delete_CkJsonObject $tokens
delete_CkHttp $http
delete_CkHttpRequest $form
delete_CkHttpResponse $resp
delete_CkJsonObject $problem
delete_CkJsonObject $reply
delete_CkDateTime $now