需求描述:
因本app是自己测试项目,没有接入支付宝和微信的SDK支付,点击支付按钮时就是传给后台一个订单ID,然后后台接入了支付流程,会直接返回一个URL链接,app调用链接进行网页支付,支付完成后想要拿到支付的状态,从而判断跳转的界面。
第一步:
我们需要传给后台一个订单ID,拿到调起支付宝或者微信支付的网页URL,拿到URL我们app调用
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:htmlStr]];
这个时候能够调起Safari浏览器,我们就可以进行支付了
第二步:
支付完成后,我们会从Safari中返回到app,这个时候需要知道支付是否成功或者失败,这个时候不像app接入支付宝,微信SDK那样,在- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation能够直接拿到支付状态的回调,但我们这里使用的是调起网页支付呀,因此需要另寻途径,拿到回调
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
if ([url.host isEqualToString:@"safepay"]) {
// 支付跳转支付宝钱包进行支付,处理支付结果
[[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
NSLog(@"result = %@",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?:@"");
}];
}else {
return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}
return YES;
}
这个时候我们进去AppDelegate.m中会发现有如下两种方法
- (void)applicationWillEnterForeground:(UIApplication *)application {
NSLog(@"applicationWillEnterForeground----url====%@",application);
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
NSLog(@"applicationDidBecomeActive----url====%@",application);
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
这个时候我们可以在调起网页支付的界面加入通知,然后调用一下查询订单状态的接口即可,这样就能知道是否支付成功!
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
}
- (void)becomeActive{
if (!self.isDefault) {
[self orderDetailRequest];//查询订单支付状态
}
}
这样也有可能其他非支付的地方调用,因此可以加一个isPayJump的BOOL值进行标记。