<template>
<div>
<button @click="pay">微信支付</button>
</div>
</template>
<script>
import wxpay from 'weixin-js-sdk'; // 引入微信JS-SDK库
export default {
name: 'WechatPay',
props: {
amount: { // 支付金额
type: Number,
required: true
},
notifyUrl: { // 支付结果通知接口地址
type: String,
required: true
}
},
methods: {
pay() {
// 调用后端接口获取微信支付参数
axios.get('/api/wxpay', {params: {amount: this.amount, notifyUrl: this.notifyUrl}})
.then(res => {
const payInfo = res.data; // 后端返回的支付参数
// 调用微信JS-SDK库的支付接口
wxpay.chooseWXPay({
appId: payInfo.appId,
timestamp: payInfo.timestamp,
nonceStr: payInfo.nonceStr,
package: payInfo.package,
signType: payInfo.signType,
paySign: payInfo.paySign,
success: function (res) {
// 支付成功后的回调函数
console.log('支付成功', res);
},
fail: function (res) {
// 支付失败后的回调函数
console.log('支付失败', res);
}
});
})
.catch(err => {
console.error(err);
});
}
}
};
</script>
这是一个简单的微信支付组件,其中使用了axios库向后端发送请求获取支付参数,使用了微信JS-SDK库实现支付功能。在使用组件时,需要传入支付金额和支付结果通知接口地址两个参数。在按钮点击事件中调用pay
方法,该方法会向后端发送请求获取支付参数,然后调用微信JS-SDK库的支付接口。支付成功或失败后,微信JS-SDK库会调用相应的回调函数,我们可以在回调函数中处理支付结果。