wx-login/app/src/routes-simple/wx-mp-login.ts
2025-03-01 13:50:00 +08:00

75 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { SimpleRouter } from '@kevisual/router/simple';
import crypto from 'crypto';
import xml2js from 'xml2js';
export const simpleRouter = new SimpleRouter();
simpleRouter.get('/api/wxmsg', async (req, res) => {
const query = simpleRouter.getSearch(req);
const body = await simpleRouter.getBody(req);
const {
signature, // 微信加密签名signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp, // 时间戳
nonce, // 随机数
echostr, // 随机字符串
} = query;
const token = 'xiongabc123';
let str = [token, timestamp, nonce].sort().join('');
let strSha1 = crypto.createHash('sha1').update(str).digest('hex');
// 签名对比相同则按照微信要求返回echostr参数值
if (signature == strSha1) {
res.end(echostr);
} else {
res.end('send fail');
}
});
export const getJsonFromXml = async (req: any): Promise<any> => {
return await new Promise((resolve) => {
// 读取请求数据
let data = '';
req.setEncoding('utf8');
// 监听data事件接收数据片段
req.on('data', (chunk) => {
data += chunk;
});
// 当请求结束时处理数据
req.on('end', () => {
try {
// 使用xml2js解析XML
xml2js.parseString(data, function (err, result) {
if (err) {
console.error('XML解析错误:', err);
resolve(null);
} else {
const jsonString = JSON.stringify(result);
resolve(jsonString);
}
});
} catch (error) {
console.error('处理请求时出错:', error);
resolve(null);
}
});
});
};
simpleRouter.post('/api/wxmsg', async (req, res) => {
console.log('tuisong');
const msg = await getJsonFromXml(req);
console.log('Receive:', msg);
const builder = new xml2js.Builder();
const result = builder.buildObject({
xml: {
ToUserName: msg.FromUserName,
FromUserName: msg.ToUserName,
CreateTime: Date.now(),
MsgType: msg.MsgType,
Content: 'Hello ' + msg.Content,
},
});
res.end(result);
});
export const listen = async (req, res) => {
return await simpleRouter.parse(req, res);
};