项目中有一个情景是使用H5拉起微信支付,支付成功之后却返回到了safari,经过一番百度之后问题得以解决,记录如下(需要将xxxxxxxxxx替换成自己对应的内容)
注意:
1.拉起支付的url中不能包含redirectUrl参数,否则跳转Safiri并打开该参数对应的链接
2.必须设置Referer,格式为app的scheme + //:的形式
3.原理是利用sheme的形式打开app
以WKWebview为例
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if ([urlString hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"]) { // 处理微信支付
// 注意,此处须与H5沟通好去掉redirectUrl参数
NSDictionary *header = navigationAction.request.allHTTPHeaderFields;
if (header[@"Referer"] && [header[@"Referer"] isEqualToString:@"xxxxxxxxxx://"]) { // 如果已经设置过referer
// 允许跳转
decisionHandler(WKNavigationActionPolicyAllow);
return;
} else {
// 设置referer
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSURL *url = [navigationAction.request URL];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"GET"];
[request setValue:@"xxxxxxxxxx://" forHTTPHeaderField: @"Referer"];
[self.webView loadRequest:request];
});
});
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
}
NSURL *url = navigationAction.request.URL;
// 微信支付协议
if ([url.scheme isEqualToString:@"weixin"]) {
if ([url.host isEqualToString:@"wap"]) {
if ([url.relativePath isEqualToString:@"/pay"]) {
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}
}
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
// 允许跳转
decisionHandler(WKNavigationActionPolicyAllow);
}
然后在target中配置urlType,如下(注仅为xxxxxxxxx部分,不包含://):
tmp4f0f14ec.png
至此,问题解决
网友评论