最近项目碰到一个不接入微信、支付宝SDK做支付的功能,简单的说的就是用H5调起微信、支付支付。支付完成后返回app。
注:没有安装支付宝app,可以使用网页版支付。
找了好多资料,其实原理都一样,就是拦截wkwebview、webview的请求,对请求做一些调整。实现起来也不难,这里做个记录。
- (void)webView:(WKWebView*)webViewdecidePolicyForNavigationAction:(WKNavigationAction*)navigationActiondecisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler {
NSString*str = webView.URL.absoluteString;
// 拦截支付请求
if ([str containsString:@"https://wx.tenpay.com"] || [str containsString:@"https://mclient.alipay"]) {
NSDictionary*dic = navigationAction.request.allHTTPHeaderFields;
NSString*refer = dic[@"Referer"];
if(refer ==nil) {
dispatch_async(dispatch_get_main_queue(), ^{
NSURL*url = navigationAction.request.URL;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
request.HTTPMethod=@"GET";
[requestaddValue:@"你的app标识"forHTTPHeaderField:@"Referer"];
// 设置app标识是为了支付完成可以返回app,也就ios 应用间的跳转,具体可以了解下URL Scheme。iOS 9以后,可以使用通用链接实现app间的调整(通讯)。
[webViewloadRequest: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(@available(iOS10.0, *)) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
}];
}else{
[[UIApplicationsharedApplication]openURL:url];
}
}
}
decisionHandler(WKNavigationActionPolicyAllow);
return;
}
// 调起支付支付
if ([str containsString:@"https://mclient.alipay"]) {
if(@available(iOS10.0, *)) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
}];
}else{
[[UIApplication sharedApplication] openURL:url];
}
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
decisionHandler(WKNavigationActionPolicyAllow);
}