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

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.CkDateTime,
  Chilkat.HttpResponse,
  Chilkat.HttpRequest,
  Chilkat.JsonObject,
  Chilkat.Secrets,
  Chilkat.Http;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  vault: TSecrets;
  entry: TJsonObject;
  tokens: TJsonObject;
  refresh: string;
  http: THttp;
  form: THttpRequest;
  resp: THttpResponse;
  problem: TJsonObject;
  reply: TJsonObject;
  access: string;
  lifetime: Integer;
  replacement: string;
  now: TCkDateTime;

begin
  success := False;

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

  vault := TSecrets.Create;
  vault.Location := 'local_manager';
  vault.AutoSplit := True;
  entry := TJsonObject.Create;
  entry.UpdateString('appName','SchwabTrader');
  entry.UpdateString('service','OAuth2');
  entry.UpdateString('username','personal-desktop');
  tokens := TJsonObject.Create;
  success := vault.GetSecretJson(entry,tokens);
  if (success <> True) then
    begin
      WriteLn('Could not read the token record. Check the store and complete desktop authorization first.');
      Exit;
    end;
  if (tokens.HasMember('refresh_token') <> True) then
    begin
      WriteLn('No saved refresh token. Complete desktop authorization.');
      Exit;
    end;
  refresh := tokens.StringOf('refresh_token');
  if (refresh = '') then
    begin
      WriteLn('The saved refresh token is empty. Complete desktop authorization.');
      Exit;
    end;
  http := THttp.Create;
  http.RequireSslCertVerify := True;
  http.BasicAuth := True;
  http.Login := 'APP_KEY';
  http.Password := 'APP_SECRET';
  form := THttpRequest.Create;
  form.HttpVerb := 'POST';
  form.ContentType := 'application/x-www-form-urlencoded';
  form.AddParam('grant_type','refresh_token');
  form.AddParam('refresh_token',refresh);
  resp := THttpResponse.Create;
  success := http.HttpReq('https://api.schwabapi.com/v1/oauth/token',form,resp);
  if (success <> True) then
    begin
      if (resp.StatusCode = 0) then
        begin
          WriteLn('No HTTP response. Check connectivity before retrying.');
          Exit;
        end;
    end;
  if (resp.StatusCode <> 200) then
    begin
      problem := TJsonObject.Create;
      success := problem.Load(resp.BodyStr);
      WriteLn('Schwab rejected the refresh. HTTP ' + resp.StatusCode);
      if (success = True) then
        begin
          if (problem.StringOfEquals('error','invalid_grant',True) = True) then
            begin
              WriteLn('The grant is expired or invalid. Run desktop authorization again.');
            end;
          if (problem.StringOfEquals('error','invalid_client',True) = True) then
            begin
              WriteLn('Check the app key and secret. If the seven-day grant has expired, authorize again.');
            end;
        end;
      Exit;
    end;
  reply := TJsonObject.Create;
  success := reply.Load(resp.BodyStr);
  if (success <> True) then
    begin
      WriteLn('Unexpected token response.');
      Exit;
    end;
  if (reply.HasMember('access_token') <> True) then
    begin
      WriteLn('The token response contained no access token.');
      Exit;
    end;
  access := reply.StringOf('access_token');
  lifetime := reply.IntOf('expires_in');
  if ((access = '') or (lifetime <= 0)) then
    begin
      WriteLn('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 (reply.HasMember('refresh_token') = True) then
    begin
      replacement := reply.StringOf('refresh_token');
      if (replacement <> '') then
        begin
          tokens.UpdateString('refresh_token',replacement);
        end;
    end;
  now := TCkDateTime.Create;
  now.SetFromCurrentSystemTime();
  tokens.UpdateString('obtained_at_utc',now.GetAsTimestamp(False));
  tokens.UpdateString('access_token',access);
  tokens.UpdateInt('expires_in',lifetime);
  success := vault.UpdateSecretJson(entry,tokens);
  if (success <> True) then
    begin
      WriteLn('Could not save the new credentials. Check the configured secret store.');
      Exit;
    end;
  WriteLn('Saved credentials. Access token lifetime in seconds: ' + lifetime);


  vault.Free;
  entry.Free;
  tokens.Free;
  http.Free;
  form.Free;
  resp.Free;
      problem.Free;
  reply.Free;
  now.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.