ionic2 cordova插件用法之二

时间:2021-09-12 22:59:12

之前参考官方的写了一种用法,但是这种用法不是很方便,于是再写个方便一些的。

以cordova-plugin-wechat为例:

在项目中创建wechat-plugin.ts,代码如下:

declare var Wechat: any;  // 此处声明plugin.xml中clobbers对应的值

export interface WechatPayParam {
  mch_id: string;
  prepay_id: string;
  nonce: string;
  timestamp: string;
  sign: string;
}

export class WechatPlugin {

  public static isInstalled() {
    return new Promise((resolve, reject) => {
      Wechat.isInstalled(result => {
        resolve(result);
      }, error => {
        reject(error);
      });
    });
  }

  public static sendPaymentRequest(params: WechatPayParam) {
    return new Promise((resolve, reject) => {
      Wechat.sendPaymentRequest(params, result => {
        resolve(result);
      }, error => {
        reject(error);
      });
    });
  }
}
调用代码如下:

WechatPlugin.sendPaymentRequest({
          mch_id: prepayInfo.partner_id,
          prepay_id: prepayInfo.prepay_id,
          nonce: prepayInfo.nonce_str,
          timestamp: prepayInfo.timestamp,
          sign: prepayInfo.sign
        }).then(() => {
          alert("success");
        }).catch((error) => {
          alert(error);
        });