Wechat payment V3 RSA signature stepping pit

Recently, we are making wechat payment. According to the requirements of wechat official documents, RSA is used to sign to request the adjustment of the payment window. The payment development process is listed in detail below;

The process of the current project is that the front end submits data according to the requirements of the back end and gets the prepay returned by the background_ ID, and order_ID, ---- front end RSA signature -------- call up wechat payment window -------- payment.

 

 

myOderData(options){
    const that=this;
    let params={
      datas:options,//Parameters for submitting order data
      method:'POST' 
     }
     let paycode,OrderNo;
 api.addorderData(params).then(res=>{
      
      if(res.data.Success==false){
        utils.msgtips(res.data.Msg);
      }else{
        paycode=res.data.Data.prepay_id;//Get the prepay returned from the background_ id
        OrderNo=res.data.Data.OrderNo;//Get the order number returned from the background
       // console.log(paycode);
        let obj= utils.paysign(paycode);  //RSA signature, which has been encapsulated as paysign method
        utils.processPay(obj).then(res=>{//Initiate the call of the payment form, which has been encapsulated into the processPay method
          if(res.errMsg=="requestPayment:ok"){//When the payment is successful, the order number should be transferred to the background to change the order status
            that.updateorderData(OrderNo)
          }else if(res.errMsg=="requestPayment:fail cancel"){//Action when canceling payment
            utils.msgtips('You have cancelled the payment');
            wx.navigateTo({
              url:'../mppaycancel/index'
            })
          }
        })
       }
    }).catch(err=>{
      console.log(err)
    }) 

  

 

The above is the overall method.

Here's how to add signature:

According to the requirements of Tencent's official documents, as shown in the figure:

 

 

Original document address: https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_4.shtml

 

 

v3 is used now, and v2 MD5 was used before

It should be noted that the encryption and signing method should be consistent with the backend.

1 applet ID acquisition:

 const accountInfo = wx.getAccountInfoSync();
  let appId=accountInfo.miniProgram.appId;

  2. Timestamp:

function createTimeStamp(){
  return parseInt(new Date().getTime() / 1000) + ''
}

3.32-bit random number:

function randomString(){
  const chars='ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; //The confusing characters ooll, 9gq, VV, UU and I1 are removed by default
  const len=32;
  const maxPos=chars.length;
  let pwd='';
  for(let i=0;i<len;i++){
    pwd+=chars.charAt(Math.floor(Math.random()*maxPos));
  }
  return pwd;
}

  4. Order detail extension character prepay_id:

That is, the prepay returned by the backend_ ID field data.

 

  5. Signature method:

signType= 'RSA'

  6. Sign paysign. Here's an explanation:

 1). It is best to strictly follow the order required by Tencent documents. Use fields appId, timeStamp, nonceStr, package

2) Use '\ n' to connect the fields, and use '\ n' at the end, not the equals sign.

The official document has a description: link: https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_4.shtml

As shown in the figure:

 

There is also a very important RSA signature:

I found the information provided by two bloggers:

1):

demo: https://blog.csdn.net/UFO00001/article/details/72822907

github: https://github.com/UFO0001/WX_RSA

 

2)

https://github.com/zhangzhaopds/WeixinApp_RSA_Signature

The second one needs to be built with a small program npm, which can be operated according to the document,

The npm build document is as follows:

https://developers.weixin.qq.com/miniprogram/dev/devtools/npm.html

 

I used the first one, which introduced Wx directly into the page_ rsa. js

As shown in the figure:

 

 

function signLong  (data) {
  let sign_rsa = new RSA.RSAKey();
  sign_rsa = RSA.KEYUTIL.getKey(privateKey);
  let hashAlg = 'sha256';//sha256 / / change here to the method required by Tencent
  let Sig = sign_rsa.signString(data, hashAlg);
  Sig = RSA.hex2b64(Sig); // hex to b64
  return Sig;
  }

  

About private keys:

Be sure to download the certificate:

 

After downloading, open this file, copy and paste the private key into the editor. It cannot be copied in TXT. The encoding method will be changed, resulting in unsuccessful signing.

 

 

Tencent's official website has a verification tool for adding and removing signatures, which can only detect whether it meets the specifications, not whether the value is correct. Address: https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay6_0.shtml

 

 

function paysign(options){//Initiate field preparation for payment sign off

  const accountInfo = wx.getAccountInfoSync();
  let appId=accountInfo.miniProgram.appId,//Applet appid
   timeStamp=createTimeStamp(),//time stamp
    nonceStr=randomString(),//32-bit random number
    Ppackage= `prepay_id=${options}`,//prepay_id
    signType= 'RSA';//Signature method
  //appId,timeStamp,nonceStr,package
  let PpaySign=`${appId}\n${timeStamp}\n${nonceStr}\n${Ppackage}\n`;//Splicing of fields to be signed
  let cryptStr=Rsa.signLong(PpaySign);//Generate signature
  let paySign=cryptStr;
  return obj={timeStamp,nonceStr,Ppackage,signType,paySign}; 
}

  

//Initiate payment
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);
     }
   });
  }) 
 }

  

The above is a complete description of some methods and value taking processes related to payment.

 

 

Keywords: Mini Program

Added by bidnshop on Tue, 04 Jan 2022 21:34:05 +0200