iOS 集成支付宝支付
SDK下载
集成支付宝首先是去官网下载SDK https://doc.open.alipay.com/doc2/detail.htm?treeId=54&articleId=104509&docType=1 ,这里选择SDK的时候有一个小小的注意点,当APP内集成了阿里百川的SDK时候(比如阿里云推送、OSS服务等),请下载第二种,不然会报UTDID文件冲突错误
环境配置
官方文档关于环境配置已经写得很清楚,我就不赘述了,大家请自行前往查看 https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.2bhZNR&treeId=204&articleId=105295&docType=1,配置URLScheme时尽量特殊,防止与其他APP重复,当然这种概率太小!
API调用说明
- 发起支付:
orderString
由后端统一生成,appScheme
就是环境配置中设置的URLScheme
[[AlipaySDK defaultService] payOrder:orderString
fromScheme:appScheme
callback:^(NSDictionary *resultDic) {
NSLog(@"reslut = %@",resultDic);
}];
- 处理支付结果:在AppDelegate的以下三个方法中调用,这里调用方法单独封装出来
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
if ([url.host isEqualToString:@"safepay"]) {
// 从支付宝打开app
[[DBMobilePay shareInstance] processOrderWithPaymentResultUrl:url];
}
return YES;
}
// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<NSString*, id> *)options {
if ([url.host isEqualToString:@"safepay"]) {
// 支付完成回调
[[DBMobilePay shareInstance] processOrderWithPaymentResultUrl:url];
}
return YES;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
NSString * absoluteUrlStr = [url absoluteString];
if ([url.host isEqualToString:@"safepay"]) {
// 从支付宝打开app
[[DBMobilePay shareInstance] processOrderWithPaymentResultUrl:url];
}
return YES;
}
// 支付跳转支付宝钱包进行支付,处理支付结果
[[AlipaySDK defaultService] processOrderWithPaymentResult:url
standbyCallback:^(NSDictionary *resultDic) {
// NSLog(@"AlipayResult = %@",resultDic);
// 在这里处理支付结果
}];
// 授权跳转支付宝钱包进行支付,处理支付结果
[[AlipaySDK defaultService] processAuth_V2Result:url
standbyCallback:^(NSDictionary *resultDic) {
NSLog(@"result = %@",resultDic);
// 解析 auth code
NSString *result = resultDic[@"result"];
NSString *authCode = nil;
if (result.length > 0) {
NSArray *resultArr = [result componentsSeparatedByString:@"&"];
for (NSString *subResult in resultArr) {
if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
authCode = [subResult substringFromIndex:10];
break;
}
}
}
NSLog(@"授权结果 authCode = %@", authCode?:@"");
}];