Created
January 9, 2018 06:08
-
-
Save shiningabdul/6d67e102b0ea2ef169866b7f1cb3705f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) { | |
// Use Stripe to charge the user | |
STPAPIClient.shared().createToken(with: payment) { (stripeToken, error) in | |
guard error == nil, let stripeToken = stripeToken else { | |
print(error!) | |
return | |
} | |
let url = URL(string:"http://localhost:3000/pay") | |
guard let apiUrl = url else { | |
print("Error creating url") | |
return | |
} | |
var request = URLRequest(url: apiUrl) | |
request.httpMethod = "POST" | |
request.setValue("application/json", forHTTPHeaderField: "Content-Type") | |
request.setValue("application/json", forHTTPHeaderField: "Accept") | |
// Stripe doesn't allow decimal, so have to convert the amount | |
// into cents by multiplying by 100 | |
let body:[String : Any] = ["stripeToken" : stripeToken.tokenId, | |
"amount" : 300, | |
"description" : "Purchase of a t-shirt"] | |
// Convert the body to JSON | |
try? request.httpBody = JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) | |
// Make an HTTP request to our backend | |
let task = URLSession.shared.dataTask(with: request) {data, response, error in | |
guard error == nil else { | |
print (error!) | |
completion(PKPaymentAuthorizationResult(status: .failure, errors: nil)) | |
return | |
} | |
guard let response = response else { | |
print ("Empty or erronous response") | |
completion(PKPaymentAuthorizationResult(status: .failure, errors: nil)) | |
return | |
} | |
print (response) | |
if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 { | |
// Once the payment is successful, show the user that the purchase has been successful | |
completion(PKPaymentAuthorizationResult(status: .success, errors: nil)) | |
} else { | |
completion(PKPaymentAuthorizationResult(status: .failure, errors: nil)) | |
} | |
} | |
task.resume() | |
} | |
completion(PKPaymentAuthorizationResult(status: .success, errors: nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment