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

Xbase++
LOCAL nSuccess
LOCAL oVault
LOCAL oEntry
LOCAL oTokens
LOCAL cRefresh
LOCAL oHttp
LOCAL oForm
LOCAL oResp
LOCAL oProblem
LOCAL oReply
LOCAL cAccess
LOCAL nLifetime
LOCAL cReplacement
LOCAL oNow

nSuccess := 0

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
nSuccess := 0

oVault := CreateObject("Chilkat.Secrets")
oVault:Location := "local_manager"
oVault:AutoSplit := 1
oEntry := CreateObject("Chilkat.JsonObject")
oEntry:UpdateString("appName", "SchwabTrader")
oEntry:UpdateString("service", "OAuth2")
oEntry:UpdateString("username", "personal-desktop")
oTokens := CreateObject("Chilkat.JsonObject")
nSuccess := oVault:GetSecretJson(oEntry, oTokens)
IF (nSuccess != 1)
    ? "Could not read the token record. Check the store and complete desktop authorization first."
    oVault:destroy()
    oEntry:destroy()
    oTokens:destroy()
    RETURN
ENDIF

IF (oTokens:HasMember("refresh_token") != 1)
    ? "No saved refresh token. Complete desktop authorization."
    oVault:destroy()
    oEntry:destroy()
    oTokens:destroy()
    RETURN
ENDIF

cRefresh := oTokens:StringOf("refresh_token")
IF (cRefresh == "")
    ? "The saved refresh token is empty. Complete desktop authorization."
    oVault:destroy()
    oEntry:destroy()
    oTokens:destroy()
    RETURN
ENDIF

oHttp := CreateObject("Chilkat.Http")
oHttp:RequireSslCertVerify := 1
oHttp:BasicAuth := 1
oHttp:Login := "APP_KEY"
oHttp:Password := "APP_SECRET"
oForm := CreateObject("Chilkat.HttpRequest")
oForm:HttpVerb := "POST"
oForm:ContentType := "application/x-www-form-urlencoded"
oForm:AddParam("grant_type", "refresh_token")
oForm:AddParam("refresh_token", cRefresh)
oResp := CreateObject("Chilkat.HttpResponse")
nSuccess := oHttp:HttpReq("https://api.schwabapi.com/v1/oauth/token", oForm, oResp)
IF (nSuccess != 1)
    IF (oResp:StatusCode == 0)
        ? "No HTTP response. Check connectivity before retrying."
        oVault:destroy()
        oEntry:destroy()
        oTokens:destroy()
        oHttp:destroy()
        oForm:destroy()
        oResp:destroy()
        RETURN
    ENDIF

ENDIF

IF (oResp:StatusCode != 200)
    oProblem := CreateObject("Chilkat.JsonObject")
    nSuccess := oProblem:Load(oResp:BodyStr)
    ? "Schwab rejected the refresh. HTTP " + Str(oResp:StatusCode)
    IF (nSuccess == 1)
        IF (oProblem:StringOfEquals("error", "invalid_grant", 1) == 1)
            ? "The grant is expired or invalid. Run desktop authorization again."
        ENDIF

        IF (oProblem:StringOfEquals("error", "invalid_client", 1) == 1)
            ? "Check the app key and secret. If the seven-day grant has expired, authorize again."
        ENDIF

    ENDIF

    oVault:destroy()
    oEntry:destroy()
    oTokens:destroy()
    oHttp:destroy()
    oForm:destroy()
    oResp:destroy()
    oProblem:destroy()
    RETURN
ENDIF

oReply := CreateObject("Chilkat.JsonObject")
nSuccess := oReply:Load(oResp:BodyStr)
IF (nSuccess != 1)
    ? "Unexpected token response."
    oVault:destroy()
    oEntry:destroy()
    oTokens:destroy()
    oHttp:destroy()
    oForm:destroy()
    oResp:destroy()
    oProblem:destroy()
    oReply:destroy()
    RETURN
ENDIF

IF (oReply:HasMember("access_token") != 1)
    ? "The token response contained no access token."
    oVault:destroy()
    oEntry:destroy()
    oTokens:destroy()
    oHttp:destroy()
    oForm:destroy()
    oResp:destroy()
    oProblem:destroy()
    oReply:destroy()
    RETURN
ENDIF

cAccess := oReply:StringOf("access_token")
nLifetime := oReply:IntOf("expires_in")
IF ((cAccess == "") .OR. (nLifetime <= 0))
    ? "The token response lacks a usable access token or lifetime."
    oVault:destroy()
    oEntry:destroy()
    oTokens:destroy()
    oHttp:destroy()
    oForm:destroy()
    oResp:destroy()
    oProblem:destroy()
    oReply:destroy()
    RETURN
ENDIF

//  A refresh response can omit the refresh token. Update it only when a new value is supplied.
IF (oReply:HasMember("refresh_token") == 1)
    cReplacement := oReply:StringOf("refresh_token")
    IF (cReplacement != "")
        oTokens:UpdateString("refresh_token", cReplacement)
    ENDIF

ENDIF

oNow := CreateObject("Chilkat.CkDateTime")
oNow:SetFromCurrentSystemTime()
oTokens:UpdateString("obtained_at_utc", oNow:GetAsTimestamp(0))
oTokens:UpdateString("access_token", cAccess)
oTokens:UpdateInt("expires_in", nLifetime)
nSuccess := oVault:UpdateSecretJson(oEntry, oTokens)
IF (nSuccess != 1)
    ? "Could not save the new credentials. Check the configured secret store."
    oVault:destroy()
    oEntry:destroy()
    oTokens:destroy()
    oHttp:destroy()
    oForm:destroy()
    oResp:destroy()
    oProblem:destroy()
    oReply:destroy()
    oNow:destroy()
    RETURN
ENDIF

? "Saved credentials. Access token lifetime in seconds: " + Str(nLifetime)

oVault:destroy()
oEntry:destroy()
oTokens:destroy()
oHttp:destroy()
oForm:destroy()
oResp:destroy()
oProblem:destroy()
oReply:destroy()
oNow:destroy()