2026-07-27 11:28:33 +08:00

71 lines
2.1 KiB
JavaScript

const crypto = require("@wecom/crypto");
const xml2js = require("xml2js");
const weCom = require("./weCom/index");
const token = "LNNwUNiMZnEMTa9JOEhspoVB5";
const aeskey = "53Onm6kkDzNyszxqLdumhq6SEnIZtQtBeIsITEyusi9";
function decodeParams(params) {
return Object.keys(params).reduce((acc, key) => {
acc[key] = decodeURIComponent(params[key]);
return acc;
}, {});
}
async function parserXml(decodedString) {
return new Promise((resolve, reject) => {
const parser = new xml2js.Parser();
parser.parseString(decodedString, (err, result) => {
if (err) {
reject(err);
return;
}
resolve(result);
});
});
}
async function processPostRequest(body) {
const decodedString = Buffer.from(body, "base64").toString("utf-8");
const xmlRes = await parserXml(decodedString);
const encrypt = xmlRes.xml.Encrypt[0];
const messageXML = crypto.decrypt(aeskey, encrypt);
console.log(messageXML);
const callbackDataBody = await parserXml(messageXML.message);
for (const key in callbackDataBody.xml) {
if (Array.isArray(callbackDataBody.xml[key])) {
callbackDataBody.xml[key] = callbackDataBody.xml[key][0];
}
}
await weCom.getWeComData(callbackDataBody.xml);
return "success";
}
function data(e) {
const { httpMethod, queryStringParameters } = e;
const { timestamp, nonce, echostr, msg_signature } = decodeParams(queryStringParameters);
const signature = crypto.getSignature(token, timestamp, nonce, echostr);
if (httpMethod === "GET" && signature === msg_signature) {
const { message } = crypto.decrypt(aeskey, echostr);
return message;
} else if (httpMethod === "POST") {
return processPostRequest(e.body);
}
}
exports.httpGet = async function (item) {
const { timestamp, nonce, echostr, msg_signature } = decodeParams(item);
const signature = crypto.getSignature(token, timestamp, nonce, echostr);
if (signature === msg_signature) {
const { message } = crypto.decrypt(aeskey, echostr);
return message;
}
};
exports.httpPost = processPostRequest;
exports.main = async function (e) {
return data(e);
};