Swift
Swift
PayPal -- Get an OAuth 2.0 Access Token
See more PayPal Examples
Demonstrates how to send a request to get a PayPal OAuth2 access token. Sends an HTTP request equivalent to the following:curl https://api.sandbox.paypal.com/v1/oauth2/token \ -H "Accept: application/json" \ -H "Accept-Language: en_US" \ -u "Client-Id:Secret" \ -d "grant_type=client_credentials"
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
let rest = CkoRest()!
// Make the initial connection.
// A single REST object, once connected, can be used for many PayPal REST API calls.
// The auto-reconnect indicates that if the already-established HTTPS connection is closed,
// then it will be automatically re-established as needed.
var bAutoReconnect: Bool = true
success = rest.connect(hostname: "api.sandbox.paypal.com", port: 443, tls: true, autoReconnect: bAutoReconnect)
if success != true {
print("\(rest.lastErrorText!)")
return
}
// Duplicate this request:
// curl https://api.sandbox.paypal.com/v1/oauth2/token \
// -H "Accept: application/json" \
// -H "Accept-Language: en_US" \
// -u "Client-Id:Secret" \
// -d "grant_type=client_credentials"
rest.addHeader(name: "Accept", value: "application/json")
rest.addHeader(name: "Accept-Language", value: "en_US")
// For additional help on where to find your client ID and API secret, see PayPal Client_ID and API_Secret
rest.setAuthBasic(username: "PAYPAL_REST_API_CLIENT_ID", password: "PAYPAL_REST_API_SECRET")
rest.addQueryParam(name: "grant_type", value: "client_credentials")
var responseStr: String? = rest.fullRequestFormUrlEncoded(httpVerb: "POST", uriPath: "/v1/oauth2/token")
if rest.lastMethodSuccess != true {
print("\(rest.lastErrorText!)")
return
}
print("\(rest.lastRequestHeader!)")
// A sample response:
// {
// "scope": "https://api.paypal.com/v1/payments/.* https://api.paypal.com/v1/vault/credit-card https://api.paypal.com/v1/vault/credit-card/.*",
// "access_token": "EEwJ6tF9x5WCIZDYzyZGaz6Khbw7raYRIBV_WxVvgmsG",
// "token_type": "Bearer",
// "app_id": "APP-6XR95014BA15863X",
// "expires_in": 28800
// }
let json = CkoJsonObject()!
json.load(json: responseStr)
json.emitCompact = false
// Check the response status code. A 200 indicates success..
if rest.responseStatusCode.intValue != 200 {
print("\(json.emit()!)")
print("Failed.")
return
}
// Given that the access token expires in approx 8 hours,
// let's record the date/time this token was created.
// This will allow us to know beforehand if the token
// is expired (and we can then fetch a new token).
let dateTime = CkoDateTime()!
var bLocalTime: Bool = false
var dtNow: Int = dateTime.get(asUnixTime: bLocalTime)
json.appendInt(name: "tokenCreateTimeUtc", value: dtNow)
// Examine the access token and save to a file.
print("Access Token: \(json.string(of: "access_token")!)")
print("Full JSON Response:")
print("\(json.emit()!)")
let sbResponse = CkoStringBuilder()!
sbResponse.append(value: json.emit())
var bEmitBom: Bool = false
sbResponse.writeFile(path: "qa_data/tokens/paypal.json", charset: "utf-8", emitBom: bEmitBom)
}