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>
不知道是什么原因导致的回复不了!
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.