![](https://img.haomeiwen.com/i2420391/768e74cb568924b5.jpeg)
最近,app嵌入了一个H5模块,H5里面加入了微信支付的功能。在发起微信支付的时候是通过weixin://的协议方式的,在UIWebView中可以正常调起微信发起支付,但支付成功会跳转Safari浏览器然后加载支付成功页面,WKWebView不能识别这种协议,不会跳转微信。
拦截H5微信支付请求
-
配置 URL Schemes,用于跳回App
在info.plist中添加一个URL Schemes,用于在微信支付完成返回app。
WeChateafef43a2d42634f63759992120f9f25.png
-
拦截支付请求,设置返回Url并保存支付成功页面
在WKWebView的 WKNavigationDelegate代理方法中拦截支付请求
let request = navigationAction.request
let scheme = request.url?.scheme
let absoluteString = request.url?.absoluteString.removingPercentEncoding
DPrint(absoluteString)
// 设置返回Url:在Info.plist中设置的URL Schemes
let appScheme = ""
let redirect_url = "redirect_url=zxl.\(appScheme)://"
// 判断是否是微信支付请求
let hasPrefix = absoluteString?.hasPrefix("https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb")
let hasSuffix = absoluteString?.hasSuffix(redirect_url)
if hasPrefix! && hasSuffix == false {
decisionHandler(.cancel)
var requestUrl = absoluteString
let range = requestUrl?.range(of: "&redirect_url=")
if (range != nil) {
let subRange = (range?.lowerBound)!..<(requestUrl?.endIndex)!
// 保存支付成功页面路径,支付成功后加载
WeiXinPayRedirectURL = "https://hlht.echargenet.com/perhlhth5/#/views/rechargeSuccess"
requestUrl?.removeSubrange(subRange)
}
requestUrl = requestUrl! + "&" + redirect_url
// 重新发送请求
let newRequest = NSMutableURLRequest(url: URL(string: requestUrl!)!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: TIMEOUT)
newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields
webView.load(newRequest as URLRequest)
return;
}
-
跳转微信发起支付
if scheme == "weixin" {
decisionHandler(.cancel)
if UIApplication.shared.canOpenURL(request.url!) {
UIApplication.shared.open(request.url!, options: [UIApplication.OpenExternalURLOptionsKey.init(rawValue: "hello") : "world"]) { (isT) in
DPrint((isT ? "成功" : "失败"))
}
}
}
监听支付完成并加载支付成功页面
在AppDelegate中监听微信的支付成功回调,发送通知(也可以通过其他方式)。
NotificationCenter.default.post(name: NSNotification.Name(rawValue: WebViewWXPaySuccess), object: "")
监听微信支付成功
/// 微信支付成功
///
/// - Parameter notification: 通知
@objc func webViewWXPaySuccess(_ notification:Notification) {
DispatchQueue.global().async {
DispatchQueue.main.async {
let request = NSMutableURLRequest(url: URL(string: self.WeiXinPayRedirectURL)!)
request.httpMethod = "GET"
request.setValue("zxl.**://", forHTTPHeaderField: "Referer")
self.webView.load(request as URLRequest)
}
}
}
网友评论