


Detailed explanation of nodejs implementation of WeChat payment function example
The most important thing about using WeChat payment through nodejs is WeChat signature. The characters after md5 here must be converted to uppercase. This article mainly introduces the implementation of WeChat payment function based on nodejs in detail. It has certain reference value. If you are interested, Friends, you can refer to it, I hope it can help everyone.
1. Reply to WeChat notification message template
message.ejs
<xml> <return_code><![CDATA[<%-return_code%>]]></return_code> <return_msg><![CDATA[<%=return_msg%>]]></return_msg> </xml>
2. WeChat payment model file code
wxpay.js
##
var config = require('../config'); //配置文件 appid 等信息 var Q = require("q"); var request = require("request"); var crypto = require('crypto'); var ejs = require('ejs'); var fs = require('fs'); var key = "此处为申请微信支付的API密码"; var messageTpl = fs.readFileSync(__dirname + '/message.ejs', 'utf-8'); var WxPay = { getXMLNodeValue: function(node_name, xml) { var tmp = xml.split("<" + node_name + ">"); var _tmp = tmp[1].split("</" + node_name + ">"); return _tmp[0]; }, 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; }, paysignjs: function(appid, nonceStr, package, signType, timeStamp) { 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(); }, paysignjsapi: function(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 = this.raw(ret); string = string + '&key=' + key; //key为在微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->密钥设置 var crypto = require('crypto'); var sign = crypto.createHash('md5').update(string, 'utf8').digest('hex'); return sign.toUpperCase(); }, // 随机字符串产生函数 createNonceStr: function() { return Math.random().toString(36).substr(2, 15); }, // 时间戳产生函数 createTimeStamp: function() { return parseInt(new Date().getTime() / 1000) + ''; },
// 此处的attach不能为空值 否则微信提示签名错误 order: function(attach, body, mch_id, openid, bookingNo, total_fee, notify_url) { var deferred = Q.defer(); var appid = config.member_config.appid; var nonce_str = this.createNonceStr(); var timeStamp = this.createTimeStamp(); var url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; var formData = "<xml>"; formData += "<appid>" + appid + "</appid>"; //appid formData += "<attach>" + attach + "</attach>"; //附加数据 formData += "<body>" + body + "</body>"; formData += "<mch_id>" + mch_id + "</mch_id>"; //商户号 formData += "<nonce_str>" + nonce_str + "</nonce_str>"; //随机字符串,不长于32位。 formData += "<notify_url>" + notify_url + "</notify_url>"; formData += "<openid>" + openid + "</openid>"; formData += "<out_trade_no>" + bookingNo + "</out_trade_no>"; formData += "<spbill_create_ip>61.50.221.43</spbill_create_ip>"; formData += "<total_fee>" + total_fee + "</total_fee>"; formData += "<trade_type>JSAPI</trade_type>"; formData += "<sign>" + this.paysignjsapi(appid, attach, body, mch_id, nonce_str, notify_url, openid, bookingNo, '61.50.221.43', total_fee, 'JSAPI') + "</sign>"; formData += "</xml>"; var self = this; request({ url: url, method: 'POST', body: formData }, function(err, response, body) { if (!err && response.statusCode == 200) { console.log(body); var prepay_id = self.getXMLNodeValue('prepay_id', body.toString("utf-8")); var tmp = prepay_id.split('['); var tmp1 = tmp[2].split(']'); //签名 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; }, //支付回调通知 notify: function(obj) { var output = ""; if (obj.return_code == "SUCCESS") { var reply = { return_code: "SUCCESS", return_msg: "OK" }; } else { var reply = { return_code: "FAIL", return_msg: "FAIL" }; } output = ejs.render(messageTpl, reply); return output; }, }; module.exports = WxPay;
3. Call wxpay in express router
##
//微信支付demo router.get('/order', function(req, res, next){ var attach = "1276687601"; var body = "测试支付"; var mch_id = "1111111"; //商户ID var openid = "111111"; var bookingNo = "201501806125346"; //订单号 var total_fee = 10; var notify_url = "http://localhost/wxpay/notify"; //通知地址 wxpay.order(attach, body, mch_id, openid, bookingNo, total_fee, notify_url).then(function(data){ res.render('wxpay', {args: data}); }); });
//微信回调通知 采用数据流形式读取微信返回的xml数据 此处不在累赘 router.post('/notify', function(req, res, next){ });
Related recommendations:
The above is the detailed content of Detailed explanation of nodejs implementation of WeChat payment function example. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version
Useful JavaScript development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.