微信公众号里的网页支付,网上很多说的是使用纯JS的方式(包括官方的例子,也是距离的纯JS的实现方式),如果我们使用的vue搭建的项目,也是类似的,下面给出我的实现方式。
package.json加入"weixin-js-sdk": "^1.6.0",如下:
{ "name": "test-wx", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "dependencies": { "axios": "^0.19.2", "core-js": "^3.6.5", "vue": "^2.6.11", "vue-router": "^3.1.6", "vuex": "^3.1.2", "weixin-js-sdk": "^1.6.0" }, "devDependencies": { "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-router": "~4.5.0", "@vue/cli-plugin-vuex": "~4.5.0", "@vue/cli-service": "~4.5.0", "less": "^3.11.1", "less-loader": "^5.0.0", "vue-template-compiler": "^2.6.11" }, "browserslist": [ "> 1%", "last 2 versions", "not dead" ] }
在需要调用支付的vue页面中(该页面需要在微信商户中增加为支付目录),代码如下:
methods: { // 用户支付支付从这里开始,先请求后台的预下单接口,返回prepay_id等 submitOrderClicked: function () { let payload = qs.stringify({productId: this.product.id, openId: this.oid, num: this.num}); http.post('/api/product_order', payload).then(res => { this.loading = false; if (!res.data.result) { Notify({type: 'danger', message: res.data.message}); } else { this.payRequest = res.data.extra.payRequest; this.orderNo = res.data.extra.orderNo; this.doPay(); } }); }, onBridgeReady() { // https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_7&index=6 // 这里的payRequest我是后台通过预支付后,组装好的,类似: // { // "appId": "wx2421b1c4370ec43b", //公众号ID,由商户传入 // "timeStamp": "1395712654", //时间戳,自1970年以来的秒数 // "nonceStr": "e61463f8efa94090b1f366cccfbbb444", //随机串 // "package": "prepay_id=up_wx21201855730335ac86f8c43d1889123400", // "signType": "RSA", //微信签名方式: // "paySign": "abc123==" //微信签名 // } WeixinJSBridge.invoke('getBrandWCPayRequest', this.payRequest, (res) => { if (res.err_msg === "get_brand_wcpay_request:ok") { // 使用以上方式判断前端返回,微信团队郑重提示: //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。 Notify({type: 'success', message: '成功支付!'}); this.checkStateAndGoOrderDetail(); } else if(res.err_msg === "get_brand_wcpay_request:cancel") { Notify({type: 'warning', message: '已取消支付!'}); } else { Notify({type: 'warning', message: '支付失败!'}); } }); }, // 真正的JS支付方法入口 doPay() { if (typeof WeixinJSBridge == "undefined") { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false); } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady); document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady); } } else { this.onBridgeReady(); } }, checkStateAndGoOrderDetail() { Toast.loading({ message: '加载中...', forbidClick: true, }); http.get('/api/order_transaction_check?orderId='+this.orderNo).then(res => { Toast.clear(); if (!res.data.result) { Notify({type: 'danger', message: res.data.message}); } else { //跳到支付订单详细页面 // res.data.extra.order里有信息,可以使用 this.$router.replace('/my_order_detail?id='+this.orderNo); } }); } },
文章评论