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

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false

local vault = chilkat.Secrets.new()
vault.location = "local_manager"
vault.auto_split = true
local entry = chilkat.JsonObject.new()
entry:update_string("appName", "SchwabTrader")
entry:update_string("service", "OAuth2")
entry:update_string("username", "personal-desktop")
local tokens = chilkat.JsonObject.new()
success = vault:get_secret_json(entry, tokens)
if not success then
    print("Could not read the token record. Check the store and complete desktop authorization first.")
    return
end

if not tokens:has_member("refresh_token") then
    print("No saved refresh token. Complete desktop authorization.")
    return
end

local refresh = tokens:string_of("refresh_token")
if refresh == "" then
    print("The saved refresh token is empty. Complete desktop authorization.")
    return
end

local http = chilkat.Http.new()
http.require_ssl_cert_verify = true
http.basic_auth = true
http.login = "APP_KEY"
http.password = "APP_SECRET"
local form = chilkat.HttpRequest.new()
form.http_verb = "POST"
form.content_type = "application/x-www-form-urlencoded"
form:add_param("grant_type", "refresh_token")
form:add_param("refresh_token", refresh)
local resp = chilkat.HttpResponse.new()
success = http:http_req("https://api.schwabapi.com/v1/oauth/token", form, resp)
if not success then
    if resp.status_code == 0 then
        print("No HTTP response. Check connectivity before retrying.")
        return
    end
end

if resp.status_code ~= 200 then
    local problem = chilkat.JsonObject.new()
    success = problem:load(resp.body_str)
    print("Schwab rejected the refresh. HTTP " .. resp.status_code)
    if success then
        if problem:string_of_equals("error", "invalid_grant", true) then
            print("The grant is expired or invalid. Run desktop authorization again.")
        end

        if problem:string_of_equals("error", "invalid_client", true) then
            print("Check the app key and secret. If the seven-day grant has expired, authorize again.")
        end
    end

    return
end

local reply = chilkat.JsonObject.new()
success = reply:load(resp.body_str)
if not success then
    print("Unexpected token response.")
    return
end

if not reply:has_member("access_token") then
    print("The token response contained no access token.")
    return
end

local access = reply:string_of("access_token")
local lifetime = reply:int_of("expires_in")
if (access == "") or (lifetime <= 0) then
    print("The token response lacks a usable access token or lifetime.")
    return
end

-- A refresh response can omit the refresh token. Update it only when a new value is supplied.
if reply:has_member("refresh_token") then
    local replacement = reply:string_of("refresh_token")
    if replacement ~= "" then
        tokens:update_string("refresh_token", replacement)
    end
end

local now = chilkat.DateTime.new()
now:set_from_current_system_time()
tokens:update_string("obtained_at_utc", now:get_as_timestamp(false))
tokens:update_string("access_token", access)
tokens:update_int("expires_in", lifetime)
success = vault:update_secret_json(entry, tokens)
if not success then
    print("Could not save the new credentials. Check the configured secret store.")
    return
end

print("Saved credentials. Access token lifetime in seconds: " .. lifetime)