Swift Requires Chilkat v11.0.0+
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// See Unlock Chilkat before making requests.
let http = CkoHttp()!
// 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 = true
let issued = CkoDateTime()!
issued.setFromCurrentSystemTime()
let resp = CkoHttpResponse()!
success = http.httpStr(verb: "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 != true {
print("No HTTP response: \(http.lastErrorText!)")
return
}
if (resp.statusCode.intValue < 200) || (resp.statusCode.intValue >= 300) {
let errorInfo = CkoJsonObject()!
errorInfo.load(json: resp.bodyStr)
print("HTTP \(resp.statusCode.intValue) \(errorInfo.string(of: "error")!) \(errorInfo.string(of: "error_description")!)")
print("PayPal debug ID: \(errorInfo.string(of: "debug_id")!)")
return
}
let result = CkoJsonObject()!
var parsed: Bool = result.load(json: resp.bodyStr)
if parsed != true {
print("Expected a JSON response; HTTP \(resp.statusCode.intValue)")
return
}
var accessToken: String? = result.string(of: "access_token")
var lifetime: Int = result.int(of: "expires_in").intValue
if (result.hasMember(jsonPath: "access_token") != true) || (lifetime <= 0) {
print("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.
let timing = CkoJsonObject()!
timing.updateString(jsonPath: "issued_at", value: issued.get(asTimestamp: false))
timing.updateInt(jsonPath: "expires_in", value: lifetime)
var savedTiming: Bool = timing.writeFile(path: "paypal-token-timing.json")
if savedTiming != true {
print("Could not save token timing.")
return
}
print("Token received; lifetime in seconds: \(lifetime)")
}