Code for developing the online payment function for WeChat applets

Source: Internet
Author: User
This article mainly introduces the implementation of the online payment function for applets. For more information, see this article, for more information, see

Applet online payment function

Recently, the online payment function needs to be used in small programs. so I read the official documents and found that it is very convenient to implement payment in small programs, if you have previously developed the payment under the service number, you will find that the payment in the applet is exactly the same as the development process in the service number, next I will introduce the development process and attention of payment in the applet.

1. activate payment and merchant ID

This process is the same as the payment process for activating the service number. there is nothing to say.


2. obtain the user's openid

On the homepage, we need to obtain the current user's openid in the client js of the applet. by calling the wx. login method, we can get the user's code, and then the developer server obtains the openid using the login credential code.


Wx. login ({success: function (res) {if (res. code) {// initiate a network request 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 ('failed to get the user logon status! '+ Res. errMsg )}}});


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));      }    });

3. get the prepay_id and the payment signature to verify the paySign.

The process of this step is the same as the payment process in the service number, which is divided into client and server

First, let's take a look at the client js

In the service number, we use the following code to call the payment function


Function jsApiCall () {WeixinJSBridge. invoke ('getbrandwcpayrequest', {"appId": "", // public account name, which is input by the merchant "timeStamp": "", // timeStamp, "nonceStr": "", // random string "package": "prepay_id = <% = prepay_id %>", "signType": "MD5 ", // signature method: "paySign": "<% = _ paySignjs %>" // signature}, function (res) {WeixinJSBridge. log (res. err_msg); if (res. err_msg = "get_brand_wcpay_request: OK") {alert ("payment successful! ");} Else {alert (" payment failed! ");}});}

In a small program, we use the wx. requestPayment method to call the payment function. Before that, we must first obtain the prepay_id.


Wx. request ({url: 'https: // yourwebsit/service/getpa', method: 'post', data: {bookingNo: bookingNo,/* Order Number */total_fee: total_fee, /* order amount */openid: openid}, header: {'content-type': 'application/json'}, success: function (res) {wx. requestPayment ({'timestamp': timeStamp, 'noncestr ': nonceStr, 'Package': 'prepay _ id =' + res. data. prepay_id, 'signtype': 'md5', 'paysign': res. data. _ paySignjs, 'success': function (res) {console. log (res) ;}, 'fail ': function (res) {console. log ('fail: '+ JSON. stringify (res) ;}}, fail: function (err) {console. log (err )}})

On the server side, we need to obtain the prepay_id and sign the paySign.


Var bookingNo = req. param ("bookingNo"); var total_timeout = req. param ("total_fee"); var openid = req. param ("openid"); var body = "billing description"; var url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; var formData ="
 
  
"; FormData + =" appid"; // Appid formData + =" test"; FormData + =""+ Body +""; FormData + ="
  
   
Mch_id
  "; // Merchant ID formData + ="
  
   
Nonce_str
  "; FormData + ="
  
   
Notify_url
  "; FormData + ="
  
   
"+ Openid +"
  "; FormData + ="
  
   
"+ BookingNo +"
  "; FormData + ="
  
   
Spbill_create_ip
  "; FormData + ="
  
   
"+ Total_detail +"
  "; FormData + ="
  
   
JSAPI
  "; FormData + ="
  
   
"+ Paysignjsapi (appid, attach, body, mch_id, nonce_str, yy_url, openid, bookingNo, spbill_create_ip, total_fee, 'jsapi') +"
  "; FormData + ="
 "; Request ({url: url, method: 'post', body: formData}, function (err, response, body) {if (! Err & response. statusCode = 200) {var prepay_id = getXMLNodeValue ('prepay _ id', body. toString ("UTF-8"); var tmp = prepay_id.split ('['); var tmp1 = tmp [2]. split (']'); // sign var _ paySignjs = paysignjs (appid, mch_id, 'prepay _ id = '+ tmp1 [0], 'md5', timeStamp ); var o = {prepay_id: tmp1 [0], _ paySignjs: _ paySignjs} res. send (o );}});

The following are the functions used.


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 + '&key='+key;  console.log(string);  var crypto = require('crypto');  return crypto.createHash('md5').update(string, 'utf8').digest('hex');};function raw1(args) {  var keys = Object.keys(args);  keys = keys.sort()  var newArgs = {};  keys.forEach(function(key) {    newArgs[key] = args[key];  });  var string = '';  for(var k in newArgs) {    string += '&' + k + '=' + 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 + '&key='+key;  var crypto = require('crypto');  return crypto.createHash('md5').update(string, 'utf8').digest('hex');};function raw(args) {  var keys = Object.keys(args);  keys = keys.sort()  var newArgs = {};  keys.forEach(function(key) {    newArgs[key.toLowerCase()] = args[key];  });  var string = '';  for(var k in newArgs) {    string += '&' + k + '=' + newArgs[k];  }  string = string.substr(1);  return string;};function getXMLNodeValue(node_name, xml) {  var tmp = xml.split("<" + node_name + ">");  var _tmp = tmp[1].split("
 ");  return _tmp[0];}

In this case, the payment function of the applet is connected in three simple steps. the following shows the payment for the test.


Thank you for reading this article. I hope it will help you. thank you for your support for this site!

The above is the code details for implementing the online payment function developed by applets. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.