封装微信公众h5调用微信支付
1、安装 weixin-js-sdk
npm install weixin-js-sdk
2、引用 weixin-js-sdk
const wx = require('weixin-js-sdk');
3、结合后台传过来的参数
wx.config({ debug: false, appId: data.appId, timestamp: data.timeStamp, nonceStr: data.nonceStr, signature: data.paySign, jsApiList: ['chooseWXPay'] }); wx.ready(() => { wx.chooseWXPay({ timestamp: data.timeStamp, //这个字段是为字符串后端返回时需检查 nonceStr: data.nonceStr, package: data.package, signType: data.signType, paySign: data.paySign, success(res) { r({ code: 0, msg: "成功" }); }, cancel() { r({ code: 1, msg: "取消" }); }, fail(err) { r({ code: 2, msg: err.errMsg.split(':')[1] || '支付失败!' }); }, // 无论失败成功都会执行 complete(e) { // e.errMsg三种状态 1.chooseWXPay:ok 支付成功 2: chooseWXPay:cancel 支付取消 3:chooseWXPay:fail 支付失败 if (e.errMsg === 'chooseWXPay:ok') { if (jumpUrl) { window.location.href = jumpUrl } else { window.location.reload() } } } }); }); wx.error(function(err) { r({ code: 2, msg: '支付失败!' }); }); })
完整代码(新建js文件放置):
const wx = require('weixin-js-sdk'); export default { wexinPay(data, jumpUrl) { return new Promise(r => { wx.config({ debug: false, appId: data.appId, timestamp: data.timeStamp, nonceStr: data.nonceStr, signature: data.paySign, jsApiList: ['chooseWXPay'] }); wx.ready(() => { wx.chooseWXPay({ timestamp: data.timeStamp, //这个字段是为字符串后端返回时需检查 nonceStr: data.nonceStr, package: data.packageValue, signType: data.signType, paySign: data.paySign, success(res) { r({ code: 0, msg: "成功" }); }, cancel() { r({ code: 1, msg: "取消" }); }, fail(err) { r({ code: 2, msg: err.errMsg.split(':')[1] || '支付失败!' }); }, // 无论失败成功都会执行 complete(e) { // e.errMsg三种状态 1.chooseWXPay:ok 支付成功 2: chooseWXPay:cancel 支付取消 3:chooseWXPay:fail 支付失败 if (e.errMsg === 'chooseWXPay:ok') { if (jumpUrl) { window.location.href = jumpUrl } else { window.location.reload() } } } }); }); wx.error(function(err) { r({ code: 2, msg: '支付失败!' }); }); }) } }
调用:
import $wxPay from '@/utils/wxPay.js' this.$u.api.wechatPayApi({ orderList: this.curOrderList, openid: this.vuex_wxinfo.openId }).then(res => { if (res.code === 200) { $wxPay.wexinPay(res.data.wx).then(res1 => { switch (Number(res1.code)) { case 0: // 成功 //#ifdef H5 window.location.reload(); //#endif break; case 1: // 取消 this.$refs.uToast.show({ title: '已取消支付', type: 'info' }); break; case 2: // 支付失败 this.$refs.uToast.show({ title: '支付失败,请检查!', type: 'error' }); break; } }) } })
自己根据后台接口适当调整!
希望大佬看到有不对的地方,提出博主予以改正!