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

Delphi DLL
var
success: Boolean;
vault: HCkSecrets;
entry: HCkJsonObject;
tokens: HCkJsonObject;
refresh: PWideChar;
http: HCkHttp;
form: HCkHttpRequest;
resp: HCkHttpResponse;
problem: HCkJsonObject;
reply: HCkJsonObject;
access: PWideChar;
lifetime: Integer;
replacement: PWideChar;
now: HCkDateTime;

begin
success := False;

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

vault := CkSecrets_Create();
CkSecrets_putLocation(vault,'local_manager');
CkSecrets_putAutoSplit(vault,True);
entry := CkJsonObject_Create();
CkJsonObject_UpdateString(entry,'appName','SchwabTrader');
CkJsonObject_UpdateString(entry,'service','OAuth2');
CkJsonObject_UpdateString(entry,'username','personal-desktop');
tokens := CkJsonObject_Create();
success := CkSecrets_GetSecretJson(vault,entry,tokens);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not read the token record. Check the store and complete desktop authorization first.');
    Exit;
  end;
if (CkJsonObject_HasMember(tokens,'refresh_token') <> True) then
  begin
    Memo1.Lines.Add('No saved refresh token. Complete desktop authorization.');
    Exit;
  end;
refresh := CkJsonObject__stringOf(tokens,'refresh_token');
if (refresh = '') then
  begin
    Memo1.Lines.Add('The saved refresh token is empty. Complete desktop authorization.');
    Exit;
  end;
http := CkHttp_Create();
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putBasicAuth(http,True);
CkHttp_putLogin(http,'APP_KEY');
CkHttp_putPassword(http,'APP_SECRET');
form := CkHttpRequest_Create();
CkHttpRequest_putHttpVerb(form,'POST');
CkHttpRequest_putContentType(form,'application/x-www-form-urlencoded');
CkHttpRequest_AddParam(form,'grant_type','refresh_token');
CkHttpRequest_AddParam(form,'refresh_token',refresh);
resp := CkHttpResponse_Create();
success := CkHttp_HttpReq(http,'https://api.schwabapi.com/v1/oauth/token',form,resp);
if (success <> True) then
  begin
    if (CkHttpResponse_getStatusCode(resp) = 0) then
      begin
        Memo1.Lines.Add('No HTTP response. Check connectivity before retrying.');
        Exit;
      end;
  end;
if (CkHttpResponse_getStatusCode(resp) <> 200) then
  begin
    problem := CkJsonObject_Create();
    success := CkJsonObject_Load(problem,CkHttpResponse__bodyStr(resp));
    Memo1.Lines.Add('Schwab rejected the refresh. HTTP ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
    if (success = True) then
      begin
        if (CkJsonObject_StringOfEquals(problem,'error','invalid_grant',True) = True) then
          begin
            Memo1.Lines.Add('The grant is expired or invalid. Run desktop authorization again.');
          end;
        if (CkJsonObject_StringOfEquals(problem,'error','invalid_client',True) = True) then
          begin
            Memo1.Lines.Add('Check the app key and secret. If the seven-day grant has expired, authorize again.');
          end;
      end;
    Exit;
  end;
reply := CkJsonObject_Create();
success := CkJsonObject_Load(reply,CkHttpResponse__bodyStr(resp));
if (success <> True) then
  begin
    Memo1.Lines.Add('Unexpected token response.');
    Exit;
  end;
if (CkJsonObject_HasMember(reply,'access_token') <> True) then
  begin
    Memo1.Lines.Add('The token response contained no access token.');
    Exit;
  end;
access := CkJsonObject__stringOf(reply,'access_token');
lifetime := CkJsonObject_IntOf(reply,'expires_in');
if ((access = '') or (lifetime <= 0)) then
  begin
    Memo1.Lines.Add('The token response lacks a usable access token or lifetime.');
    Exit;
  end;
//  A refresh response can omit the refresh token. Update it only when a new value is supplied.
if (CkJsonObject_HasMember(reply,'refresh_token') = True) then
  begin
    replacement := CkJsonObject__stringOf(reply,'refresh_token');
    if (replacement <> '') then
      begin
        CkJsonObject_UpdateString(tokens,'refresh_token',replacement);
      end;
  end;
now := CkDateTime_Create();
CkDateTime_SetFromCurrentSystemTime(now);
CkJsonObject_UpdateString(tokens,'obtained_at_utc',CkDateTime__getAsTimestamp(now,False));
CkJsonObject_UpdateString(tokens,'access_token',access);
CkJsonObject_UpdateInt(tokens,'expires_in',lifetime);
success := CkSecrets_UpdateSecretJson(vault,entry,tokens);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not save the new credentials. Check the configured secret store.');
    Exit;
  end;
Memo1.Lines.Add('Saved credentials. Access token lifetime in seconds: ' + IntToStr(lifetime));

CkSecrets_Dispose(vault);
CkJsonObject_Dispose(entry);
CkJsonObject_Dispose(tokens);
CkHttp_Dispose(http);
CkHttpRequest_Dispose(form);
CkHttpResponse_Dispose(resp);
    CkJsonObject_Dispose(problem);
CkJsonObject_Dispose(reply);
CkDateTime_Dispose(now);