第一步:获取从app跳转过来时,携带的token和money(支付金额)
第二步:调用微信的login接口获取code
第三步:调用后端接口,用获取的code换取openId
第四步:调用后端的支付接口获取微信支付需要的相关参数
第五步:调用微信的支付接口进行支付
温馨提示:因为此场景是用户从app跳转到微信页面进行支付,所以在支付完成之后,我们还需要让用户跳转回app。在这里,我在用户支付完成之后,无论是否支付成功,都用了u-popup组件进行提示。
以下是代码部分:
//第一步:获取从app跳转过来时,携带的token和money(支付金额)
onLoad(options) {
this.token = options.token
this.money = options.money
},
pay() {
const that = this
//第二步:调用微信的login接口获取code
uni.login({
provider: 'weixin',
success(res) {
console.log(res)
if (res.code) {
that.getOpenId(res.code)
} else {
uni.showToast({
title: '获取openId失败',
icon: 'none'
})
}
}
})
},
async getOpenId(code) {
const that = this
//第三步:用获取的code换取openId
const res = await getOpenId(code)
if (res.code === 200) {
const data = {
openId: res.data.openId,
money: this.money,
token: this.token
}
//第四步:调用后端的支付接口获取微信支付需要的相关参数
const res2 = await payMoney(data)
if (res2.code === 200) {
//第五步:调用微信的支付接口进行支付
uni.requestPayment({
provider: 'wxpay',
timeStamp: res2.data.timeStamp,
nonceStr: res2.data.nonceStr,
package: res2.data.packageValue,
signType: 'MD5',
paySign: res2.data.paySign,
success: function(res) {
that.popTiTle = '充值成功'
that.showPop = true
that.result = 'success'
},
fail: function(err) {
that.popTiTle = '充值失败'
that.showPop = true
that.result = 'fail'
}
});
}
}
},
//用户支付完成后,弹出的提示组件,app-parameter为返回到app时,给app那边的页面反应的支付状态(成功还是失败)
<!--支付成功弹出-->
<u-popup :show="showPop" mode="center" :round="10">
<view
style="width: 500rpx;height: 400rpx;display: flex;flex-direction: column;align-items: center;justify-content: center;">
<view style="font-size: 40rpx;">
{{popTiTle}}
</view>
<view>
<u-icon name="checkbox-mark" color="#909399" size="90" v-if="popTiTle==='充值成功'"></u-icon>
<u-icon name="error-circle" color="#909399" size="90" v-else></u-icon>
</view>
<button open-type="launchApp" :app-parameter="result" binderror="launchAppError"
style="width: 340rpx;height: 90rpx;display: flex;justify-content: center;align-items: center;">确定</button>
</view>
</u-popup>
<!--取消支付时弹出-->
<u-popup :show="showCancel" mode="center" :round="10">
<view class="cancel-tips">
<view class="title">
取消支付将无法完成账户充值
</view>
<view class="btn-box">
<button class="btn" @click="showCancel=false">我在想想</button>
<button open-type="launchApp" app-parameter="result" binderror="launchAppError" class="btn confirm">确定取消</button>
</view>
</view>
</u-popup>