微信支付实现(nuxt)
- 获取token
text
async asyncData({ $axios, query, n2token }) {
// 1. 从query中拿到code
const { code } = query
// const code = '081ozf300lj2aR1rCI000lRQOc3ozf33'
const useRes = await toAuthentication({
code,
state: 'sharp'
})
let token
if (useRes.data.success) {
token = useRes.data.data.token
} else {
token = ''
}
// 4. 通过token拿到用户套餐
const configRes = await getVipConfig({})
// 支付时用product_id 调用 makeOrder 拿到支付需要的参数并调起微信支付
return {
token,
payList: configRes.data.data,
currType: configRes.data.data[0]
}
},
- 点击支付
text
async makeOrder() {
// 支付时用product_id 调用 makeOrder 拿到支付需要的参数并调起微信支付
const res = await makeMiniH5Order(
{
product_id: this.currType.params.productId,
trade_type: this.isIOS ? 'ios' : 'android'
},
{
headers: {
Authorization: this.token
}
}
)
const openData = res.data.data.open_data
this.wxJSPay(
{ ...openData, appId: res.data.data.weichatpay.appid },
() => {
this.$toast('支付成功, 快去小程序体验会员功能吧!~')
},
() => {
this.$toast('支付失败')
}
)
},
// 微信环境
wxJSPay(configObj, successCb, failCb) {
function onBridgeReady() {
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
{
...configObj
},
function(res) {
if (res.err_msg == 'get_brand_wcpay_request:ok') {
// 使用以上方式判断前端返回,微信团队郑重提示:
// res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
successCb && successCb()
} else {
failCb && failCb()
}
}
)
}
if (typeof WeixinJSBridge === 'undefined') {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
}
} else {
onBridgeReady()
}
}