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

AutoIt
Local $bSuccess = False

;  Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False

$oVault = ObjCreate("Chilkat.Secrets")
$oVault.Location = "local_manager"
$oVault.AutoSplit = True
$oEntry = ObjCreate("Chilkat.JsonObject")
$oEntry.UpdateString("appName","SchwabTrader")
$oEntry.UpdateString("service","OAuth2")
$oEntry.UpdateString("username","personal-desktop")
$oTokens = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oVault.GetSecretJson($oEntry,$oTokens)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not read the token record. Check the store and complete desktop authorization first." & @CRLF)
    Exit
EndIf

If ($oTokens.HasMember("refresh_token") <> True) Then
    ConsoleWrite("No saved refresh token. Complete desktop authorization." & @CRLF)
    Exit
EndIf

Local $sRefresh = $oTokens.StringOf("refresh_token")
If ($sRefresh = "") Then
    ConsoleWrite("The saved refresh token is empty. Complete desktop authorization." & @CRLF)
    Exit
EndIf

$oHttp = ObjCreate("Chilkat.Http")
$oHttp.RequireSslCertVerify = True
$oHttp.BasicAuth = True
$oHttp.Login = "APP_KEY"
$oHttp.Password = "APP_SECRET"
$oForm = ObjCreate("Chilkat.HttpRequest")
$oForm.HttpVerb = "POST"
$oForm.ContentType = "application/x-www-form-urlencoded"
$oForm.AddParam "grant_type","refresh_token"
$oForm.AddParam "refresh_token",$sRefresh
$oResp = ObjCreate("Chilkat.HttpResponse")
$bSuccess = $oHttp.HttpReq("https://api.schwabapi.com/v1/oauth/token",$oForm,$oResp)
If ($bSuccess <> True) Then
    If ($oResp.StatusCode = 0) Then
        ConsoleWrite("No HTTP response. Check connectivity before retrying." & @CRLF)
        Exit
    EndIf

EndIf

If ($oResp.StatusCode <> 200) Then
    $oProblem = ObjCreate("Chilkat.JsonObject")
    $bSuccess = $oProblem.Load($oResp.BodyStr)
    ConsoleWrite("Schwab rejected the refresh. HTTP " & $oResp.StatusCode & @CRLF)
    If ($bSuccess = True) Then
        If ($oProblem.StringOfEquals("error","invalid_grant",True) = True) Then
            ConsoleWrite("The grant is expired or invalid. Run desktop authorization again." & @CRLF)
        EndIf

        If ($oProblem.StringOfEquals("error","invalid_client",True) = True) Then
            ConsoleWrite("Check the app key and secret. If the seven-day grant has expired, authorize again." & @CRLF)
        EndIf

    EndIf

    Exit
EndIf

$oReply = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oReply.Load($oResp.BodyStr)
If ($bSuccess <> True) Then
    ConsoleWrite("Unexpected token response." & @CRLF)
    Exit
EndIf

If ($oReply.HasMember("access_token") <> True) Then
    ConsoleWrite("The token response contained no access token." & @CRLF)
    Exit
EndIf

Local $sAccess = $oReply.StringOf("access_token")
Local $iLifetime = $oReply.IntOf("expires_in")
If (($sAccess = "") Or ($iLifetime <= 0)) Then
    ConsoleWrite("The token response lacks a usable access token or lifetime." & @CRLF)
    Exit
EndIf

;  A refresh response can omit the refresh token. Update it only when a new value is supplied.
If ($oReply.HasMember("refresh_token") = True) Then
Local $sReplacement = $oReply.StringOf("refresh_token")
    If ($sReplacement <> "") Then
        $oTokens.UpdateString("refresh_token",$sReplacement)
    EndIf

EndIf

$oNow = ObjCreate("Chilkat.CkDateTime")
$oNow.SetFromCurrentSystemTime()
$oTokens.UpdateString("obtained_at_utc",$oNow.GetAsTimestamp(False))
$oTokens.UpdateString("access_token",$sAccess)
$oTokens.UpdateInt("expires_in",$iLifetime)
$bSuccess = $oVault.UpdateSecretJson($oEntry,$oTokens)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not save the new credentials. Check the configured secret store." & @CRLF)
    Exit
EndIf

ConsoleWrite("Saved credentials. Access token lifetime in seconds: " & $iLifetime & @CRLF)