最近袍暴,app嵌入了一個(gè)H5模塊填帽,H5里面加入了微信支付的功能执泰。在發(fā)起微信支付的時(shí)候是通過(guò)weixin://的協(xié)議方式的,在UIWebView中可以正常調(diào)起微信發(fā)起支付嗡善,但支付成功會(huì)跳轉(zhuǎn)Safari瀏覽器然后加載支付成功頁(yè)面辑莫,WKWebView不能識(shí)別這種協(xié)議,不會(huì)跳轉(zhuǎn)微信罩引。
攔截H5微信支付請(qǐng)求
-
配置 URL Schemes各吨,用于跳回App
在info.plist中添加一個(gè)URL Schemes,用于在微信支付完成返回app蜒程。
-
攔截支付請(qǐng)求绅你,設(shè)置返回Url并保存支付成功頁(yè)面
在WKWebView的 WKNavigationDelegate代理方法中攔截支付請(qǐng)求
let request = navigationAction.request
let scheme = request.url?.scheme
let absoluteString = request.url?.absoluteString.removingPercentEncoding
DPrint(absoluteString)
// 設(shè)置返回Url:在Info.plist中設(shè)置的URL Schemes
let appScheme = ""
let redirect_url = "redirect_url=zxl.\(appScheme)://"
// 判斷是否是微信支付請(qǐng)求
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)!
// 保存支付成功頁(yè)面路徑伺帘,支付成功后加載
WeiXinPayRedirectURL = "https://hlht.echargenet.com/perhlhth5/#/views/rechargeSuccess"
requestUrl?.removeSubrange(subRange)
}
requestUrl = requestUrl! + "&" + redirect_url
// 重新發(fā)送請(qǐng)求
let newRequest = NSMutableURLRequest(url: URL(string: requestUrl!)!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: TIMEOUT)
newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields
webView.load(newRequest as URLRequest)
return;
}
-
跳轉(zhuǎn)微信發(fā)起支付
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 ? "成功" : "失敗"))
}
}
}
監(jiān)聽(tīng)支付完成并加載支付成功頁(yè)面
在AppDelegate中監(jiān)聽(tīng)微信的支付成功回調(diào),發(fā)送通知(也可以通過(guò)其他方式)忌锯。
NotificationCenter.default.post(name: NSNotification.Name(rawValue: WebViewWXPaySuccess), object: "")
監(jiān)聽(tīng)微信支付成功
/// 微信支付成功
///
/// - 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)
}
}
}