按照“支付宝开放平台”的“iOS集成流程”进行集成:
https://docs.open.alipay.com/204/105295/
一、项目配置:
1.将支付宝SDK导入到工程项目中:
2.在Build Phases选项卡的Link Binary With Libraries中,增加以下依赖:
3.在Info选项卡的URL Types中,增加回调跳转URL Schemes:
二、代码:
1.在桥接文件中添加AliPay类库:
#import <AlipaySDK/AlipaySDK.h>
//定义跳转本app的URLSchemes(需要跟 Target/Info/URLSchemes 中设置的保持一致)
let kAppScheme = "EducationCloudRAZ"
2.PayViewController.swift:
//添加支付宝支付结果观察者
NotificationCenter.default.addObserver(self, selector: #selector(aliPayNotificationAction(notification:)), name: kAliPayNotificationName, object: nil)
deinit {
NotificationCenter.default.removeObserver(self)
}
//MARK: - 支付宝相关
extension PayViewController {
//调用支付宝API
func aliPay(orderString:String) {
AlipaySDK.defaultService().payOrder(orderString, fromScheme: kAppScheme) { (resultDic:[AnyHashable:Any]?) in
if resultDic != nil {
let resultStatus = resultDic!["resultStatus"] as! String
if resultStatus == "9000" {//支付成功
NotificationCenter.default.post(name: kAliPayNotificationName, object: kAliPaySuccessNotificationObject)
} else {//支付失败
NotificationCenter.default.post(name: kAliPayNotificationName, object: kAliPayFailNotificationObject)
}
}
}
}
//接收到通知的方法-支付宝支付结果
func aliPayNotificationAction(notification:Notification) {
guard notification.object != nil else {
return
}
if let notificationObjectStr = notification.object! as? String {
if (notificationObjectStr == kAliPaySuccessNotificationObject) {
print("支付成功!")
self.title = "支付成功"
self.view.addSubview(self.paySuccessView)
self.view.bringSubview(toFront: self.paySuccessView)
UserTool.share.refreshUserInfo()//刷新用户信息
} else if (notificationObjectStr == kAliPayFailNotificationObject) {
print("支付失败!")
self.title = "支付失败"
self.view.addSubview(self.payFailView)
self.view.bringSubview(toFront: self.payFailView)
} else {
return
}
}
}
}
3.AppDelegate.swift:
//MARK: - 支付宝回调
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
//aliPay支付结果回调
if url.host == "safepay" {
AlipaySDK.defaultService().processOrder(withPaymentResult: url, standbyCallback: { (resultDic: [AnyHashable : Any]?) in
if resultDic != nil {
let resultStatus = resultDic!["resultStatus"] as! String
if resultStatus == "9000" {//支付成功
NotificationCenter.default.post(name: kAliPayNotificationName, object: kAliPaySuccessNotificationObject)
} else {//支付失败
NotificationCenter.default.post(name: kAliPayNotificationName, object: kAliPayFailNotificationObject)
}
}
})
}
return true
}
备注:
(1)PayViewController.swift中支付结果的回调,是当从支付宝H5页面支付之后走的回调(未离开本app)
(2)AppDelegate.swift中支付结果的回调,是当从支付宝app支付之后走的回调(离开了本app)