


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></tousername> <fromusername></fromusername> <createtime>createTime</createtime> <msgtype></msgtype> <content></content> <msgid>1234567890123456</msgid> </xml>
When a user sends a picture message, the XML data format received by the WeChat public account is as follows :
<xml> <tousername></tousername> <fromusername></fromusername> <createtime>1348831860</createtime> <msgtype></msgtype> <picurl></picurl> <mediaid></mediaid> <msgid>1234567890123456</msgid> </xml>
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);
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') }
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 } }); ...
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
... 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,微信服务器不会对此作任何处理
Send a text message to your test account, you can see the following data printed out on the command line
<xml> <tousername></tousername> <fromusername></fromusername> <createtime>1516940059</createtime> <msgtype></msgtype> <content></content> <msgid>6515207943908059832</msgid> </xml>
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!

随着互联网的发展,SEO(SearchEngineOptimization,搜索引擎优化)已经成为了网站优化的重要一环。如果您想要使您的PHP网站在搜索引擎中获得更高的排名,就需要对SEO的内容有一定的了解了。本文将会介绍如何在PHP中实现SEO优化,内容包括网站结构优化、网页内容优化、外部链接优化,以及其他相关的优化技巧。一、网站结构优化网站结构对于S

随着电子商务和企业管理的发展,许多企业开始寻找更好的方法来处理其日常业务流程。ERP系统是一种能够整合企业各种业务流程的软件工具。它提供了全面的功能,包括生产、销售、采购、库存、财务等方面,帮助企业提高效率、控制成本和提高客户满意度。而在PHP编程语言中,也能够实现ERP系统,这就需要我们掌握一些基本的知识和技术。下面,我们将深入探讨如何在PHP中实现ERP

随着物联网技术的发展和普及,越来越多的应用场景需要使用PHP语言进行物联网开发。PHP作为一种广泛应用于Web开发的脚本语言,它的易学易用、开发速度快、可扩展性强等特点,使其成为开发物联网应用的一种优秀选择。本文将介绍在PHP中实现物联网开发的常用技术和方法。一、传输协议和数据格式物联网设备通常使用TCP/IP或UDP协议进行数据传输,而HTTP协议是一个优

随着企业的发展,客户管理变得越来越重要。为了提高客户满意度和忠诚度,越来越多的企业采用客户关系管理系统(CRM)来帮助其管理客户关系。而PHP是一种流行的编程语言,因其简单易学、灵活和强大而被广泛应用于Web开发。那么,如何在PHP中实现CRM系统呢?本文将为您介绍实现CRM系统的步骤和技巧。Step1:需求分析在开始开发CRM系统之前,您需要进行需求分析

智能合约(SmartContract)是一种基于区块链的自动化交易程序,可以实现自动化执行、验证和执行交易。智能合约可以减少交易中的人为干扰,提高交易的安全性和效率。在不同的区块链中,智能合约的实现方式略有不同。本文将介绍在PHP中如何实现智能合约。PHP是一种广泛使用的编程语言,特别适合Web开发。PHP有着成熟的开源生态系统,以及许多可靠的框架和库。在

随着互联网的不断发展,越来越多的网站需要使用验证码来保证安全性。验证码是一种借助人类能力而无法被计算机破解的认证技术,广泛应用于网站注册、登录、找回密码等功能中。下面将介绍如何使用PHP实现验证码功能。一、生成验证码图片验证码图片的生成是验证码功能的核心,需要生成一个随机字符,并将其渲染为图像展示给用户。在PHP中,可以使用GD库来生成图片。GD库是一种用于

随着现代企业管理的需求与时俱进,各种管理软件如ERP、CRM、HRM和OA等软件的使用已经变得越来越普遍。特别是办公自动化(OA)软件,已经成为企业必不可少的一部分。随着PHP发展的越来越成熟,越来越多的企业开始使用PHP作为开发OA软件的工具,并取得了很好的效果。那么,在PHP中如何实现OA开发呢?确定OA的需求在开始OA的开发之前,必须先明确自己的OA需

随着移动互联网的发展,微信已经成为了人们生活中不可或缺的一部分,越来越多的商家选择在微信平台上开展业务。实现微信支付功能对于商家来说是非常必要的。本文将介绍如何使用PHP实现JSAPI支付。首先,我们需要了解什么是JSAPI支付。JSAPI是微信公众号支付功能的一种,通过JS调用微信支付接口实现支付。JSAPI支付的优点在于用户只需要在微信中进行支付,不需要


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.