Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v10.1.2+

Schwab OAuth 2.0: Authorize a desktop application

See more Schwab Examples

Use a Schwab Trader API app approved for your own desktop application. Register https://127.0.0.1:8182/ as its callback and enter exactly that URL in the code, including the trailing slash. Load your app key and secret from protected configuration. The browser handles Schwab sign-in, account selection, and consent.

Schwab requires HTTPS. Chilkat’s built-in OAuth listener speaks HTTP. For this example, run a loopback HTTPS reverse proxy on port 8182 that forwards the original path and query string to http://127.0.0.1:3017. Use a certificate trusted by the browser for 127.0.0.1. For example, start Caddy with the following Caddyfile and trust its local CA on the desktop:

https://127.0.0.1:8182 {
    bind 127.0.0.1
    tls internal
    reverse_proxy 127.0.0.1:3017
}

Keep callback query strings out of proxy logs. If you already use an application-controlled HTTPS callback relay, register its exact URL instead and forward the authorization response to the initiating desktop. After consent, use Refresh a Schwab access token during the seven-day refresh-token lifetime.

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;
oauth: HCkOAuth2;
url: PWideChar;
waitedMs: Integer;
state: Integer;
reply: HCkJsonObject;
access: PWideChar;
lifetime: Integer;
refresh: PWideChar;
vault: HCkSecrets;
entry: HCkJsonObject;
tokens: HCkJsonObject;
now: HCkDateTime;

begin
success := False;

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

oauth := CkOAuth2_Create();
CkOAuth2_putAuthorizationEndpoint(oauth,'https://api.schwabapi.com/v1/oauth/authorize');
CkOAuth2_putTokenEndpoint(oauth,'https://api.schwabapi.com/v1/oauth/token');
CkOAuth2_putClientId(oauth,'APP_KEY');
CkOAuth2_putClientSecret(oauth,'APP_SECRET');
CkOAuth2_putUseBasicAuth(oauth,True);
CkOAuth2_putCodeChallenge(oauth,False);

//  The registered HTTPS callback forwards to this desktop's HTTP listener.
CkOAuth2_putAppCallbackUrl(oauth,'https://127.0.0.1:8182/');
CkOAuth2_putLocalHost(oauth,'127.0.0.1');
CkOAuth2_putListenPort(oauth,3017);
url := CkOAuth2__startAuth(oauth);
if (CkOAuth2_getLastMethodSuccess(oauth) <> True) then
  begin
    Memo1.Lines.Add('Could not start authorization. Check the callback settings and free the listener port.');
    Exit;
  end;
success := CkOAuth2_LaunchBrowser(oauth,url);
if (success <> True) then
  begin
    CkOAuth2_Cancel(oauth);
    Memo1.Lines.Add('Could not open the system browser.');
    Exit;
  end;
//  Allow time for sign-in, MFA, and account selection.
waitedMs := 0;
while (waitedMs < 300000) and (CkOAuth2_getAuthFlowState(oauth) < 3) do
  begin
    CkOAuth2_SleepMs(oauth,100);
    waitedMs := waitedMs + 100;
  end;

state := CkOAuth2_getAuthFlowState(oauth);
if (state < 3) then
  begin
    CkOAuth2_Cancel(oauth);
    Memo1.Lines.Add('Authorization timed out. Check the HTTPS callback and try again.');
    Exit;
  end;
if (state = 4) then
  begin
    Memo1.Lines.Add('Authorization was declined.');
    Exit;
  end;
if (state <> 3) then
  begin
    Memo1.Lines.Add('Authorization failed. Check app approval, credentials, and the exact callback URL.');
    Exit;
  end;

reply := CkJsonObject_Create();
success := CkJsonObject_Load(reply,CkOAuth2__accessTokenResponse(oauth));
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;
if (CkJsonObject_HasMember(reply,'refresh_token') <> True) then
  begin
    Memo1.Lines.Add('No refresh token in the authorization response.');
    Exit;
  end;
refresh := CkJsonObject__stringOf(reply,'refresh_token');
if (refresh = '') then
  begin
    Memo1.Lines.Add('The refresh token is empty.');
    Exit;
  end;
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();
CkJsonObject_UpdateString(tokens,'refresh_token',refresh);
now := CkDateTime_Create();
CkDateTime_SetFromCurrentSystemTime(now);
CkJsonObject_UpdateString(tokens,'authorized_at_utc',CkDateTime__getAsTimestamp(now,False));
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));

CkOAuth2_Dispose(oauth);
CkJsonObject_Dispose(reply);
CkSecrets_Dispose(vault);
CkJsonObject_Dispose(entry);
CkJsonObject_Dispose(tokens);
CkDateTime_Dispose(now);