美文网首页支付集成OC-开发案例收集
Swift WKWebView 实现支付宝,微信支付流程

Swift WKWebView 实现支付宝,微信支付流程

作者: 李木的 | 来源:发表于2019-07-22 17:34 被阅读21次

    公司做微信和支付宝支付时采用了h5的方式。我是使用swift开发的,所以选择使用WKWebView。
    1.使用webview必然会有js交互。就会使用到evaluateJavaScript为h5传参数。
    2.做h5支付宝支付的时候,我们必须使用到WKWebView这个代理方法,就是一个截取navigationAction.request.url?.scheme的值为alipay。这个是我们进行app间跳转的URLScheme,通过白名单跳转。当然支付完成后我们也需要返回到自己的app 中。在获取alipay的网址中会有一个fromAppUrlScheme字段,这个就是我们app自己的URLScheme。直接上代码。

     func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void){
    
        let urlScheme = navigationAction.request.url?.scheme ?? ""
        let urlStr = navigationAction.request.url?.absoluteString ?? ""
        if urlScheme == "alipay"{
    
            UIApplication.shared.open(handleAlipayUrl(url: URL.init(string: urlStr)!)!, options: [:]) { (bo) in
            }
            print("dsfsdf ====\(urlScheme) ======\(urlStr)")
            decisionHandler(WKNavigationActionPolicy.cancel)
    
        }
      
        else{
        decisionHandler(WKNavigationActionPolicy.allow)
        }
    
    
    }
    fileprivate func handleAlipayUrl(url: URL) -> URL? {
        if url.absoluteString.hasPrefix("alipay://alipayclient/") {
            // 更换scheme
            var decodePar = url.query ?? ""
            decodePar.urlDecode()
            var dict = ValidateManager.jsonToDictionary(jsonString: decodePar)
            dict["fromAppUrlScheme"] = "myappScheme"
            if let strData = try? JSONSerialization.data(withJSONObject: dict , options: []) {
                var param = String(data: strData, encoding: .utf8)
                param?.urlEncode()
                let finalStr = "alipay://alipayclient/?\(param ?? "")"
                if let finalUrl = URL(string: finalStr) {
                    return finalUrl
                }
            }
            return url
        }
        return nil
    }
    

    2.微信的比较坑吧,第一个坑就是支付完成后会跳转到Safari浏览器中,第二个坑是不会有支付回调。先解决第一个坑吧,就是先要根据支付域名设置自己APP的URLScheme,这样的话就可以在支付完成后返回到的我们自己的app中,当然需要在APPdelegate中处理这个回调。

       func webView(_ webView: WKWebView, decidePolicyFor   navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    
        let urlScheme = navigationAction.request.url?.scheme ?? ""
        let urlStr = navigationAction.request.url?.absoluteString ?? ""
      if urlScheme == "weixin"{
    
            if UIApplication.shared.canOpenURL(URL.init(string: urlStr)!){
            UIApplication.shared.open(URL.init(string: urlStr)!, options: [:]) { (bo) in
            }
            print("dsfsdf ====\(urlScheme) ======\(urlStr)")
            decisionHandler(WKNavigationActionPolicy.cancel)
            }else{
                let url = URL.init(string: PayUrl)
                
                let request = NSURLRequest(url: url!)
                //加载请求
                webView.load(request as URLRequest)
    
                let alert = JLAlertView.init(title: "温馨提示", detailText: "请先现在微信客户端", customView: nil, cancelButtonTitle: "取消", otherButtonTitles: ["去下载"])
                alert?.show({ (index) in
                    if index == 1{
                        UIApplication.shared.open(URL.init(string: "https://apps.apple.com/cn/app/wei-xin/id414478124")!, options: [:]) { (bo) in
                        }
                    }
                })
                
            
                decisionHandler(WKNavigationActionPolicy.allow)
            }
    
        }else{
            if urlStr.range(of: "https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb") != nil && !self.isload{
                    let array : Array = urlStr.components(separatedBy: "redirect_url=")
                    self.redirect_url =  array[1]
                    let rs = "******.cn://".urlDecoded
                    let mNewUrl = array[0] + "redirect_url=\(rs)"
                    let newURLS = URL(string: mNewUrl)
                    var mRequest = URLRequest.init(url: newURLS!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
                    mRequest.setValue("******.cn://", forHTTPHeaderField: "Referer")
                    webView.load(mRequest)
                    self.isload = true
    
                decisionHandler(WKNavigationActionPolicy.cancel)
                    return
            }
            self.isload = false
        decisionHandler(WKNavigationActionPolicy.allow)
        }
    }
    

    3.js调用原生方法这个就需要使用到WKWebview中WKUserScript和WKScriptMessageHandler的代理方法。我使用的最笨的方案,因为前端没有时间处理,我只能通过页面控件的id进行处理点击事件。

         let baiduButtonId = "back"
        let baiduMessage = "jsCallIOS"
        let scriptStr = "function fun(){window.webkit.messageHandlers.\(baiduMessage).postMessage(\"\(baiduButtonId)\");}(function(){var btn=document.getElementById(\"\(baiduButtonId)\");btn.addEventListener('click',fun,false);}());"
        let userScript = WKUserScript(source: scriptStr, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        let baiduButtonId1 = "back2"
        let baiduMessage1 = "jsCallIOS"
        let scriptStr1 = "function fun(){window.webkit.messageHandlers.\(baiduMessage1).postMessage(\"\(baiduButtonId1)\");}(function(){var btn=document.getElementById(\"\(baiduButtonId1)\");btn.addEventListener('click',fun,false);}());"
        let userScript1 = WKUserScript(source: scriptStr1, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        webView.configuration.userContentController.addUserScript(userScript1)
        webView.configuration.userContentController.addUserScript(userScript)
        webView.configuration.userContentController.add(self, name: baiduMessage)   
      func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.body)
        let mess = message.body as! String
        if mess == "back"  {
        }
        if mess == "back2" {
    
        }
    }
    

    4.为webview添加加载进度条和获取标题 在viewDidLoad中添加

        webView.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    

    实现观察方法

     //添加观察者方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //设置进度条
        if keyPath == "estimatedProgress"{
            progressView.alpha = 1.0
            progressView.setProgress(Float(webView.estimatedProgress), animated: true)
            if webView.estimatedProgress >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
                    self.progressView.alpha = 0
                }, completion: { (finish) in
                    self.progressView.setProgress(0.0, animated: false)
                })
            }
        }
            
            //重设标题
        else if keyPath == "title" {
            self.title = self.webView.title
        }
    }
    

    相关文章

      网友评论

        本文标题:Swift WKWebView 实现支付宝,微信支付流程

        本文链接:https://www.haomeiwen.com/subject/wjgwlctx.html