Home > Web Front-end > JS Tutorial > How to operate the Koa2 WeChat public account to achieve message management

How to operate the Koa2 WeChat public account to achieve message management

php中世界最好的语言
Release: 2018-05-29 11:15:19
Original
2488 people have browsed it

Receive messages

When an ordinary WeChat user sends a message to a public account, the WeChat server will POST the XML data packet of the message to the URL filled in by the developer .

2.1 Receive common message data format

The structure of XML is basically fixed, and different message types are slightly different.

When a user sends a text message, the XML data format received by the WeChat public account is as follows:

<xml>
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>createTime</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[this is a test]]></Content>
 <MsgId>1234567890123456</MsgId>
</xml>
Copy after login

When a user sends a picture message, the XML data format received by the WeChat public account is as follows :

<xml> 
 <ToUserName><![CDATA[toUser]]></ToUserName>
 <FromUserName><![CDATA[fromUser]]></FromUserName>
 <CreateTime>1348831860</CreateTime> 
 <MsgType><![CDATA[image]]></MsgType> 
 <PicUrl><![CDATA[this is a url]]></PicUrl>
 <MediaId><![CDATA[media_id]]></MediaId> 
 <MsgId>1234567890123456</MsgId>
</xml>
Copy after login

For the structure of other message message types, please refer to [WeChat Public Platform Development Documents]

For the processing of POST request, koa2 does not encapsulate the method of obtaining parameters, which is required By parsing the native node.js request object request in the context context by itself. We will use the row-body module to get the data.

2.2 Let’s optimize the previous code first

The code in this section follows the code implemented in the previous session, with slight changes based on the previous session. .

'use strict'
const Koa = require('koa')
const app = new Koa()
const crypto = require('crypto')
// 将配置文件独立到config.js
const config = require('./config')
app.use(async ctx => {
 // GET 验证服务器
 if (ctx.method === 'GET') {
  const { signature, timestamp, nonce, echostr } = ctx.query
  const TOKEN = config.wechat.token
  let hash = crypto.createHash('sha1')
  const arr = [TOKEN, timestamp, nonce].sort()
  hash.update(arr.join(''))
  const shasum = hash.digest('hex')
  if (shasum === signature) {
   return ctx.body = echostr
  }
  ctx.status = 401
  ctx.body = 'Invalid signature'
 } else if (ctx.method === 'POST') { // POST接收数据
  // TODO
 }
});
app.listen(7001);
Copy after login

Here we only verified whether the signature value is legal in GET. In fact, we should also verify the signature in POST.

Write signature verification as a function

function getSignature (timestamp, nonce, token) {
 let hash = crypto.createHash('sha1')
 const arr = [token, timestamp, nonce].sort()
 hash.update(arr.join(''))
 return hash.digest('hex')
}
Copy after login

Optimize the code and add verification to POST

...
app.use(async ctx => {
 const { signature, timestamp, nonce, echostr } = ctx.query
 const TOKEN = config.wechat.token
 if (ctx.method === 'GET') {
  if (signature === getSignature(timestamp, nonce, TOKEN)) {
   return ctx.body = echostr
  }
  ctx.status = 401
  ctx.body = 'Invalid signature'
 }else if (ctx.method === 'POST') {
  if (signature !== getSignature(timestamp, nonce, TOKEN)) {
   ctx.status = 401
   return ctx.body = 'Invalid signature'
  }
  // TODO
 }
});
...
Copy after login

Up to this point we have not started to implement the function of accepting XML data packets, but It is the code before modification. This is to demonstrate the actual development process. Writing any code is not a one-step process, and good code can only be modified.

2.3 Receive XML data packets for ordinary messages from public accounts

Now let’s get to the point of this section, accept XML data packets and convert them to JSON

$ npm install raw-body --save
Copy after login
...
const getRawBody = require('raw-body')
...
// TODO
// 取原始数据
const xml = await getRawBody(ctx.req, {
 length: ctx.request.length,
 limit: '1mb',
 encoding: ctx.request.charset || 'utf-8'
});
console.log(xml)
return ctx.body = 'success' // 直接回复success,微信服务器不会对此作任何处理
Copy after login

Send a text message to your test account, you can see the following data printed out on the command line

<xml>
 <ToUserName><![CDATA[gh_9d2d49e7e006]]></ToUserName>
 <FromUserName><![CDATA[oBp2T0wK8lM4vIkmMTJfFpk6Owlo]]></FromUserName>
 <CreateTime>1516940059</CreateTime>
 <MsgType><![CDATA[text]]></MsgType>
 <Content><![CDATA[JavaScript之禅]]></Content>
 <MsgId>6515207943908059832</MsgId>
</xml>
Copy after login

Congratulations, you can now receive XML data.

The above is the detailed content of How to operate the Koa2 WeChat public account to achieve message management. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template