微信支付小程序支付requestPayment方法参数以及封装加签js

最简单易懂wx.requestPayment调起微信支付

  1. 封装一个processPay.js用来调起wx.requestPayment
//发起支付
function  processPay(options){
  // console.log(options)
   let that=this;
  return new Promise((resolve,reject)=>{
   wx.requestPayment({
     package:options.Ppackage,...options,
     success: (res)=>{
       resolve(res);
     },
     fail: (err)=>{
       resolve(err);
     }
   });
  })
 }
 export default processPay;
  1. 调用封装方法传参数
var id = "xxxxxxxxxxxx"; //小程序id
var time = Date.now().toString();
var roundnumber = this.randomString(); //随机数生成
var packageurl = "prepay_id=xxxxxxxx"; //预支付交易会话标识,一般由后端返回 
let PpaySign=`${id}\n${time}\n${roundnumber}\n${packageurl}\n`;//需要加签的字段拼接
processPay({
		"appId":id,
		"timeStamp": time,
		"nonceStr": roundnumber,
		"package": packageurl,
		"signType": "RSA",
		"paySign": signLong(PpaySign)}
).then(res=>{//发起支付窗体的调起,已封装成processPay方法
	  if(res.errMsg=="requestPayment:ok"){//支付成功时,要传入订单号到后台改变订单状态
		uni.showToast({
			icon: "none",
			title: `支付成功`
		})
		
	  }else if(res.errMsg=="requestPayment:fail cancel"){//取消支付时的操作
	  
	  uni.showToast({
	  	icon: "none",
	  	title: `您已取消支付`
	  })
		
	}

3.辅助方法

// 随机生成32位字符串
    randomString() {
      let len = 32
      let $chars =
        'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' 
      let maxPos = $chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    }

你可能感兴趣的:(前端封装组件,javascript,微信,小程序)