Home > WeChat Applet > Mini Program Development > WeChat Mini Program: WeChat Payment Pitfall Process

WeChat Mini Program: WeChat Payment Pitfall Process

高洛峰
Release: 2017-03-01 10:58:47
Original
2425 people have browsed it

Let’s take a look at the mini program development steps first

WeChat Mini Program: WeChat Payment Pitfall Process

##wx.login calls the interface to obtain the login credentials (code)

code in exchange for the user’s unique identification (openid )

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

WeChat Mini Program: WeChat Payment Pitfall Process

Unified order placement


URL address: https://api.mch.weixin.qq.com/pay/unifiedorder

post

The parameter is XML


wx.requestPayment to make payment

WeChat Mini Program: WeChat Payment Pitfall Process

Chaikeng

Signature MD5 encryption, some algorithms on the Internet are wrong, you still need online MD5 after writing it yourself Encryption tool for verification (I spent the whole afternoon trying to figure out whether what I wrote is correct, but it just can’t come out. The reason is that the MD5 tool is used incorrectly, which is a scam - -)

Notes on signature rules (must)


◆ Sort the ASCII codes of parameter names from small to large (lexicographic order);

◆ If the value of the parameter is empty, it will not participate in the signature;

◆ Parameter names are size-sensitive Write;

◆ When the verification call returns or WeChat actively notifies the signature, the transmitted sign parameter does not participate in the signature, and the generated signature is verified against the sign value.

◆ The WeChat interface may add fields, and the added extended fields must be supported when verifying signatures


Unify the order signature appid, wx.requestPayment signature appId (case must be distinguished, really difficult to find) Blind my titanium alloy dog ​​eyes - - )

The package parameter in wx.requestPayment must be package:"prepay_id=wx21**************", otherwise, a call will occur The payment JSAPI lacks appid/total_fee

total_fee points, and is int

Generate random numbers and timestamps. Make sure the signature is consistent with the upload parameters

case. . Be sure to note that

WeChat applet trade_type=JSAPI, the openid parameter must be passed

wx.requestPayment generates a signature with appId, but there is no appId when requesting



Okay, here’s the code (the code is very original and not encapsulated)

/* 微信支付 */
  wxpay: function () {
    var that = this
    //登陆获取code
    wx.login({
      success: function (res) {
        console.log(res.code)
        //获取openid
        that.getOpenId(res.code)
      }
    });
  },

  /* 获取openId */
  getOpenId: function (code) {
    var that = this
    wx.request({
      url: "https://api.weixin.qq.com/sns/jscode2session?appid=wxbd5a8270399d41d9&secret=d8aac26a5a9c16266d1a23851ebb7d9b&js_code=" + code + "&grant_type=authorization_code",
      method: 'GET',
      success: function (res) {
        //统一支付签名
        var appid = '';//appid  
        var body = '';//商户名
        var mch_id = '';//商户号  
        var nonce_str = that.randomString;//随机字符串,不长于32位。  
        var notify_url = '';//通知地址
        var spbill_create_ip = '';//ip
        // var total_fee = parseInt(that.data.wxPayMoney) * 100;
        var total_fee = 100;
        var trade_type = "JSAPI";
        var key = '';
        var unifiedPayment = 'appid=' + appid + '&body=' + body + '&mch_id=' + mch_id + '&nonce_str=' + nonce_str + '¬ify_url=' + notify_url + '&openid=' + res.data.openid + '&out_trade_no=' + that.data.paySn + '&spbill_create_ip=' + spbill_create_ip + '&total_fee=' + total_fee + '&trade_type=' + trade_type + '&key=' + key
        var sign = MD5.MD5(unifiedPayment).toUpperCase()
        console.log(sign)

        //封装统一支付xml参数
        var formData = ""
        formData += "" + appid + ""
        formData += "" + body + ""
        formData += "" + mch_id + ""
        formData += "" + nonce_str + ""
        formData += "" + notify_url + ""
        formData += "" + res.data.openid + ""
        formData += "" + that.data.paySn + ""
        formData += "" + spbill_create_ip + ""
        formData += "" + total_fee + ""
        formData += "[tr]" + trade_type + ""
        formData += "" + sign + ""
        formData += ""

        //统一支付
        wx.request({
          url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
          method: 'POST',
          head: 'application/x-www-form-urlencoded',
          data: formData, // 设置请求的 header
          success: function (res) {
            console.log(res.data)
          
            var result_code = that.getXMLNodeValue('result_code', res.data.toString("utf-8"))
            var resultCode = result_code.split('[')[2].split(']')[0]
            if (resultCode == 'FAIL') {
              var err_code_des = that.getXMLNodeValue('err_code_des', res.data.toString("utf-8"))
              var errDes = err_code_des.split('[')[2].split(']')[0]
              wx.navigateBack({
                delta: 1, // 回退前 delta(默认为1) 页面
                success: function (res) {
                  wx.showToast({
                    title: errDes,
                    icon: 'success',
                    duration: 2000
                  })
                },

              })
            } else {

              //发起支付
              var prepay_id = that.getXMLNodeValue('prepay_id', res.data.toString("utf-8"))
              var tmp = prepay_id.split('[')
              var tmp1 = tmp[2].split(']')
              //签名  
              var key = '';
              var appId = '';
              var timeStamp = that.createTimeStamp();
              var nonceStr = that.randomString();
              var stringSignTemp = "appId=&nonceStr=" + nonceStr + "&package=prepay_id=" + tmp1[0] + "&signType=MD5&timeStamp=" + timeStamp + "&key="
              var sign = MD5.MD5(stringSignTemp).toUpperCase()
              console.log(sign)
              var param = { "timeStamp": timeStamp, "package": 'prepay_id=' + tmp1[0], "paySign": sign, "signType": "MD5", "nonceStr": nonceStr }
              that.pay(param)
            }



          },

        })
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  /* 随机数 */
  randomString: function () {
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = chars.length;
    var pwd = '';
    for (var i = 0; i < 32; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  },
  /* 获取prepay_id */
  getXMLNodeValue: function (node_name, xml) {
    var tmp = xml.split("<" + node_name + ">")
    var _tmp = tmp[1].split("")
    return _tmp[0]
  },

  /* 时间戳产生函数   */
  createTimeStamp: function () {
    return parseInt(new Date().getTime() / 1000) + &#39;&#39;
  },
  /* 支付   */
  pay: function (param) {
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: param.signType,
      paySign: param.paySign,
      success: function (res) {
        // success
        console.log(res)
        wx.navigateBack({
          delta: 1, // 回退前 delta(默认为1) 页面
          success: function (res) {
            wx.showToast({
              title: &#39;支付成功&#39;,
              icon: &#39;success&#39;,
              duration: 2000
            })
          },
          fail: function () {
            // fail
          },
          complete: function () {
            // complete
          }
        })
      },
      fail: function () {
        // fail
        console.log("支付失败")
      },
      complete: function () {
        // complete
        console.log("pay complete")
      }
    })
  }
Copy after login

For more WeChat mini programs: WeChat payment trap process related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template