Skip to content

Instantly share code, notes, and snippets.

@vikdenic
Created February 10, 2015 15:55
Show Gist options
  • Save vikdenic/8b9652352650c1399324 to your computer and use it in GitHub Desktop.
Save vikdenic/8b9652352650c1399324 to your computer and use it in GitHub Desktop.
Retrieve PayPal Access Token via HTTP Request
func httpRequestAccessToken()
{
//Concatenate a String composed of the client and secret id's
let authString = "\(kClientIdSandbox):\(kSecretId)"
let authData = authString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let credentials = "Basic \(authData!.base64EncodedStringWithOptions(nil))"
//Create and set configuration object with necessary Header and value parameters
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = ["Accept": "application/json", "Accept-Language": "en_US", "Content-Type": "application/x-www-form-urlencoded", "Authorization": credentials]
//Create session
let session = NSURLSession(configuration: configuration)
//Create request
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.sandbox.paypal.com/v1/oauth2/token")!)
request.HTTPMethod = "POST"
//Create data for request
let dataString = "grant_type=client_credentials"
let theData = dataString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)
//Creates an HTTP request for the specified URL request object, uploads the provided data object, and calls a handler upon completion.
let task = session.uploadTaskWithRequest(request, fromData: theData) { (data, response, error) -> Void in
if error != nil
{
println(error.localizedDescription)
}
else
{
println("data = \(NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)!)")
}
}
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment