参考链接:
问题:自己的APP里面H5支付无法唤起微信以及回调如何处理
流程:app -> 微信客户端->支付结果->app
准备:获取微信的下单链接mweb_url,如:https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx0000&package=00000一样的格式
//实现wkwwebview的代理WKNavigationDelegate
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) ->
Void) {
guard let fullPath = navigationAction.request.url?.absoluteString.removingPercentEncoding else {
decisionHandler(.allow)
return
}
// 需要在URL Types中添加xx.自己的的域名.com,方便从微信返回到自己的应用
// 自己的域名是微信商户平台设置的H5域名
let schemeCallback = "xx.自己的的域名.com://wxpaycallback/“
if fullPath.contains("wx.tenpay.com"),
fullPath.hasSuffix(schemeCallback) == false,
let loc = fullPath.range(of: "&redirect_url=") {
let redirect = String.init(fullPath.suffix(from: loc.upperBound))
// 替换以前的支付完成的回调地址,让微信直接返回到自己的APP
let urlStr = fullPath.replacingOccurrences(of: redirect, with: schemeCallback)
if let url = URL.init(string: urlStr) {
// 保存以前的回调地址,当appdelelgate响应的时候,再通知网页加载这个地址,让用户主动触发订单校验请求
redirectURL = redirect
// 加载修改后的链接,网页会重定向以weixin://开头的路径,为下一步做准备
var req = URLRequest.init(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
req.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields
// 用于微信校验链接后面的redirect_url的值,实际中此步骤忘记加了,但是也能正常使用,
// req.setValue(schemeCallback, forHTTPHeaderField: "Referer")
webView.load(req)
}
decisionHandler(.cancel)
return
}
// 对weixin://开头的链接打开微信
if fullPath.hasPrefix("weixin://") {
decisionHandler(.allow)
if let URL = navigationAction.request.url {
UIApplication.shared.open(URL, options: [:], completionHandler: nil)
}
return
}
decisionHandler(.allow)
}
网友评论