import { Injectable, NestMiddleware } from '@nestjs/common'
import { Request } from 'express'
import * as xml2js from 'xml2js'
const parseString = xml2js.parseString
const parseXml = (xml: string): any => {
return new Promise((resolve, reject) => {
parseString(xml, { explicitArray: false }, function (err, result) {
if (!err) {
resolve(result)
} else {
reject(err)
throw err
}
})
})
}
@Injectable()
export class XMLMiddleware implements NestMiddleware {
use (req: Request, res: any, next: () => void) {
const buffer = []
req.on('data', (data) => {
buffer.push(data)
})
req.on('end', async () => {
console.log(req.query)
const msgXml = Buffer.concat(buffer).toString('utf-8')
const xmlData = await parseXml(msgXml)
req.body = xmlData
next()
})
}
}
@Public()
@Post('callback')
async postMsg (@Body() body: {xml: any}, @Req() req: Request, @Res() res: Response) {
const xml = body.xml
if (xml.MsgType.toLowerCase() === 'text') {
const fromUserName = xml.FromUserName
const toUserName = xml.ToUserName
const content = xml.Content
const replyXml = await this.weixinService.sendTextMsg(fromUserName, toUserName, content)
console.log(replyXml)
res.type('application/xml')
res.end(replyXml)
}
}
结果如下
// query 信息
{
signature: '5bd7841d375e610c6c78f1219d910acf0e61549d',
timestamp: '1668078826',
nonce: '1894931224',
openid: 'o2gkvuBvc_il-f0As0GjBzlqknJo'
}
// body 信息
{
xml: {
ToUserName: 'gh_4440d1e4f1af',
FromUserName: 'o2gkvuBvc_il-f0As0GjBzlqknJo',
CreateTime: '1668078825',
MsgType: 'text',
Content: '123123',
MsgId: '23881145195544631'
}
}
所有实现感觉都没啥问题;但是就是回复不了信息
返回信息如下
// 收到 xml 信息
{
xml: {
ToUserName: 'gh_4440d1e4f1af',
FromUserName: 'o2gkvuBvc_il-f0As0GjBzlqknJo',
CreateTime: '1668078825',
MsgType: 'text',
Content: '123123',
MsgId: '23881145195544631'
}
}
// 返回给微信服务器的信息;
<xml><ToUserName><![CDATA[o2gkvuBvc_il-f0As0GjBzlqknJo]]></ToUserName><FromUserName><![CDATA[gh_4440d1e4f1af]]></FromUserName><CreateTime>1668078827925</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[123123]]></Content></xml>
不知道是什么原因导致的回复不了!
1
oppddd OP 看了看 nest 文档 猜测是因为 post 的返回码都是 201 导致的,明天试试
|
2
Giftina 2022-11-11 09:42:15 +08:00
|
3
Giftina 2022-11-11 09:43:55 +08:00
|