Using node.js for WeChat public account development - access

This article is participating in the technical topic call for Node.js advanced road, click to view details

foreword

A while ago, I started a public account, and I also came into contact with the development of the public account during the exploration period. I will record the experience during the exploration process and share it with you. Since I have not experienced the back-end learning of the system, the following steps and ideas are all personal online. It is based on exploration and thinking. It does not guarantee authority. It is for reference only.

Access process - WeChat side

First, we log in to the official account background and find the basic settings in the left menu

image.png

After clicking Modify Configuration, we will enter the parameter filling page

image.png

Below we analyze each parameter.

Parameter Description

URL

Must start with http://or https://to support port 80 and port 443 respectively. Here we need to fill in our back-end address, the user's operation request WeChat will be forwarded to this address, it should be noted that this address only supports port 80 and port 443, so we have two methods

  • A separate subdomain name (both secondary and tertiary) will be assigned to the backend service, which is the method adopted in this article
  • Use Nginx for proxying. If your backend service does not use port 80 or 443, you can use Nginx to forward the request to the address where the backend is located.

Token

Token can be filled in by us, mainly used to generate a signature. When we initially access, WeChat will use the token to generate a secret key and send it to the server. The server verifies the secret key. If the verification is successful, the access will be successful.

EncodingAESKey

EncodingAESKey can be generated by our handwriting or by clicking the random generation button. This is the encryption and decryption of the message body sent by WeChat to the server in the later period of the main user, which we will talk about later.

message encryption and decryption

  • Plaintext mode: no encryption
  • Compatibility Mode: Coexistence of encryption without encryption
  • Security Mode: Encrypted

Since this article does not involve subsequent message processing, we will not talk about it for the time being. When we talk about message processing later, we will talk about it. We can choose compatibility mode during development.

Access Process - Server Side

Server Authentication

All are filled in, we click submit, we will find that the system pops up an error pop-up window, telling us that the token verification failed

3.png

This is because we only configured it on the WeChat side, but did not respond on the server side. Let's first see if the server has received the message

image.png

可以看到我们已经收到了微信的验证消息,下面我们只要对微信进行正确的回应就好了。

首先我们要知道微信发送的这串消息都涵盖了哪些参数,都是什么意思,我们需要怎么回应。

微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示

参数 描述
signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp 时间戳
nonce 随机数
echostr 随机字符串

signature有我们之前填写的token和微信get请求中的timestamp、nonce共同组合加密而成,我们收到之后需要对signature进行解码,然后对解码出来的token进行验证 ,验证完成之后返回echostr参数给微信即可完成接入。

signature的加密规则如下:

  1. 将token、timestamp、nonce三个参数进行字典序排序
  2. 将三个参数字符串拼接成一个字符串进行sha1加密

字典序排序其实就是按字母顺序排序,我们使用js中数组的sort方法即可。

接下来我们要在服务端对请求进行处理,来完成接入流程。

因为我们之前在微信填写的服务端地址为域名/wx,所以我们先把/wx这个路由的请求放到白名单中,不进行权限校验。

上面我们说了,signature的加密规则用到了sha1加密,这里我们可以使用node.js自带的方法来实现一个sha1加密

// encryption.js
const crypto = require('crypto')

module.exports = {
  md5: (str) => {
    return crypto.createHash('md5').update(str).digest('hex')
  },
  sha1: (str) => {
    return crypto.createHash('sha1').update(str).digest('hex')
  }
}

复制代码

之后我们就可以对微信的验证消息进行验证并处理了

const encryption = require('../utils/encryption')
class WxController {
  async index(ctx) {
    let {signature = '', timestamp = '', nonce = '', echostr = ''} = ctx.query
    let token = process.env.wx_token

    // 验证token
    let str = [token, timestamp, nonce].sort().join('')
    let sha1 = encryption.sha1(str)
    if (sha1 !== signature) {
      ctx.body = 'token验证失败'
      return
    } else {
      ctx.body = echostr
    }
  }
}

module.exports = new WxController()
复制代码

改完之后我们部署到服务器,然后再去微信侧点击一下提交,可以看到,已经可以提交成功了。

image.png

之后我们点击启用按钮,会提示我们启用之后公众平台的自定义菜单和自动回复将会失效,所有的请求都会转发到我们自己的服务端

image.png

之后我们去公众号测试一下

4cd526afbbd81fa1cdeaac78d130ae2.jpg

会发现微信提示我们公众号服务故障,这是因为我们还没有对发送的消息做任何处理,然后我们去服务端看看

image.png

It can be seen that we have successfully received the request forwarded by WeChat, indicating that we have successfully connected. We only need to process the information according to the regulations of WeChat, and then return the necessary information, which will be placed later. the article says.

By the way, there are very few permissions for personal public accounts.

Guess you like

Origin juejin.im/post/7079929519976480799