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;
}
}