Home >Web Front-end >JS Tutorial >An in-depth explanation of how to build WeChat public account backend services using Node.js
1. Foreword
Nowadays, WeChat has become an important channel for many companies and individuals to operate self-media, and building an efficient and stable back-end service for WeChat public accounts has become a necessity. As a lightweight and efficient back-end language, Node.js has received widespread attention for its powerful asynchronous IO capabilities and development efficiency. This article will introduce in a simple and in-depth way how to use Node.js to build a WeChat official account backend service.
2. Preparation
Before starting, you need to prepare the following tools and environment:
3. Build WeChat public account background service
First, create a folder to store the project. Then, enter the folder in the command line and execute the following command:
npm init
After execution, follow the prompts to enter the project name, version, description and other information to complete the project initialization.
Execute the following command to install the necessary dependencies:
npm install express request xml2js
Among them, express is a Web framework developed by Node.js, request It is a library that encapsulates HTTP requests, and xml2js is a library that converts XML into JSON data.
In the project root directory, create a file named index.js and add the following content to the file:
const express = require('express'); const request = require('request'); const { parseString } = require('xml2js'); const app = express(); app.get('/api/wechat', (req, res) => { const { signature, timestamp, nonce, echostr } = req.query; // 排序和拼接字符串 const str = [process.env.TOKEN, timestamp, nonce].sort().join(''); const sha1 = require('crypto').createHash('sha1'); sha1.update(str); const code = sha1.digest('hex'); if (code === signature) { return res.send(echostr); // 校验成功,原样返回 echostr 参数内容 } res.send(); // 校验失败,返回空响应 });
The above code implements the access verification of WeChat public accounts. For specific implementation methods, please refer to the official website documentation.
In the project root directory, create a file named message.js for processing WeChat messages. Add the following content to the file:
/** * 解析 XML 数据 * @param {string} xmlStr XML 字符串 */ function parseXML(xmlStr) { const options = { explicitArray: false, // 不将子元素变为数组 ignoreAttrs: true, // 忽略属性 }; return new Promise((resolve, reject) => { parseString(xmlStr, options, (err, result) => { if (err) { return reject(err); } resolve(result.xml); }); }); } module.exports = function handleWechatMessage(req, res) { let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', async () => { const { ToUserName, FromUserName, CreateTime, MsgType, Event, Content, EventKey, } = await parseXML(body); let replyXML; switch (MsgType) { case 'text': // 处理文本消息 replyXML = `<xml> <ToUserName><![CDATA[${FromUserName}]]></ToUserName> <FromUserName><![CDATA[${ToUserName}]]></FromUserName> <CreateTime>${Math.floor(Date.now() / 1000)}</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[${Content}]]></Content> </xml>`; break; case 'event': // 处理事件消息 if (Event === 'subscribe') { // 处理关注事件 replyXML = `<xml> <ToUserName><![CDATA[${FromUserName}]]></ToUserName> <FromUserName><![CDATA[${ToUserName}]]></FromUserName> <CreateTime>${Math.floor(Date.now() / 1000)}</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[欢迎关注]]></Content> </xml>`; } else if (Event === 'unsubscribe') { // 处理取消关注事件 console.log('用户取消关注'); } else if (Event === 'CLICK' && EventKey === 'test') { // 处理菜单点击事件 replyXML = `<xml> <ToUserName><![CDATA[${FromUserName}]]></ToUserName> <FromUserName><![CDATA[${ToUserName}]]></FromUserName> <CreateTime>${Math.floor(Date.now() / 1000)}</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[点击了测试菜单]]></Content> </xml>`; } break; default: break; } if (replyXML) { res.setHeader('Content-Type', 'application/xml'); return res.send(replyXML); } res.send(); }); };
The above code parses the message from the WeChat official account, and returns the corresponding reply message after processing.
In index.js, add the following code to start the service:
const handleWechatMessage = require('./message'); const server = app.listen(process.env.PORT || 3000, () => { const address = server.address(); console.log(`Server running at http://${address.address}:${address.port}`); }); app.post('/api/wechat', handleWechatMessage);
After starting the service, you can verify it by configuring the server address in the background of the WeChat official account. After successful verification, you can use this address as the backend service address of the WeChat official account. At the same time, you can debug in the code to ensure that messages can be delivered and replied normally.
4. Summary
This article introduces how to use Node.js to build WeChat public account backend services, covering two aspects: access verification and message processing. Through this article, I believe readers can quickly understand and master the basic principles and implementation methods of using Node.js to build WeChat backend services.
The above is the detailed content of An in-depth explanation of how to build WeChat public account backend services using Node.js. For more information, please follow other related articles on the PHP Chinese website!