The original

Recently in personal, public, also published some of their own technology, at the same time in order to add powder, so add a reply to the function of the keywords for the demo, but should be in every setting keyword WeChat public platform Settings, more tedious, so think of directly using the back-end control, however, is limited by its back-end strength, It was difficult to build a complete system, so a compromise was reached.

object-oriented

  1. Not familiar with the back end, but with basic programming thinking;
  2. Understand the basics of operations (see my other article deploying your own blog from scratch under CentOS);
  3. Simple function, no complex scene, more suitable for individuals.

The development process

tool

Must be

  • A server
  • A domain name

The software is recommended

  1. SSH tools: Mobaxterm(Windows), Nuoshell (MAC) — both are free and available from the command line on Linux
  2. Nginx: Other tools are also available, without proxy Apache
  3. Pm2: Easy to manage Express applications

Installation tools

  1. Install Node and nginx

As described in previous articles, I will not repeat the details of deploying my blog from scratch under CentOS

  • NPM command, I all use taobao image, with CNPM command speed will be much faster
  1. Install Express scaffolding and PM2
npm install express-generator -g
npm install pm2 -g
Copy the code
  • It is recommended to install express scaffolding directly, so that routing and other things are ready to use, of course, want to customize, can only install Express scaffolding.
  1. Create a wechat project and install dependencies
express -e wechat
cd wechat
npm install
Copy the code

Apply wechat parameters

We can first use it in the test environment, test the account application page on the wechat public platform interface, create the basic parameters, and remember the token parameters.

The code

The function development

  1. This step requires crypto to be installed
npm install crypto
Copy the code

According to the document description, sort the fields and encrypt them to compare with the signature, the code

const crypto = require('crypto'); router.get('/', function (req, res, next) { const signature = req.query.signature; const timestamp = req.query.timestamp; const nonce = req.query.nonce; const echostr = req.query.echostr; Let array = new array (' token set by wechat background ', timestamp, nonce); array.sort(); let str = array.toString().replace(/,/g, ""); Let sha1Code = crypto.createHash("sha1"); let code = sha1Code.update(str, 'utf-8').digest("hex"); If (code === signature) {res.send(echostr)} else {res.send("error"); if (code === signature) {res.send("error"); }});Copy the code
  1. Response function

Since all interactions with wechat are in XML format, we also need to install an XML parsing library

npm install xml2js -s
Copy the code

Parse the received message

const parseString = require('xml2js').parseString; router.post("/", (req, res) => { var buffer = []; req.on('data', function (data) { buffer.push(data); }); req.on('end', function () { var msgXml = Buffer.concat(buffer).toString('utf-8'); parseString(msgXml, { explicitArray: false }, (err, result) => { if (err) { throw err; } result = result.xml; var toUser = result.ToUserName; var fromUser = result.FromUserName; If (result.msgType === "text") {// text message} else if (result.msgType === "image") {// Image message} else if ('event' === = "image") Result. The MsgType) {if (= = = 'subscribe' result. The Event) {/ / be attention}}})})});Copy the code

Reply text message

let str = `<xml><ToUserName><! [CDATA[${fromUser}]]> </ToUserName><FromUserName><! [CDATA[${toUser}]]></FromUserName> <CreateTime>${new Date().getTime()}</CreateTime> <MsgType><! [CDATA[text]]></MsgType> <Content><! [CDATA[the text Content of your reply]]></Content></ XML > '; res.send(str);Copy the code
  1. The menu features
  • Menu function is only open to the authentication of the public number, because I did not authenticate the public number, so in the official number, did not send to achieve, but the test is possible.
Axios. Post (` https://api.weixin.qq.com/cgi-bin/menu/create?access_token= access to the access_token `, 'content' menu). Then ((response) = > {the if (response) data) errcode = = 0) {/ / success}}). The catch ((error) = > {} / / failure);Copy the code

The dynamic update of each function is realized without database

Focus. That’s the main thing

Instead of using a database, we use a JSON configuration file to simulate the database. How do we do that?

The FS library gives us an API

/**
     * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed.
     * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
     * URL support is _experimental_.
     */
    export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void;
Copy the code

So it’s easy to register a listener when Node is started and update data in real time without restarting the server.

The agent

Because wechat only supports port 80/443, we need to use the nginx agent. Of course, the port is not used, you can run node directly on this port. For example, if port 443 is enabled, the proxy configuration is as follows

server { listen 443 ssl; Server_name Proxy domain name; Ssl_certificate signature file; Ssl_certificate_key signature file; ssl_session_cache shared:SSL:1m; ssl_session_timeout 5m; ssl_ciphers HIGH:! aNULL:! MD5; ssl_prefer_server_ciphers on; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Nginx-Proxy true; proxy_set_header Connection ""; // Enter the actual address and port proxy_pass http://127.0.0.1:3000; proxy_redirect default; #root html; #index index.html index.htm; }}Copy the code

run

At this point, all development is complete, and we can test the effect if we want

npm start
Copy the code

If we publish it, it won’t stay on the terminal, so we use the PM2 command

pm2 start bin/www
Copy the code

More commands, you can search by yourself.

The demo access

This article is participating in the “Nuggets 2021 Spring Recruitment Campaign”, click to see the details of the campaign