H5页面中调用微信和支付宝支付

第一步:先判断当前环境

判断用户所属环境,根据环境不同,执行不同的支付程序。

if (/MicroMessenger/.test(window.navigator.userAgent)) {
            // alert('微信');
        } else if (/AlipayClient/.test(window.navigator.userAgent)) {
            //alert('支付宝');
        } else {
            //alert('其他浏览器');
        }

第二步:如果是微信环境,需要先进行网页授权

网页授权获取code,然后调用后端支付接口

复制代码
const url =
                        'https://www.xxx.com/mobile/pay?pay_token=' +
                        this.token +
                        '&methodId=' +
                        this.methodId +
                        '&merchantNo=' +
                        this.merchantNo +
                        '&skuId=' +
                        this.skuId +
                        '&methodType=' +
                        this.methodType;
                    window.location.replace(
                        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=${encodeURIComponent(
                            url
                        )}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`
                    );
复制代码

 

第三步:

1、微信支付

微信支付有两种方法: 1:调用微信浏览器提供的内置接口WeixinJSBridge 2:引入微信jssdk,使用wx.chooseWXPay方法,需要先通过config接口注入权限验证配置。 我这里使用的是第一种,在从后台拿到签名、时间戳这些数据后,直接调用微信浏览器提供的内置接口WeixinJSBridge即可完成支付功能。

复制代码
 getDeviceInfo() {
            const ua = navigator.userAgent;
            const browser = {
                mobile: !!ua.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
                wx: ua.indexOf('MicroMessenger') > -1 // 是否微信
            };
            return browser;
        },
        query(search) {
            const str = search || window.location.search;
            const objURL = {};
            str.replace(new RegExp('([^?=&]+)(=([^&]*))?', 'g'), ($0, $1, $2, $3) => {
                objURL[window.decodeURIComponent($1)] = window.decodeURIComponent($3);
            });
            return objURL;
        },
        fnCreatePay(code) {
            let { pay_token, merchantNo, methodId, methodType } = this.query();
            if (pay_token == '') {
                return false;
            }
            this.requests
                .postMallCreateQrcode({
                    token: pay_token,
                    merchantNo,
                    methodId,
                    haveApp: this.getDeviceInfo().wx ? true : false,
                    code: code
                })
                .then(res => {
                    if (res.code == 0) {
                        let dailyResultData = {
                            name: '【' + this.commodity.daily.name + '】产业日报',
                            stage: this.startStage + '-' + this.endStage,
                            isCredits: methodType == 'integral' ? true : false,
                            price: this.dailySkuList.length && this.dailySkuList[0].sellPrice / 100,
                            credits: this.dailySkuList.length && this.dailySkuList[0].credits,
                            orderNo: res.data.orderNo
                        };
                        sessionStorage.setItem('dailyResultData', JSON.stringify(dailyResultData));
                        let wechatAppPay = res.data.wechatAppPay;
                        //微信搭桥需要的数据
                        this.$set(this.weChatParameter, 'appId', wechatAppPay.appId);
                        this.$set(this.weChatParameter, 'timeStamp', wechatAppPay.timeStamp);
                        this.$set(this.weChatParameter, 'nonceStr', wechatAppPay.nonceStr);
                        this.$set(this.weChatParameter, 'package', wechatAppPay.package);
                        this.$set(this.weChatParameter, 'signType', wechatAppPay.signType);
                        this.$set(this.weChatParameter, 'sign', wechatAppPay.sign);
                        setTimeout(() => {
                            this.weixinPay();
                        }, 500);
                    } else {
                        this.$message.error(res.msg);
                    }
                });
        },
        //搭桥前先解决微信内置对象报错
        weixinPay() {
            var that = this;
            if (typeof WeixinJSBridge == 'undefined') {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', that.onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', that.onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', that.onBridgeReady);
                }
            } else {
                that.onBridgeReady();
            }
        },
        //微信内置浏览器类
        onBridgeReady() {
            var that = this;
            window.WeixinJSBridge.invoke(
                'getBrandWCPayRequest',
                {
                    appId: that.weChatParameter.appId, //公众号名称,由商户传入
                    timeStamp: that.weChatParameter.timeStamp, //时间戳,自1970年以来的秒数
                    nonceStr: that.weChatParameter.nonceStr, //随机串
                    package: that.weChatParameter.package,
                    signType: that.weChatParameter.signType, //微信签名方式:
                    paySign: that.weChatParameter.sign //微信签名
                },
                function (res) {
                    // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
                    if (res.err_msg == 'get_brand_wcpay_request:ok') {
                        //支付成功
                        if (that.query().fromPage) {
                            that.$router.push({
                                path: that.query().fromPage
                            });
                        } else {
                            that.$router.push({
                                path: '/mobile/subresult'
                            });
                        }
                    } else if (res.err_msg == 'get_brand_wcpay_request:cancel') {
                        //取消支付的操作
                        if (that.query().fromPage) {
                            that.$router.push({
                                path: that.query().fromPage
                            });
                        } else {
                            that.$router.push({
                                path: '/mobile/dailyorder',
                                query: {
                                    skuId: that.query().skuId
                                }
                            });
                        }

                        //取消支付
                    } else {
                        //支付失败
                        if (that.query().fromPage) {
                            that.$router.push({
                                path: that.query().fromPage
                            });
                        } else {
                            that.$router.push({
                                path: '/mobile/dailyorder',
                                query: {
                                    skuId: that.query().skuId
                                }
                            });
                        }
                    }
                }
            );
        }
复制代码

 

2、支付宝支付

支付宝支付相对于微信来说,前端这块工作更简单 ,后台会返回给前端一个form表单,我们要做的就是把这个表单进行提交即可。相关代码如下:

复制代码
this.$api.alipayPay(data).then((res) => {
                // console.log('支付宝参数', res.data)
                if (res.code == 200) {
                    var resData =res.data
                    const div = document.createElement('div')
                    div.id = 'alipay'
                    div.innerHTML = resData
                    document.body.appendChild(div)
                    document.querySelector('#alipay').children[0].submit() // 执行后会唤起支付宝
                }

            }).catch((err) => {
            })
复制代码

 3、浏览器拉起微信支付宝支付

复制代码
  fnCreateQrcode() {
            let { token, merchantNo, methodId } = this;
            if (token == '') {
                return false;
            }

            let url = 'https://bestla.cyzone.cn/saas/mobile/subquery';
            if (process.env.NODE_ENV === 'production' && window.location.hostname === 'bestla.cyzone.cn') {
                url = 'https://bestla.cyzone.cn/saas/mobile/subquery';

                // 测试环境
            } else if (process.env.NODE_ENV === 'production' && window.location.hostname !== 'bestla.cyzone.cn') {
                url = 'https://testla.cyzone.cn/saas/mobile/subquery';
            }

            this.requests
                .postMallCreateQrcode({
                    token,
                    merchantNo,
                    methodId,
                    haveApp: false,
                    callbackUrl: url
                })
                .then(result => {
                    if (result.code == 0) {
                        let resData = result.data;
                        resData.backUrl = '/mobile/subresult';
                        cookies.set('mobile_daily_pay_info', resData, 5 * 60 * 1000);
                        let dailyResultData = {
                            name: '【' + this.commodity.daily.name + '】产业日报',
                            stage: this.startStage + '-' + this.endStage,
                            isCredits: this.methodType == 'integral' ? true : false,
                            price: this.dailySkuList.length && this.dailySkuList[0].sellPrice / 100,
                            credits: this.dailySkuList.length && this.dailySkuList[0].credits,
                            orderNo: resData.orderNo
                        };
                        sessionStorage.setItem('dailyResultData', JSON.stringify(dailyResultData));
                        if (this.methodType == 'alipay') {
                            const div = document.createElement('div');
                            div.id = 'alipay';
                            div.innerHTML = resData.submitData;
                            document.body.appendChild(div);
                            document.querySelector('#alipay').children[0].submit(); // 执行后会唤起支付宝
                        } else if (this.methodType == 'wechat') {
                            window.location.href = resData.wechatAppPay.payUrl + '&redirect_url=' + encodeURIComponent(url);
                        }
                    } else {
                        this.$message.error(result.msg);
                    }
                });
        },
复制代码

 

 微信支付文档链接:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6
 参考链接:https://juejin.cn/post/7034033584684204068
https://blog.csdn.net/Android_boom/article/details/125017455
https://blog.51cto.com/u_15300825/5271711
https://blog.csdn.net/zhwangchao/article/details/100612795
https://blog.csdn.net/fangxin222/article/details/85002430
https://juejin.cn/post/6934594640754507789
https://blog.csdn.net/fengkang511/article/details/103560522
https://blog.csdn.net/SK_21/article/details/110160045
https://juejin.cn/post/6844904009770205191#heading-5
https://www.jianshu.com/p/5ff377abc98b
posted @   振锋小哥  阅读(4093)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示

目录导航