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

Objective-C
#import <CkoSecrets.h>
#import <CkoJsonObject.h>
#import <NSString.h>
#import <CkoHttp.h>
#import <CkoHttpRequest.h>
#import <CkoHttpResponse.h>
#import <CkoDateTime.h>

BOOL success = NO;

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

CkoSecrets *vault = [[CkoSecrets alloc] init];
vault.Location = @"local_manager";
vault.AutoSplit = YES;
CkoJsonObject *entry = [[CkoJsonObject alloc] init];
[entry UpdateString: @"appName" value: @"SchwabTrader"];
[entry UpdateString: @"service" value: @"OAuth2"];
[entry UpdateString: @"username" value: @"personal-desktop"];
CkoJsonObject *tokens = [[CkoJsonObject alloc] init];
success = [vault GetSecretJson: entry jsonOut: tokens];
if (success != YES) {
    NSLog(@"%@",@"Could not read the token record. Check the store and complete desktop authorization first.");
    return;
}

if ([tokens HasMember: @"refresh_token"] != YES) {
    NSLog(@"%@",@"No saved refresh token. Complete desktop authorization.");
    return;
}

NSString *refresh = [tokens StringOf: @"refresh_token"];
if (refresh == @"") {
    NSLog(@"%@",@"The saved refresh token is empty. Complete desktop authorization.");
    return;
}

CkoHttp *http = [[CkoHttp alloc] init];
http.RequireSslCertVerify = YES;
http.BasicAuth = YES;
http.Login = @"APP_KEY";
http.Password = @"APP_SECRET";
CkoHttpRequest *form = [[CkoHttpRequest alloc] init];
form.HttpVerb = @"POST";
form.ContentType = @"application/x-www-form-urlencoded";
[form AddParam: @"grant_type" value: @"refresh_token"];
[form AddParam: @"refresh_token" value: refresh];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
success = [http HttpReq: @"https://api.schwabapi.com/v1/oauth/token" request: form response: resp];
if (success != YES) {
    if ([resp.StatusCode intValue] == 0) {
        NSLog(@"%@",@"No HTTP response. Check connectivity before retrying.");
        return;
    }

}

if ([resp.StatusCode intValue] != 200) {
    CkoJsonObject *problem = [[CkoJsonObject alloc] init];
    success = [problem Load: resp.BodyStr];
    NSLog(@"%@%d",@"Schwab rejected the refresh. HTTP ",[resp.StatusCode intValue]);
    if (success == YES) {
        if ([problem StringOfEquals: @"error" value: @"invalid_grant" caseSensitive: YES] == YES) {
            NSLog(@"%@",@"The grant is expired or invalid. Run desktop authorization again.");
        }

        if ([problem StringOfEquals: @"error" value: @"invalid_client" caseSensitive: YES] == YES) {
            NSLog(@"%@",@"Check the app key and secret. If the seven-day grant has expired, authorize again.");
        }

    }

    return;
}

CkoJsonObject *reply = [[CkoJsonObject alloc] init];
success = [reply Load: resp.BodyStr];
if (success != YES) {
    NSLog(@"%@",@"Unexpected token response.");
    return;
}

if ([reply HasMember: @"access_token"] != YES) {
    NSLog(@"%@",@"The token response contained no access token.");
    return;
}

NSString *access = [reply StringOf: @"access_token"];
int lifetime = [[reply IntOf: @"expires_in"] intValue];
if ((access == @"") || (lifetime <= 0)) {
    NSLog(@"%@",@"The token response lacks a usable access token or lifetime.");
    return;
}

//  A refresh response can omit the refresh token. Update it only when a new value is supplied.
if ([reply HasMember: @"refresh_token"] == YES) {
    NSString *replacement = [reply StringOf: @"refresh_token"];
    if (replacement != @"") {
        [tokens UpdateString: @"refresh_token" value: replacement];
    }

}

CkoDateTime *now = [[CkoDateTime alloc] init];
[now SetFromCurrentSystemTime];
[tokens UpdateString: @"obtained_at_utc" value: [now GetAsTimestamp: NO]];
[tokens UpdateString: @"access_token" value: access];
[tokens UpdateInt: @"expires_in" value: [NSNumber numberWithInt: lifetime]];
success = [vault UpdateSecretJson: entry secret: tokens];
if (success != YES) {
    NSLog(@"%@",@"Could not save the new credentials. Check the configured secret store.");
    return;
}

NSLog(@"%@%d",@"Saved credentials. Access token lifetime in seconds: ",lifetime);