iOS APP内嵌Webview跳转支付宝,完成后跳回APP

遇到的问题:

由于项目是通过WKWebView内嵌的h5来实现,而且需要进行支付宝支付。

问题1:点击h5中的支付时,并没有跳转支付宝APP
问题2:支付完成或取消支付时,支付宝APP没有跳转回原APP

解决方法:

问题1:通过WKWebView的代理拦截请求的URL,捕获支付宝的链接:
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *urlStr = navigationAction.request.URL.absoluteString;
    if ([urlStr hasPrefix:@"alipays://"] || [urlStr hasPrefix:@"alipay://"]) {
        NSURL* alipayURL = [self changeURLSchemeStr:urlStr];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:alipayURL options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
                
            }];
        } else {
            // Fallback on earlier versions
            [[UIApplication sharedApplication] openURL:alipayURL];
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
问题2:通过替换拦截的URL中的fromAppUrlScheme值:

拦截到的URL.png

由于拦截到的URL是编码过的,有兴趣的同学可以看下这个在线编码解码工具。

我的方法是:对URL进行解码得到string,取出?之后的字符串,转换成字典,再取出字典中key为fromAppUrlScheme对应的value,再将string中的value替换为自己APP对应的URLSchemes,再将该string进行,URL编码,得到一个新的URL,供跳转。

-(NSURL*)changeURLSchemeStr:(NSString*)urlStr{
    NSString* tmpUrlStr = urlStr.copy;
    if([urlStr containsString:@"fromAppUrlScheme"]) {
        tmpUrlStr = [tmpUrlStr stringByRemovingPercentEncoding];
        NSDictionary* tmpDic = [self dictionaryWithUrlString:tmpUrlStr];
        NSString* tmpValue = [tmpDic valueForKey:@"fromAppUrlScheme"];
        tmpUrlStr = [[tmpUrlStr stringByReplacingOccurrencesOfString:tmpValue withString:@"你对应的URLSchemes"] mutableCopy];
        tmpUrlStr = [[tmpUrlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] mutableCopy];
    }
    NSURL * newURl = [NSURL URLWithString:tmpUrlStr];
    return newURl;
}
-(NSDictionary*)dictionaryWithUrlString:(NSString*)urlStr{
    if(urlStr && urlStr.length&& [urlStr rangeOfString:@"?"].length==1) {
        NSArray *array = [urlStr componentsSeparatedByString:@"?"];
        if(array && array.count==2) {
            NSString*paramsStr = array[1];
            if(paramsStr.length) {
                NSString* paramterStr = [paramsStr stringByRemovingPercentEncoding];
                NSData *jsonData = [paramterStr dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
                return responseDic;
            }
        }
    }
    return nil;
}
对应info.plist设置的URLSchemes.png

你可能感兴趣的:(iOS APP内嵌Webview跳转支付宝,完成后跳回APP)