点击支付按钮
<button class="user-btn" bindtap="allowInv">支付</button>
allowInv: async function () {
const { payFee } = this.data
this.setData({ loading: true })
try {
if (payFee > 0) {
const oid = await this.createOrder()
const payData = await this.invokeOrder(oid)
await this.payOrder(payData)
await this.getOrderResult(oid)
this.toShop()
} else {
}
} catch (ex) {
if (ex.message) {
app.showErrorMsg(ex.message)
}
}
this.setData({ loading: false })
},
支付处理
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d2affc6070c67c51bfb1876b8c9f0b03.png)
- serviceApp.getMutation是自己封装的请求调用函数,可自定义修改为自己的接口请求,主要就是去接收后台res的返回值
createOrder: async function () {
const { userId, levelId } = this.data
const res = await throwServiceMutation(gql_create, { levelId, sellerId: userId })
console.log('创建订单', res);
return res.wxAppPay.create
},
invokeOrder: async function (oid) {
const res = await throwServiceMutation(gql_invoke, { oid })
console.log('创建微信支付需要的信息', res);
const script = res.wxAppPay.invoke.script
const data = script && JSON.parse(script)
return data
},
payOrder: async function (options) {
return new Promise((resolve, reject) => {
const { nonceStr, paySign, signType, timestamp } = options
wx.requestPayment({
nonceStr: nonceStr,
package: options.package,
paySign: paySign,
timeStamp: timestamp.toString(),
signType: signType,
success: (res) => {
console.log('支付成功', res);
resolve(res)
},
fail: (err) => {
reject(new Error('支付失败'))
}
})
})
},
getOrderResult: async function (oid) {
this.invokeResultCount++
let res = await serviceApp.getMutation({
mutation: gql_result,
variables: { oid },
hideError: true
})
console.log('获取结果', res);
if (isErrorCode(res, 101)) {
if (this.invokeResultCount < 10) {
await setTimeoutAsync(() => { }, 2000)
res = await this.getOrderResult(oid)
}
} else if (!res || res.errors) {
throw new Error('获取支付结果失败')
}
return res
},
toShop: function () {
wx.redirectTo({
url: `xxxx`,
success: () => {
wx.showToast('支付完成,加入成功')
}
})
}
--------------------------------------------
async function throwServiceMutation(mutation, variables) {
const res = await serviceApp.getMutation({
mutation, variables, hideError: true
})
if (res && !res.errors) {
return res
} else {
throw new Error(err)
}
}