swift项目中用到paypal支付,看到网上关于paypal的资料很少,而且基本都是OC的,于是记录下来项目中用到的swift版.
链接参考
object-C paypal集成:
http://www.jianshu.com/p/812d9f010b5b
本文作者项目中paypal使用cocoapods导入的,cocoapods使用方法:
http://www.jianshu.com/p/b64b4fd08d3c
因为paypal目前没有swift版,所以目前会用到桥接文件,
桥接方法链接:
http://www.jianshu.com/p/c399297f3869
假若已经建好桥接文件,在其加入
#import <PayPalMobile.h>
1.在AppDelegate.swift的
didFinishLaunchingWithOptions方法中添加以下代码:
PayPalMobile.initializeWithClientIds(forEnvironments: [PayPalEnvironmentProduction : "你的真实交易模式ClientID",PayPalEnvironmentSandbox : "你的沙盒交易模式ClientID"])
2.在需要paypal的控制器中添加代理
PayPalPaymentDelegate
@IBAction func submitAmountBtn(_ sender: AnyObject) {
guard let num=Double(amountTextField.text ?? "") else {
print("不能为空")
return
}
//print("num ===\(num)")
//为保留小数点后两位
let payamount = NSString(format: "%.2f", num)
//将double转为String
let payamount = NSString(format: "%.2f", payamount1!)
var payment=PayPalPayment()
payment=PayPalPayment.init()
payment.amount = NSDecimalNumber.init(string: payamount as String)
print("payment.amount=\(payment.amount)")
payment.currencyCode="SGD"
payment.shortDescription="CashLess"
payment.intent=PayPalPaymentIntent.sale
if !payment.processable {
// If, for example, the amount was negative or the shortDescription was empty, then
// this payment would not be processable. You would want to handle that here.
}
//设置代理
var paymentViewController = PayPalPaymentViewController()
paymentViewController = PayPalPaymentViewController.init(payment: payment, configuration: payPalConfiguration, delegate: self as PayPalPaymentDelegate)!
self.present(paymentViewController, animated: true, completion: nil)
}
//配置支付相关信息
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
payPalConfiguration=PayPalConfiguration.init()
payPalConfiguration.acceptCreditCards = false
payPalConfiguration.payPalShippingAddressOption = PayPalShippingAddressOption.payPal
}
//设置(测试或正式)环境
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
PayPalMobile.preconnect(withEnvironment: PayPalEnvironmentNoNetwork)
}
实现PayPalPaymentDelegate代理方法
func payPalPaymentDidCancel(_ paymentViewController: PayPalPaymentViewController) {
self.dismiss(animated: true, completion: nil)
}
//pragma mark Proof of payment validation 验证
func payPalPaymentViewController(_ paymentViewController: PayPalPaymentViewController, didComplete completedPayment: PayPalPayment) {
//调用下面的方法用于验证
self.vertifyCompletedPayment(completedPayment: completedPayment)
self.dismiss(animated: true, completion: nil)
}
func vertifyCompletedPayment(completedPayment:PayPalPayment) {
//将该数据传入服务器进行验证
//验证成功后执行更新方法
}
网友评论