Objective-C Requires Chilkat v11.0.0+
Objective-C
PayPal: Get a sandbox access token
See more PayPal Examples
Exchange a sandbox REST app client ID and secret for a bearer token on a merchant-controlled backoffice workstation. PayPal supplies its lifetime in seconds. Store the token in a protected credential store; the companion expiry example reads only timing metadata.
Chilkat Objective-C Downloads
#import <CkoHttp.h>
#import <CkoDateTime.h>
#import <CkoHttpResponse.h>
#import <CkoJsonObject.h>
#import <NSString.h>
BOOL success = NO;
// See Unlock Chilkat before making requests.
CkoHttp *http = [[CkoHttp alloc] init];
// Load these values from the credential store on the merchant backoffice workstation.
// Never embed the merchant secret in an app distributed to customers.
http.Login = @"SANDBOX_CLIENT_ID";
http.Password = @"SANDBOX_CLIENT_SECRET";
http.BasicAuth = YES;
CkoDateTime *issued = [[CkoDateTime alloc] init];
[issued SetFromCurrentSystemTime];
CkoHttpResponse *resp = [[CkoHttpResponse alloc] init];
success = [http HttpStr: @"POST" url: @"https://api-m.sandbox.paypal.com/v1/oauth2/token" bodyStr: @"grant_type=client_credentials" charset: @"utf-8" contentType: @"application/x-www-form-urlencoded" response: resp];
if (success != YES) {
NSLog(@"%@%@",@"No HTTP response: ",http.LastErrorText);
return;
}
if (([resp.StatusCode intValue] < 200) || ([resp.StatusCode intValue] >= 300)) {
CkoJsonObject *errorInfo = [[CkoJsonObject alloc] init];
[errorInfo Load: resp.BodyStr];
NSLog(@"%@%d%@%@%@%@",@"HTTP ",[resp.StatusCode intValue],@" ",[errorInfo StringOf: @"error"],@" ",[errorInfo StringOf: @"error_description"]);
NSLog(@"%@%@",@"PayPal debug ID: ",[errorInfo StringOf: @"debug_id"]);
return;
}
CkoJsonObject *result = [[CkoJsonObject alloc] init];
BOOL parsed = [result Load: resp.BodyStr];
if (parsed != YES) {
NSLog(@"%@%d",@"Expected a JSON response; HTTP ",[resp.StatusCode intValue]);
return;
}
NSString *accessToken = [result StringOf: @"access_token"];
int lifetime = [[result IntOf: @"expires_in"] intValue];
if (([result HasMember: @"access_token"] != YES) || (lifetime <= 0)) {
NSLog(@"%@",@"Missing token or lifetime.");
return;
}
// Supply accessToken to Http.AuthToken. Never log the bearer token or client secret.
// Save only timing metadata here, relative to the start of the token request.
CkoJsonObject *timing = [[CkoJsonObject alloc] init];
[timing UpdateString: @"issued_at" value: [issued GetAsTimestamp: NO]];
[timing UpdateInt: @"expires_in" value: [NSNumber numberWithInt: lifetime]];
BOOL savedTiming = [timing WriteFile: @"paypal-token-timing.json"];
if (savedTiming != YES) {
NSLog(@"%@",@"Could not save token timing.");
return;
}
NSLog(@"%@%d",@"Token received; lifetime in seconds: ",lifetime);