Vue Typescript 实现微信支付

Vue框架下用typescript代替JavaScript,实现微信支付的功能。
查询微信开发者文档可知,需要调用WeixinJSBridge实现此功能。但是WeixinJSBridge为微信私有接口,一般情况下WeixinJSBridge内置对象在其他浏览器中无效。
难点在于使用TypeScript,如果在JavaScript中,逻辑代码如下所示。router作用在于付款后的页面跳转。

static onBridgeReady(result, router) {
    WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
        appId: 'wxa163ad6f33f2f38b', // 公众号名称,由商户传入
        timeStamp: `${result.timeStamp}`, // 时间戳,自1970年以来的秒数
        nonceStr: `${result.nonceStr}`, // 随机串
        package: `prepay_id=${result.prepayId}`,
        signType: 'MD5', // 微信签名方式:
        paySign: `${result.signedStr}`, // 微信签名
      },
      (res: WxRes) => {
        /* eslint-disable @typescript-eslint/camelcase */
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          // res.err_msg将在用户支付成功后返回ok
          // 支付成功 校验支付成功刷新  校验支付
          PayMethod.verifyPayment(result.orderPaymentNo, router);
          /* eslint-disable @typescript-eslint/camelcase */
        } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
          // 支付取消
          MessageBox.alert('支付取消');
        } else {
          // 支付失败
          MessageBox.alert('支付失败');
        }
      },
    );
  }

但是由于TypeScript相对来说类型系统比较复杂,如果按照以上逻辑写代码会导致WeixinJSBridge报错。以此借鉴之前导入mint-ui时产生问题的解决方法。
报错信息:
Could not find a declaration file for module 'mint-ui'.
在src文件夹下添加一个shim-mint.d.ts文件。然后添加内容

declare module 'mint-ui';

当然内容网上还有不同的内容。但是都要在src下添加一个shim-mint.d.ts文件。

declare module "mint-ui" {
  const Mint: any;
  export const Toast: any;
  export const MessageBox: any;
  export default Mint;
}

所以在src下面添加一个shim-weixinbridge.d.ts文件。书写方法参考官方文档声明文件链接

declare namespace WeixinJSBridge {
  interface WxBridgeInvoke{
    appId: string;

    timeStamp: string;

    nonceStr: string;

    package: string;

    signType: string;

    paySign: string;
  }

  function invoke(key: string, obj: WxBridgeInvoke, cb: Function): void
}

然后需要声明WxRes

export default class WxRes {
  /* eslint-disable @typescript-eslint/camelcase */
  err_msg: string;

  /* eslint-disable @typescript-eslint/camelcase */
  constructor(err_msg: string) {
    /* eslint-disable @typescript-eslint/camelcase */
    this.err_msg = err_msg;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值