转《基于Ionic3实现微信支付和支付宝支付》

在Ionic应用里实现支付并不难,但是有的坑真是不爬不知道。

一:支付宝支付

网上关于支付宝支付cordova插件真是非常多,但是大多会报一些让你很无语的错误。比如sdk早已过时不是最新的,或者没有出来效果。我也是经过大量试错,最终选择了以下这个。

安装cordova支付宝支付插件:

ionic cordova plugin add cordova-plugin-alipay-v2 --variable APP_ID=xxxxxxxxxxx

让用户选择支付方式

openPayActionSheet(data) {
    this.actionSheetCtrl.create({
      buttons: [
        {
          text: "支付宝支付",
          handler: () => { this.aliPay(data); } }, { text: "微信支付", handler: () => { this.weiXinPay(data); } }, { text:"取消", role: 'cancel' } ] }).present(); }

调用后台的签名方法,返回给你签名字符串,这个后台如果不知道怎么签名的话,阿里官方文档有详细的介绍。

unescapeHTML(a){
  let aNew = "" + a;
     return aNew.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&apos;/g, "'"); } aliPay(sn){ $.post('http://www.uhunche.cn/index.php?c=api&a=index',{ api:'alipay', order_sn:sn },(data)=>{ let payInfo=this.unescapeHTML(data); cordova.plugins.alipay.payment(payInfo,(success)=>{ success.resultStatus==="9000"?this.paySuccess(sn): this.payFailed(); //支付成功 this.paySuccess(); },(error)=>{ //支付失败 this.payFailed(); }); }); }

这个unescapeHTML方法就是我在此坑了两天的成果,因为我们后台返回的签名字符串里面的&符号默认是实体字符串的,但是安卓和ios的sdk会默认对其格式化成&符号,而我们的js插件代码并没有做这个事情,所以我直接上传的签名字符串一直是实体字符串,所以传上去的不是&符号,一直调起不了支付宝。而把我们的签名字符串给支付宝的客服测试,是可以通过的,就因为他们是用原生应用demo测试的,默认做了这件事情。 
这样支付成功之后就会调后台写的回调方法,订单的状态就会改变了。

二:微信支付

是的,又是经过大量的试错,我选择了这个cordova插件,我们只是使用其中的微信支付方法,像微信分享等其他功能在这个插件也能实现的。

安装cordova支付宝支付插件:

ionic cordova plugin add cordova-plugin-wechat --variable wechatappid=xxxxxxxxxx

我们稍微对这个插件的方法简单封装一下

扫描二维码关注公众号,回复: 2956980 查看本文章
declare var Wechat: any;  // 此处声明plugin.xml中clobbers对应的值
export interface WechatPayParam {
  partnerid: string;
  prepayid: string; noncestr: 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); }); }); } }

调用后台的签名方法

 weiXinPay(sn){
    this.httpService.postPHPWithLoading({
      api:'wxpay',
      order_sn:sn
    }).subscribe(
      payResult=>{
        console.log(payResult);

        var params = {
          partnerid:payResult.partnerid, // merchant id prepayid: payResult.prepayid, // prepay id noncestr: payResult.noncestr, // nonce timestamp: payResult.timestamp+"", // timestamp sign: payResult.sign // signed string }; WechatPlugin.sendPaymentRequest(params).then((result)=>{ //支付成功 this.paySuccess() },(error)=>{ //支付失败 this.payFailed() }) } ) }

这里的一个坑就是插件要求时间戳timestamp必须是字符串类型,但是一般后台返回的时间戳都是number类型。所以要对其处理一下。另外微信支付要求每次支付的支付订单号都是不同的,那么当我们使用用户下单的订单号作为支付订单号的时候,如果进行支付并没有支付而取消了,下次再对这笔订单进行支付是会失败的,所以后台应该在每次支付都保证支付订单号是唯一的。

原文直通车

猜你喜欢

转载自www.cnblogs.com/ckAng/p/9558233.html