Simple Payment examples and precautions for WeChat applets

Source: Internet
Author: User
Tags openid
This article mainly introduces the information about simple payment examples for small programs. here, we refer to the simple examples written in the official documents and put forward the precautions. if you need a friend, you can refer to the small program for payment.

The payment of mini-programs is similar to that of public accounts, and the comparison is simpler than that of public accounts, we only need to call the unified order interface to obtain the prepay_id, and then we can make the payment in the call.

Today, we will encapsulate the payment interface of a common node !!!

First, call the unified order interface. we need to know some information.

Var bookingNo = 'davdian '+ this. createNonceStr () + this. createTimeStamp () var deferred = Q. defer () var appid = config. appId var nonce_str = this. createNonceStr () var timeStamp = this. createTimeStamp () var url = "https://api.mch.weixin.qq.com/pay/unifiedorder" var formData ="
 
  
"FormData + =" "+ appid +""// Appid formData + =" "+ attach +""// Add data formData + =""+ Body +""FormData + ="
  
   
"+ Mch_id +"
  "// Merchant ID formData + ="
  
   
"+ Nonce_str +"
  "// Random string, no longer than 32 characters. FormData + ="
  
   
"+ Notify_url +"
  "FormData + ="
  
   
"+ Openid +"
  "FormData + ="
  
   
"+ BookingNo +"
  "FormData + ="
  
   
61.50.221.43
  "FormData + ="
  
   
"+ Total_detail +"
  "FormData + ="
  
   
JSAPI
  "FormData + ="
  
   
"+ This. paysignjsapi (appid, attach, body, mch_id, nonce_str, yy_url, openid, bookingNo, '61. 50.221.43 ', total_fee, 'jsapi') +"
  "FormData + ="
 "Var self = this request ({url: url, method: 'post', body: formData}, function (err, response, body) {if (! Err & response. statusCode == 200) {var prepay_id = self. getXMLNodeValue ('prepay _ id', body. toString ("UTF-8") var tmp = prepay_id.split ('[') var tmp1 = tmp [2]. split (']') // sign var _ paySignjs = self. paysignjs (appid, nonce_str, 'prepay _ id = '+ tmp1 [0], 'md5', timeStamp) var args = {appId: appid, timeStamp: timeStamp, nonceStr: nonce_str, signType: "MD5", package: tmp1 [0], paySign: _ paySignjs} deferred. resolve (args)} else {console. log (body) }}) return deferred. promise

This is a uniform order interface code. we need the appid mini-program public id, mch_id merchant id, the unique entity of the openid mini-program, and the key payment password, the rest of the parameters are order information, price, and so on. I use promise in the q module for require. This varies from person to person and can be set as needed. We need to request the https://api.mch.weixin.qq.com/pay/unifiedorderinterface

Note: The formdata passed here is an xml object instead of a json object.

Then we need to sign the method. here we need to encapsulate two methods. one is to use the signing method to call the unified order interface, and the other is to call the applet for payment.

Uniform order interface sign:

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 = this.raw(ret)   string = string + '&key=' + key   var crypto = require('crypto')   var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex')   return sign.toUpperCase()

Payment sign:

var ret = {    appId: appid,    nonceStr: nonceStr,    package: package,    signType: signType,    timeStamp: timeStamp  }  var string = this.raw(ret)  string = string + '&key=' + key  var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex')  return sign.toUpperCase()

Note that during encryption, we get a string instead of a json string. Therefore, we need to convert json to a string. the code is as follows:

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

The uniform order interface returns xml with prepay_id, so we need a method for parsing. the code is as follows:

var tmp = xml.split("<" + node_name + ">")  var _tmp = tmp[1].split("
 ")  return _tmp[0]

Finally, we only need to connect these together to obtain all the parameters required for payment. the code is as follows:

// Small program payment encapsulation, currently supporting md5 encryption, does not support sha1/***** create order by jianchep 2016/11/22 ***/var config = require ('.. /config/weapp. js ') var Q = require ("q") var request = require ("request") var crypto = require ('Crypto') var ejs = require ('ejs ') var fs = require ('Fs') var key = config. keymodule. exports = {// get prepay_id getXMLNodeValue: function (node_name, xml) {var tmp = xml. split ("<" + node_name + ">") var _ tmp = tmp [1]. split ("
 ") Return _ tmp [0]}, // object --> string raw: function (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}, // random string generation function createNonceStr: function () {return Math. random (). toString (36 ). substr (2, 15)}, // timestamp generation function createTimeStamp: function () {return parseInt (new Date (). getTime ()/1000) + ''}, // Obtain the sign paysignjs: function (appid, nonceStr, package, signType, timeStamp) through md5 encryption. {var ret = {appId: appid, nonceStr: nonceStr, package: package, signType: signType, timeStamp: timeStamp} var string = this. raw (ret) string = string + '& key =' + key var sign = crypto. createHash ('md5 '). update (string, 'utf8 '). digest ('Hex') return sign. toUpperCase ()}, // unified order interface for encrypted acquisition of sign functions: function (appid, attach, body, mch_id, nonce_str, yy_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, policy_url: policy_url, openid: openid, out_trade_no: out_trade_no, role: spbill_create_ip, total_fee: total_fee, trade_type: trade_type} var string = this. raw (ret) string = string + '& key =' + key var crypto = require ('Crypto') var sign = crypto. createHash ('md5 '). update (string, 'utf8 '). digest ('Hex') return sign. toUpperCase ()}, // order: function (attach, body, mch_id, openid, total_detail, policy_url) {var bookingNo = 'daved' + this. createNonceStr () + this. createTimeStamp () var deferred = Q. defer () var appid = config. appId var nonce_str = this. createNonceStr () var timeStamp = this. createTimeStamp () var url =" https://api.mch.weixin.qq.com/pay/unifiedorder "Var formData ="
 
  
"FormData + =" "+ appid +""// Appid formData + =" "+ attach +""// Add data formData + =""+ Body +""FormData + ="
  
   
"+ Mch_id +"
  "// Merchant ID formData + ="
  
   
"+ Nonce_str +"
  "// Random string, no longer than 32 characters. FormData + ="
  
   
"+ Notify_url +"
  "FormData + ="
  
   
"+ Openid +"
  "FormData + ="
  
   
"+ BookingNo +"
  "FormData + ="
  
   
61.50.221.43
  "FormData + ="
  
   
"+ Total_detail +"
  "FormData + ="
  
   
JSAPI
  "FormData + ="
  
   
"+ This. paysignjsapi (appid, attach, body, mch_id, nonce_str, yy_url, openid, bookingNo, '61. 50.221.43 ', total_fee, 'jsapi') +"
  "FormData + ="
 "Var self = this request ({url: url, method: 'post', body: formData}, function (err, response, body) {if (! Err & response. statusCode == 200) {var prepay_id = self. getXMLNodeValue ('prepay _ id', body. toString ("UTF-8") var tmp = prepay_id.split ('[') var tmp1 = tmp [2]. split (']') // sign var _ paySignjs = self. paysignjs (appid, nonce_str, 'prepay _ id = '+ tmp1 [0], 'md5', timeStamp) var args = {appId: appid, timeStamp: timeStamp, nonceStr: nonce_str, signType: "MD5", package: tmp1 [0], paySign: _ paySignjs} deferred. resolve (args)} else {console. log (body) }}) return deferred. promise }}

Then we encapsulate the order interface:

Unifiedorder: function (req, res) {var body = "test payment" var openid = "openid" var total_detail = 1 var policy_url = "http: // localhost/notify "var mch_id = config. shopId var attach = "test" wxpay. order (attach, body, mch_id, openid, total_fee, policy_url ). then (function (data) {console. log ('data ---> ', data, 123123) res. json (data )})},

Then, we only need to call this interface in the applet to obtain all the payment requirements and then drop the payment.

Here are the pitfalls of small program payment:

1. the unified ordering interface is xml (this is not just a small program, but also a public number), and the returned value is also in xml format. you need to obtain prepay_id by yourself,

2. the signature algorithm must contain the key and be converted to a greater value.

3. the sign algorithm for payment must also contain appid (this is unscientific and deep-seated)

4. the signature algorithm must not use json to splice keys.

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

For more small program payment simple examples and related articles, please pay attention to PHP Chinese network!

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.