


This article mainly introduces NodeJS to implement the automatic reply function after following the WeChat public account. It has certain reference value. Interested friends can refer to it
Logical steps of the real-first automatic reply function
1 Process the POST type control logic and receive the XML data packet;
2 Analysis XML data packet (get the message type of the data packet or the event type);
3 Assemble the message we defined;
4 Pack into XML format;
5 Return within 5 seconds
Second code practice
The code in this section will be modified and improved based on the previous lesson,Directory structure Same as before, the newly introduced module raw-body can be installed using npm install. The app.js startup file and util.js will not be changed. The main modifications are Click the generator.js file, and create a new wechat.js file and tools.js file in the same directory as generator.js.
The wechat.js file is to extract the code of the ticket part in the generator.js file in the previous section and put it into a separate file. The specific code is as follows:
'use strict'; // 引入模块 var Promise = require('bluebird'); var request = Promise.promisify(require('request')); //增加url配置项 var prefix = 'https://api.weixin.qq.com/cgi-bin/'; var api = { accessToken: prefix + 'token?grant_type=client_credential' }; //利用构造函数生成实例 完成票据存储逻辑 function weChat(opts) { var that = this; this.appID = opts.appID; this.appSecret = opts.appSecret; this.getAccessToken = opts.getAccessToken; this.saveAccessToken = opts.saveAccessToken; //获取票据的方法 this.getAccessToken() .then(function(data) { //从静态文件获取票据,JSON化数据,如果有异常,则尝试更新票据 try { data = JSON.parse(data); } catch (e) { return that.updateAccessToken(); } //判断票据是否在有效期内,如果合法,向下传递票据,如果不合法,更新票据 if (that.isValidAccessToken(data)) { Promise.resolve(data); } else { return that.updateAccessToken(); } }) //将拿到的票据信息和有效期信息存储起来 .then(function(data) { //console.log(data); that.access_token = data.access_token; that.expires_in = data.expires_in; that.saveAccessToken(data); }) }; //在weChat的原型链上增加验证有效期的方法 weChat.prototype.isValidAccessToken = function(data) { //进行判断,如果票据不合法,返回false if (!data || !data.access_token || !data.expires_in) { return false; } //拿到票据和过期时间的数据 var access_token = data.access_token; var expires_in = data.expires_in; //获取当前时间 var now = (new Date().getTime()); //如果当前时间小于票据过期时间,返回true,否则返回false if (now < expires_in) { return true; } else { return false; }; }; //在weChat的原型链上增加更新票据的方法 weChat.prototype.updateAccessToken = function() { var appID = this.appID; var appSecret = this.appSecret; var url = api.accessToken + '&appid=' + appID + '&secret=' + appSecret; return new Promise(function(resolve, reject) { //使用request发起请求 request({ url: url, json: true }).then(function(response) { var data = response.body; var now = (new Date().getTime()); var expires_in = now + (data.expires_in - 20) * 1000; //把新票据的有效时间赋值给data data.expires_in = expires_in; resolve(data); }) }) }; //向外暴露weChat module.exports = weChat;
The generator.js file is After simplification, add the formatting method and judgment event of XML data, and add the test information of the event of interest. The specific code is as follows:
'use strict'; // 引入模块 var sha1 = require('sha1'); var getRawBody = require('raw-body'); var weChat = require('./wechat'); var tools = require('./tools'); // 建立中间件函数并暴露出去 module.exports = function(opts) { //实例化weChat()函数 //var wechat = new weChat(opts); return function*(next) { //console.log(this.query); var that = this; var token = opts.token; var signature = this.query.signature; var nonce = this.query.nonce; var timestamp = this.query.timestamp; var echostr = this.query.echostr; // 进行字典排序 var str = [token, timestamp, nonce].sort().join(''); // 进行加密 var sha = sha1(str); //使用this.method对请求方法进行判断 if (this.method === 'GET') { // 如果是get请求 判断加密后的值是否等于签名值 if (sha === signature) { this.body = echostr + ''; } else { this.body = 'wrong'; }; } else if (this.method === 'POST') { //如果是post请求 也是先判断签名是否合法 如果不合法 直接返回wrong if (sha !== signature) { this.body = 'wrong'; return false; }; //通过raw-body模块 可以把把this上的request对象 也就是http模块中的request对象 去拼装它的数据 最终拿到一个buffer的xml数据 //通过yield关键字 获取到post过来的原始的XML数据 var data = yield getRawBody(this.req, { length: this.length, limit: '1mb', encoding: this.charset }); //console.log(data.toString());打印XML数据(当微信公众号有操作的时候 终端可以看到返回的XML数据) //tools为处理XML数据的工具包 使用tools工具包的parseXMLAsync方法 把XML数据转化成数组对象 var content = yield tools.parseXMLAsync(data); //console.log(content);打印转化后的数组对象 //格式化content数据为json对象 var message = tools.formatMessage(content.xml); console.log(message); //打印message //判断message的MsgType 如果是event 则是一个事件 if (message.MsgType === 'event') { //如果是订阅事件 if (message.Event === 'subscribe') { //获取当前时间戳 var now = new Date().getTime(); //设置回复状态是200 that.status = 200; //设置回复的类型是xml格式 that.type = 'application/xml'; //设置回复的主体 that.body = '<xml>' + '<ToUserName><![CDATA[' + message.FromUserName + ']]></ToUserName>' + '<FromUserName><![CDATA[' + message.ToUserName + ']]></FromUserName>' + '<CreateTime>' + now + '</CreateTime>' + '<MsgType><![CDATA[text]]></MsgType>' + '<Content><![CDATA[你好,同学!]]></Content>' + '</xml>'; return; } } } } };
tools.js is a tool file for processing XML data:
'use strict'; //引入模块 var xml2js = require('xml2js'); var Promise = require('bluebird'); //导出解析XML的方法 exports.parseXMLAsync = function(xml) { return new Promise(function(resolve, reject) { xml2js.parseString(xml, { trim: true }, function(err, content) { if (err) { reject(err); } else { resolve(content); }; }); }); }; //因为value值可能是嵌套多层的 所以先对value值进行遍历 function formatMessage(result) { //声明空对象message var message = {}; //对result类型进行判断 if (typeof result === 'object') { //如果是object类型 通过Object.keys()方法拿到result所有的key 并存入keys变量中 var keys = Object.keys(result); //对keys进行循环遍历 for (var i = 0; i < keys.length; i++) { //拿到每个key对应的value值 var item = result[keys[i]]; //拿到key var key = keys[i]; //判断item是否为数组或者长度是否为0 if (!(item instanceof Array) || item.length === 0) { //如果item不是数组或者长度为0 则跳过继续向下解析 continue; } //如果长度为1 if (item.length === 1) { //拿到value值存入val变量 var val = item[0]; //判断val是否为对象 if (typeof val === 'object') { //如果val为对象 则进一步进行遍历 message[key] = formatMessage(val); } else { //如果不是对象 就把值赋给当前的key放入message里 并去除收尾空格 message[key] = (val || '').trim(); } } //如果item的长度既不是0也不是1 则说明它是一个数组 else { //把message的key设置为空数组 message[key] = []; //对数组进行遍历 for (var j = 0, k = item.length; j < k; j++) { message[key].push(formatMessage(item[j])); } } } } return message; } exports.formatMessage = function(xml) { return new Promise(function(resolve, reject) { xml2js.parseString(xml, { trim: true }, function(err, content) { if (err) { reject(err); } else { resolve(content); }; }); }); }; exports.formatMessage = formatMessage;
After completing the code in this section, when following the WeChat test public account, it will automatically reply "Hello, classmate!" 』 prompt message.
The above is the detailed content of Detailed introduction on how to use NodeJS to implement the automatic reply function after following the WeChat official account. For more information, please follow other related articles on the PHP Chinese website!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
