使用Vue实现微信支付的组件

<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库会调用相应的回调函数,我们可以在回调函数中处理支付结果。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值