美文网首页
iOS webView 调起支付宝App无法回调问题

iOS webView 调起支付宝App无法回调问题

作者: CoderGuogt | 来源:发表于2019-10-24 19:21 被阅读0次
场景

由于苹果审核机制的问题,项目中如果使用到了 微信支付 或者 苹果支付,很大可能审核被拒(当然也可能有幸运儿通过),于是便有了通过网页调起支付,在这里记录一下网页调起支付宝App 无法回调到自己的 App 问题以及解决方案,在这里使用的是 UIWebView 进行加载网页。

步骤
  1. 发起订单

    • 根据数据向后台请求一个订单链接过来
  2. 利用 UIWebView 打开链接

    • UIWebView 的代理方法webView:shouldStartLoadWithRequest:navigationType: 监听链接的请求,如果发现请求链接中以 alipay://alipayclient/ 或者是 alipays://alipayclient/ 开头的链接,这个就是网页调起支付宝 App 请求了,这时候我们就需要拦截这个请求

        // 判断请求链接是否是调起支付宝 App 链接
        if ([request.URL.absoluteString hasPrefix:@"alipay://alipayclient/"] ||
            [request.URL.absoluteString hasPrefix:@"alipays://alipayclient/"]) {
            // 对该链接进行数据处理
            NSURLComponents *urlComponent = [NSURLComponents componentsWithURL:request.URL resolvingAgainstBaseURL:NO];
            
            // 解析链接中的参数,是一个json字符串
            NSData *data = [urlComponent.query dataUsingEncoding:NSUTF8StringEncoding];
            
            // 将 json 字符串转换成字典
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            // 进行深拷贝,利用可变字典对fromAppUrlScheme参数进行修改,达到原来链接有 fromAppUrlScheme 参数进行替换,没有进行增加
            NSMutableDictionary *mutableDict = [dict mutableCopy];
            [mutableDict setValue:@"自己App 的 AppURL Scheme" forKey:@"fromAppUrlScheme"];
            
            // 将整理好的字典数据转换成json字符串
            NSData *strData = [NSJSONSerialization dataWithJSONObject:mutableDict options:0 error:nil];
            
            // 放入 urlComponent.query 中,替换原来的参数
            urlComponent.query = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
            // 跳转支付宝App,在这里使用的跳转链接是我们处理过的URL
            BOOL bSucc = [[UIApplication sharedApplication] openURL:urlComponent.URL];
            
            // 如果跳转失败,则跳转itune下载支付宝App
            if (!bSucc) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                                message:@"未检测到支付宝客户端,请安装后重试。"
                                                               delegate:self
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles:@"立即安装", nil];
                [alert show];
            }
            return NO;
        } 
        return YES;
      
    • 支付宝打开支付宝App链接中的fromAppUrlScheme参数是指从哪个App跳转过来的,这时候我们通过传入自己AppUrlScheme,这样在支付宝App中付款成功了,就能回调到我们自己的App,支付宝默认链接传入的是alipays

总结

只要在 UIWebView的开始请求数据的方法中,对链接进行URL拦截,然后对链接中的fromAppUrlScheme参数设置成我们自己App的UrlScheme,这样在支付成功之后就能回调到我们自己的App

相关文章

网友评论

      本文标题:iOS webView 调起支付宝App无法回调问题

      本文链接:https://www.haomeiwen.com/subject/cqwdvctx.html