我正在尝试使用Stripe集成Applepay,以便用户能够轻松付款。我使用heroku帐户作为后端服务器。我可以在用户界面上添加ApplePay按钮(请查看我当前的故事板)并尝试配置一个来自底部的弹出结账窗口供用户付款。
My Current UI
但是,即使我点击ApplePaybutton,也没有任何反应。我的目标是在用户点击ApplePay按钮My Goal UI时创建结帐窗口。
我假设按下按钮时应调用func beginPayment()
但不起作用。我怀疑if (stripePublishableKey == "") {
和之后的代码设置不正确。任何帮助,将不胜感激!
import UIKit
import Stripe
enum STPBackendChargeResult {
case success, failure
}
typealias STPTokenSubmissionHandler = (STPBackendChargeResult?, NSError?) -> Void
class ViewController: UIViewController, PKPaymentAuthorizationViewControllerDelegate {
let stripePublishableKey = "my Stripe PublishableKey"
let backendChargeURLString = "my heroku URL"
let appleMerchantId = "my apple merchand Id"
let shirtPrice : UInt = 1000 // this is in cents
override func viewDidLoad() {
super.viewDidLoad()
//This is the method of making the ApplePayButton( didn't use storyboard)
let button = PKPaymentButton(type: .buy, style: .black)
button.addTarget(self, action: #selector(ViewController.beginPayment(_:)), for: .touchUpInside)
let bw = button.frame.size.width
let bh = button.frame.size.height
let vw = view.frame.size.width
let vh = view.frame.size.height
button.frame = CGRect(origin: CGPoint(x: vw/2 - bw/2, y: vh/2 - bh/2), size: button.frame.size)
view.addSubview(button)
}
//This func is supposed to be called when ApplePayButton is pressed.
func beginPayment(_: UIButton) {
if (stripePublishableKey == "") {
let alert = UIAlertController(
title: "You need to set your Stripe publishable key.",
message: "You can find your publishable key at https://dashboard.stripe.com/account/apikeys .",
preferredStyle: UIAlertControllerStyle.alert
)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
return
}
if (appleMerchantId != "") {
let paymentRequest = Stripe.paymentRequest(withMerchantIdentifier: appleMerchantId)
if Stripe.canSubmitPaymentRequest(paymentRequest) {
paymentRequest.paymentSummaryItems = [PKPaymentSummaryItem(label: "Cool shirt", amount: NSDecimalNumber(string: "10.00")), PKPaymentSummaryItem(label: "Stripe shirt shop", amount: NSDecimalNumber(string: "10.00"))]
let paymentAuthVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
paymentAuthVC.delegate = self
self.present(paymentAuthVC, animated: true, completion: nil)
return
}
} else {
print("You should set an appleMerchantId.")
}
}
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping ((PKPaymentAuthorizationStatus) -> Void)) {
let apiClient = STPAPIClient(publishableKey: stripePublishableKey)
apiClient.createToken(with: payment, completion: { (token, error) -> Void in
if error == nil {
if let token = token {
self.createBackendChargeWithToken(token, completion: { (result, error) -> Void in
if result == STPBackendChargeResult.success {
completion(PKPaymentAuthorizationStatus.success)
}
else {
completion(PKPaymentAuthorizationStatus.failure)
}
})
}
}
else {
completion(PKPaymentAuthorizationStatus.failure)
}
})
}
func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
dismiss(animated: true, completion: nil)
}
func createBackendChargeWithToken(_ token: STPToken, completion: @escaping STPTokenSubmissionHandler) {
if backendChargeURLString != "" {
if let url = URL(string: backendChargeURLString + "/charge") {
let session = URLSession(configuration: URLSessionConfiguration.default)
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
let postBody = "stripeToken=\(token.tokenId)&amount=\(shirtPrice)"
let postData = postBody.data(using: String.Encoding.utf8, allowLossyConversion: false)
session.uploadTask(with: request as URLRequest, from: postData, completionHandler: { data, response, error in
let successfulResponse = (response as? HTTPURLResponse)?.statusCode == 200
if successfulResponse && error == nil {
completion(.success, nil)
} else {
if error != nil {
completion(.failure, error as NSError?)
} else {
completion(.failure, NSError(domain: StripeDomain, code: 50, userInfo: [NSLocalizedDescriptionKey: "There was an error communicating with your payment backend."]))
}
}
}).resume()
return
}
}
completion(STPBackendChargeResult.failure, NSError(domain: StripeDomain, code: 50, userInfo: [NSLocalizedDescriptionKey: "You created a token! Its value is \(token.tokenId). Now configure your backend to accept this token and complete a charge."]))
}
}