Home > WeChat Applet > Mini Program Development > Implementation code for online payment function developed by WeChat applet

Implementation code for online payment function developed by WeChat applet

高洛峰
Release: 2017-03-16 15:17:51
Original
2417 people have browsed it

This article mainly introduces the relevant information on the implementation code of the online payment function developed by WeChat mini program. Friends in need can refer to the following

Online payment function of WeChat mini program

Recently I needed to use the online payment function in the WeChat mini program, so I took a look at the official documents and found that it is very convenient to implement WeChat payment in the mini program. If you have developed WeChat payment under a service account before, then You will find that the development process of WeChat payment in the mini program is exactly the same as that in the service account. Now I will talk about the development process and points of attention of WeChat payment in the mini program in detail.

Implementation code for online payment function developed by WeChat applet

1. Open WeChat payment and WeChat merchant account

This process is the same as the WeChat payment process of opening a service account Same, nothing to say.

Implementation code for online payment function developed by WeChat applet

2. Obtain the user’s openid

We need to do this on the client side of the mini program## Get the current user's openid in #js. You can get the user's code by calling the wx.login method, and then the developer server uses the login credential code to obtain the openid.


wx.login({
   success: function(res) {
    if (res.code) {
     //发起网络请求
     wx.request({
      url: 'https://yourwebsit/onLogin',
      method: 'POST',
      data: {
       code: res.code
      },
      success: function(res) {
        var openid = res.data.openid;
      },
      fail: function(err) {
        console.log(err)
      }
     })
    } else {
     console.log('获取用户登录态失败!' + res.errMsg)
    }
   }
  });
Copy after login


var code = req.param("code");
    request({
      url: "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code",
      method: 'GET'
    }, function(err, response, body) {
      if (!err && response.statusCode == 200) {
        res.json(JSON.parse(body));
      }
    });
Copy after login

3. Get prepay_id and payment signature verification paySign

The process of this step is the same as the WeChat payment process in the service account. It is divided into client and server side


First let’s take a look at the client js


in the service account Here, we activate the payment function through the following code


function jsApiCall()
    {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          "appId":"",   //公众号名称,由商户传入   
          "timeStamp":"",     //时间戳,自1970年以来的秒数   
          "nonceStr":"", //随机串   
          "package":"prepay_id=<%=prepay_id%>",   
          "signType":"MD5",     //微信签名方式:   
          "paySign":"<%=_paySignjs%>" //微信签名
        },
        function(res){
          WeixinJSBridge.log(res.err_msg);
          if( res.err_msg =="get_brand_wcpay_request:ok"){
            alert("支付成功!");
          }else{
            alert("支付失败!");
          }
        }
      );
    }
Copy after login

In the mini program, we activate the payment function through the wx.requestPayment method. Of course, here Before, we first need to get the prepay_id.


 wx.request({
          url: &#39;https://yourwebsit/service/getPay&#39;, 
          method: &#39;POST&#39;,
          data: {
           bookingNo:bookingNo, /*订单号*/
           total_fee:total_fee,  /*订单金额*/
           openid:openid
          },
          header: {
            &#39;content-type&#39;: &#39;application/json&#39;
          },
          success: function(res) {
            wx.requestPayment({
             &#39;timeStamp&#39;:timeStamp,
             &#39;nonceStr&#39;: nonceStr,
             &#39;package&#39;: &#39;prepay_id=&#39;+res.data.prepay_id,
             &#39;signType&#39;: &#39;MD5&#39;,
             &#39;paySign&#39;: res.data._paySignjs,
             &#39;success&#39;:function(res){
               console.log(res);
             },
             &#39;fail&#39;:function(res){
               console.log(&#39;fail:&#39;+JSON.stringify(res));
             }
            })
          },
          fail: function(err) {
            console.log(err)
          }
        })
Copy after login

The main thing to achieve on the server side is to obtain prepay_id and sign paySign


 var bookingNo = req.param("bookingNo");
    var total_fee = req.param("total_fee");
    var openid = req.param("openid");
    var body = "费用说明";
    var url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    var formData = "<xml>";
    formData += "<appid>appid</appid>"; //appid
    formData += "<attach>test</attach>";
    formData += "<body>" + body + "</body>";
    formData += "<mch_id>mch_id</mch_id>"; //商户号
    formData += "<nonce_str>nonce_str</nonce_str>";
    formData += "<notify_url>notify_url</notify_url>";
    formData += "<openid>" + openid + "</openid>";
    formData += "<out_trade_no>" + bookingNo + "</out_trade_no>";
    formData += "<spbill_create_ip>spbill_create_ip</spbill_create_ip>";
    formData += "<total_fee>" + total_fee + "</total_fee>";
    formData += "<trade_type>JSAPI</trade_type>";
    formData += "<sign>" + paysignjsapi(appid, attach, body, mch_id, nonce_str, notify_url, openid, bookingNo, spbill_create_ip, total_fee, &#39;JSAPI&#39;) + "</sign>";
    formData += "</xml>";
    request({
      url: url,
      method: &#39;POST&#39;,
      body: formData
    }, function(err, response, body) {
      if(!err && response.statusCode == 200) {
        var prepay_id = getXMLNodeValue(&#39;prepay_id&#39;, body.toString("utf-8"));
        var tmp = prepay_id.split(&#39;[&#39;);
        var tmp1 = tmp[2].split(&#39;]&#39;);
        //签名
        var _paySignjs = paysignjs(appid, mch_id, &#39;prepay_id=&#39; + tmp1[0], &#39;MD5&#39;,timeStamp);
        var o = {
          prepay_id: tmp1[0],
          _paySignjs: _paySignjs
        }
        res.send(o);
      }
    });
Copy after login

The following is used The

function


function paysignjs(appid, nonceStr, package, signType, timeStamp) {
  var ret = {
    appId: appid,
    nonceStr: nonceStr,
    package: package,
    signType: signType,
    timeStamp: timeStamp
  };
  var string = raw1(ret);
  string = string + &#39;&key=&#39;+key;
  console.log(string);
  var crypto = require(&#39;crypto&#39;);
  return crypto.createHash(&#39;md5&#39;).update(string, &#39;utf8&#39;).digest(&#39;hex&#39;);
};

function raw1(args) {
  var keys = Object.keys(args);
  keys = keys.sort()
  var newArgs = {};
  keys.forEach(function(key) {
    newArgs[key] = args[key];
  });

  var string = &#39;&#39;;
  for(var k in newArgs) {
    string += &#39;&&#39; + k + &#39;=&#39; + newArgs[k];
  }
  string = string.substr(1);
  return string;
};

function paysignjsapi(appid, attach, body, mch_id, nonce_str, notify_url, openid, out_trade_no, spbill_create_ip, total_fee, trade_type) {
  var ret = {
    appid: appid,
    attach: attach,
    body: body,
    mch_id: mch_id,
    nonce_str: nonce_str,
    notify_url: notify_url,
    openid: openid,
    out_trade_no: out_trade_no,
    spbill_create_ip: spbill_create_ip,
    total_fee: total_fee,
    trade_type: trade_type
  };
  var string = raw(ret);
  string = string + &#39;&key=&#39;+key;
  var crypto = require(&#39;crypto&#39;);
  return crypto.createHash(&#39;md5&#39;).update(string, &#39;utf8&#39;).digest(&#39;hex&#39;);
};

function raw(args) {
  var keys = Object.keys(args);
  keys = keys.sort()
  var newArgs = {};
  keys.forEach(function(key) {
    newArgs[key.toLowerCase()] = args[key];
  });

  var string = &#39;&#39;;
  for(var k in newArgs) {
    string += &#39;&&#39; + k + &#39;=&#39; + newArgs[k];
  }
  string = string.substr(1);
  return string;
};

function getXMLNodeValue(node_name, xml) {
  var tmp = xml.split("<" + node_name + ">");
  var _tmp = tmp[1].split("</" + node_name + ">");
  return _tmp[0];
}
Copy after login

In just 3 simple steps, the WeChat payment function of the mini program is connected. The following is the test payment effect diagram

Implementation code for online payment function developed by WeChat applet

Implementation code for online payment function developed by WeChat applet

Thank you for reading, I hope it can help everyone, thank you for your support of this site!

The above is the detailed content of Implementation code for online payment function developed by WeChat applet. For more information, please follow other related articles on 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