微信、支付宝授权与支付

被设置为公众号入口的页面的url中都会包含一个code参数,然后通过code和appid去获取token等一些信息

1. 引入

<script type="text/javascript" charset="utf-8" src="https://g.alicdn.com/de/prismplayer/2.8.1/aliplayer-h5-min.js"></script>
  <link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.8.1/skins/default/aliplayer-min.css" />
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script>
    // let URL = 'https://kid.xxx.com'   测试
    // let pageUrl = 'http://test-web.xxx.com'  测试   
    let URL = 'https://api.xxx.com'     //正式
    let pageUrl = 'http://web.xxx.com'    //正式
    let price_num = '', orderId = '', code = ''
    $(".pay_btn").bind("click",function(){
        toPay()
    });
    
    function toPay(){
        $.ajax
        ({
            url: URL + '/tv/demand/dopay',
            data: {
                code: code,
                order_no: orderId,
                type: isWeixin() ? 'wechat' : '',
                redirect_url: `${pageUrl}/demand/pay/index.html?order_no=${orderId}&demand_price=${price_num}`,
                
            },
            type: 'get',
            dataType: "text",
            // dataType: "jsonp",
            // jsonp: "callback",
            success: function (res) {
                let params = res
                if(isWeixin()){
                    //微信
                    console.log(res.data,JSON.parse(res).data)
                    wxPay(JSON.parse(res).data)
                }else{
                    //非微信
                    aliPay(params)
                }
            },
            error: function (err) {
                console.log(err)
            }
        });
    }

    function isWeixin() {
        let ua = navigator.userAgent.toLowerCase();
        return /micromessenger/.test(ua) ? true : false;
    }
    function aliPay(params){
        const div = document.createElement('div')
        div.innerHTML = (params)
        document.body.appendChild(div)
        document.forms.alipaysubmit.submit()
    }
    function wxPay(params) {
        console.log('wxPay',params)
        if (typeof window.WeixinJSBridge === 'undefined') {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', function () { onBridgeReady(params) }, false)
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', function () { onBridgeReady(params) })
                document.attachEvent('onWeixinJSBridgeReady', function () { onBridgeReady(params) })
            }
        } else {
            onBridgeReady(params)
        }
    }
    function onBridgeReady(params) {
        window.WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
                'appId': params.appId, // 公众号名称,由商户传入
                'timeStamp': params.timeStamp, // 时间戳
                'nonceStr': params.nonceStr, // 随机串
                'package': params.package,  // prepay_id
                'signType': 'MD5', // 微信签名方式:
                'paySign': params.paySign, // 微信签名
                // 'total_fee': 0.01
                // 'appId': 'xxx', // 公众号名称,由商户传入
                // 'timeStamp': '1487659282', // 时间戳
                // 'nonceStr': 'qzmYpiO2QqM5XVzF', // 随机串
                // 'package': 'prepay_id=wx101022222222222',  // prepay_id
                // 'signType': 'JSAPI', // 微信签名方式:
                // 'paySign': '4175EE024BCAF9E665678A6BA1A658A5', // 微信签名
            },
            function (res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    // alert("支付成功");
                }else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                    // alert("支付取消");
                    setTimeout(function () { // 重新刷新当前页面获取新的code
                        window.location.href = `${pageUrl}/demand/pay/index.html?order_no=${orderId}&demand_price=${price_num}`
                    }, 2000);
                } else {
                    // alert('支付失败')
                    setTimeout(function () {
                        window.location.href = `${pageUrl}/demand/pay/index.html?order_no=${orderId}&demand_price=${price_num}`
                    }, 2000);
                }
            }
        )
    }
    // 获取价格、订单号
    function getParams(){
        var url = location.search; //获取url中"?"符后的字串
        if (url.indexOf("?") != -1) {  
            var str = url.substr(1) 
            strs = str.split("&") 
            var obj = {}
            for(var i = 0; i < strs.length; i++){
                var str1 = strs[i].split('=')
                obj[str1[0]] = str1[1]
                var newarr = []
                newarr.push(obj)
            }
            
            if(newarr.length!=0){
                if(newarr[0].order_no){
                    orderId = newarr[0].order_no   //获取订单号
                }
                if(newarr[0].demand_price){
                    $("#price").text(newarr[0].demand_price);
                    price_num = newarr[0].demand_price    //获取价格
                }
                if(isWeixin()){   
                    if(newarr[0].state && newarr[0].state!=''){
                        let params = decodeURIComponent(newarr[0].state).split('&')    //静默授权地址携带多个参数进行了拼接
                        orderId = params[0].split('=')[1] || ''
                        price_num = params[1].split('=')[1] || ''
                        $("#price").text(price_num)
                    }
                    // 微信需要去授权,支付宝不必
                    let params = encodeURIComponent(`order_no=${orderId}&demand_price=${price_num}`)
                    if(!newarr[0].code){
                        console.log('重定向去获取code')
                        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxx&redirect_uri=${pageUrl}/demand/pay/index.html&response_type=code&scope=snsapi_base&state=${params}&connect_redirect=1#wechat_redirect`
                    }else{
                        code = newarr[0].code
                    }
                }
            }
        }
    }
    $(document).ready(function () {
        getParams()
    })
    // VConsole 默认会挂载到 `window.VConsole` 上
    // var vConsole = new window.VConsole();
</script>

 

posted @ 2019-09-12 16:46  番茄西红柿u  阅读(578)  评论(0编辑  收藏  举报