feat(wechat): 新增小程序/公众号消息与事件推收入口 /events/appid/:appid(URL验证/事件分发/关键词自动回复/加密被动回复,参考 PHP Index::events)
This commit is contained in:
parent
2c9f656ac9
commit
7238621025
@ -333,6 +333,298 @@ class WechatOpenController extends Controller {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 授权方(小程序/公众号)消息与事件推收入口,参考 PHP /index/index/events/appid/$APPID$。
|
||||
* GET=服务器地址 URL 有效性验证(echostr),POST=消息/事件推送(组件密钥加密)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async events() {
|
||||
const { ctx, app } = this;
|
||||
const { params } = ctx;
|
||||
const appid = String((params && params.appid) || '').trim();
|
||||
const config = app.config.wechatOpen || {};
|
||||
|
||||
if (!appid) {
|
||||
ctx.logger.error('[wechatOpen.events] 缺少 appid 参数');
|
||||
ctx.body = 'success';
|
||||
return;
|
||||
}
|
||||
|
||||
const signature = String(ctx.query.signature || '');
|
||||
const timestamp = String(ctx.query.timestamp || '');
|
||||
const nonce = String(ctx.query.nonce || '');
|
||||
const echostr = String(ctx.query.echostr || '');
|
||||
const msgSignature = String(ctx.query.msg_signature || '');
|
||||
|
||||
// ─── URL 有效性验证(首次配置服务器地址时) ───────────────
|
||||
if (echostr) {
|
||||
ctx.body = await this.verifyEventUrl(appid, signature, timestamp, nonce, echostr);
|
||||
return;
|
||||
}
|
||||
|
||||
// ─── 消息/事件推送 ───────────────────────────────────────
|
||||
try {
|
||||
const rawBody = await this.readRawBody();
|
||||
if (!rawBody || !rawBody.trim()) {
|
||||
ctx.logger.error(`[wechatOpen.events] 事件推送数据为空 appid=${appid}`);
|
||||
ctx.body = 'success';
|
||||
return;
|
||||
}
|
||||
|
||||
const decryptResult = wechatOpenCrypt.decryptMsg({
|
||||
token: config.token,
|
||||
encodingAesKey: config.encoding_aes_key,
|
||||
componentAppid: config.component_appid,
|
||||
msgSignature,
|
||||
timestamp,
|
||||
nonce,
|
||||
encryptedXml: rawBody,
|
||||
});
|
||||
|
||||
if (decryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) {
|
||||
ctx.logger.error(`[wechatOpen.events] 消息解密失败 appid=${appid} code=${decryptResult.code} msg=${decryptResult.msg}`);
|
||||
ctx.body = 'success';
|
||||
return;
|
||||
}
|
||||
|
||||
const data = wechatOpenCrypt.parseXml(decryptResult.msg);
|
||||
ctx.logger.info(`[wechatOpen.events] 事件推送 appid=${appid}: ${decryptResult.msg}`);
|
||||
|
||||
const msgType = String(data.MsgType || '');
|
||||
const event = String(data.Event || '');
|
||||
|
||||
switch (msgType) {
|
||||
case 'event':
|
||||
await this.handlePushEvent(appid, event, data);
|
||||
break;
|
||||
|
||||
case 'text': {
|
||||
// 记录文本消息并自动回复(有被动回复时返回加密 XML)
|
||||
const reply = await this.autoReply(appid, data, nonce);
|
||||
if (reply) {
|
||||
ctx.logger.info(`[wechatOpen.events] 被动回复用户消息 appid=${appid} openid=${data.FromUserName}`);
|
||||
ctx.type = 'application/xml';
|
||||
ctx.body = reply;
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'image':
|
||||
await this.recordUserAction(appid, data, 'image');
|
||||
break;
|
||||
|
||||
default:
|
||||
ctx.logger.info(`[wechatOpen.events] 未处理的消息类型 appid=${appid} MsgType=${msgType}`);
|
||||
break;
|
||||
}
|
||||
|
||||
// 微信要求回显 success 表示处理成功
|
||||
ctx.body = 'success';
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 处理异常 appid=${appid}: ${e.message}`, e);
|
||||
ctx.body = 'success';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证事件推送服务器 URL(参考 PHP verifyEventUrl)。
|
||||
* 对应授权方须已在 wms_wechat_app 登记;签名使用第三方平台(组件)Token 校验。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} signature 微信回传签名。
|
||||
* @param {string} timestamp 时间戳。
|
||||
* @param {string} nonce 随机串。
|
||||
* @param {string} echostr 回显串。
|
||||
* @return {Promise<string>} 验证通过返回 echostr,否则返回错误提示。
|
||||
*/
|
||||
async verifyEventUrl(appid, signature, timestamp, nonce, echostr) {
|
||||
const { ctx, app } = this;
|
||||
|
||||
// 对应小程序须已授权登记
|
||||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||||
if (!record) {
|
||||
ctx.logger.error(`[wechatOpen.events] URL 验证失败:appid 未登记 appid=${appid}`);
|
||||
return 'appid not found';
|
||||
}
|
||||
|
||||
const config = app.config.wechatOpen || {};
|
||||
const valid = wechatOpenCrypt.verifyUrlSignature(config.token, signature, timestamp, nonce);
|
||||
ctx.logger.info(`[wechatOpen.events] URL 验证 appid=${appid} ${valid ? '通过' : '失败'}`);
|
||||
return valid ? echostr : '验证失败';
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理事件类型推送(MsgType=event,参考 PHP handleEvent)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} event 事件类型(subscribe/unsubscribe/SCAN/CLICK/VIEW/TEMPLATESENDJOBFINISH)。
|
||||
* @param {object} data 解密后的消息对象。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async handlePushEvent(appid, event, data) {
|
||||
const { ctx } = this;
|
||||
const openid = String(data.FromUserName || '');
|
||||
|
||||
switch (event) {
|
||||
case 'subscribe':
|
||||
// 关注事件:记录行为并发送欢迎消息(客服消息,非被动回复)
|
||||
await this.recordUserAction(appid, data, 'subscribe');
|
||||
await this.sendWelcomeMessage(appid, openid);
|
||||
break;
|
||||
|
||||
case 'unsubscribe':
|
||||
await this.recordUserAction(appid, data, 'unsubscribe');
|
||||
break;
|
||||
|
||||
case 'SCAN':
|
||||
case 'CLICK':
|
||||
case 'VIEW':
|
||||
case 'TEMPLATESENDJOBFINISH':
|
||||
await this.recordUserAction(appid, data, event);
|
||||
break;
|
||||
|
||||
default:
|
||||
ctx.logger.info(`[wechatOpen.events] 未处理的事件类型 appid=${appid} Event=${event}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文本消息自动回复(参考 PHP autoReply):先记录用户行为,
|
||||
* 关键词命中生成被动回复并加密;QUERY_AUTH_CODE 场景改为客服消息直发、不被动回复。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {object} data 解密后的消息对象。
|
||||
* @param {string} nonce 微信回传随机串(用于回复签名)。
|
||||
* @return {Promise<string>} 加密回复 XML;无需被动回复时返回空串。
|
||||
*/
|
||||
async autoReply(appid, data, nonce) {
|
||||
const { ctx, app } = this;
|
||||
const config = app.config.wechatOpen || {};
|
||||
|
||||
const openid = String(data.FromUserName || '');
|
||||
const appName = String(data.ToUserName || '');
|
||||
const content = String(data.Content || '');
|
||||
|
||||
// 记录用户文本消息
|
||||
await this.recordUserAction(appid, data, 'text');
|
||||
|
||||
try {
|
||||
const lowerContent = content.toLowerCase();
|
||||
let replyContent = '';
|
||||
let noReply = false;
|
||||
|
||||
// 关键词回复(与参考实现保持一致)
|
||||
if (content.includes('你好') || lowerContent.includes('hello')) {
|
||||
replyContent = '你好!有什么可以帮您的吗?';
|
||||
} else if (content.includes('帮助') || lowerContent.includes('help')) {
|
||||
replyContent = '输入以下关键词获取帮助:\n1. 功能 - 查看功能列表\n2. 关于 - 了解更多信息';
|
||||
} else if (content.includes('TESTCOMPONENT_MSG_TYPE_TEXT')) {
|
||||
replyContent = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
|
||||
} else if (content.includes('QUERY_AUTH_CODE')) {
|
||||
// 自动化测试场景:直接发送客服消息,不生成被动回复
|
||||
noReply = true;
|
||||
const newContent = content.replace('QUERY_AUTH_CODE:', '');
|
||||
await this.sendMessage(appid, openid, `${newContent}_from_api`);
|
||||
} else {
|
||||
replyContent = `收到您的消息:${content}\n我会尽快回复您!`;
|
||||
}
|
||||
|
||||
if (noReply) return '';
|
||||
|
||||
// 组装明文回复 XML(ToUserName=用户 openid,FromUserName=公众号原始 ID)
|
||||
const plainXml = '<xml>'
|
||||
+ `<ToUserName><![CDATA[${openid}]]></ToUserName>`
|
||||
+ `<FromUserName><![CDATA[${appName}]]></FromUserName>`
|
||||
+ `<CreateTime>${Math.floor(Date.now() / 1000)}</CreateTime>`
|
||||
+ '<MsgType><![CDATA[text]]></MsgType>'
|
||||
+ `<Content><![CDATA[${replyContent}]]></Content>`
|
||||
+ '</xml>';
|
||||
|
||||
const encryptResult = wechatOpenCrypt.encryptMsg({
|
||||
token: config.token,
|
||||
encodingAesKey: config.encoding_aes_key,
|
||||
componentAppid: config.component_appid,
|
||||
plainXml,
|
||||
nonce,
|
||||
});
|
||||
|
||||
if (encryptResult.code !== wechatOpenCrypt.ERROR_CODES.OK) {
|
||||
ctx.logger.error(`[wechatOpen.events] 回复消息加密失败 code=${encryptResult.code}`);
|
||||
return '';
|
||||
}
|
||||
return encryptResult.encryptedXml;
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 自动回复失败: ${e.message}`);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录用户行为到 Redis(参考 PHP recordUserAction)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {object} data 解密后的消息对象。
|
||||
* @param {string} action 行为类型(subscribe/unsubscribe/SCAN/CLICK/VIEW/text/image 等)。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async recordUserAction(appid, data, action) {
|
||||
const { ctx } = this;
|
||||
const client = new WechatOpenClient(ctx);
|
||||
const openid = String(data.FromUserName || '');
|
||||
if (!openid) return;
|
||||
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const key = `UserAction:${appid}:${openid}:${nowSec}`;
|
||||
await client.cacheSet(key, JSON.stringify({
|
||||
appid,
|
||||
openid,
|
||||
action,
|
||||
data,
|
||||
time: nowSec,
|
||||
}), 86400);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送客服文本消息(先尝试从 DB 兜底读取 refresh token,避免 Redis 丢失导致失败)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} openid 用户 openid。
|
||||
* @param {string} content 文本内容。
|
||||
* @return {Promise<object>} 微信原始响应。
|
||||
*/
|
||||
async sendMessage(appid, openid, content) {
|
||||
const { ctx, app } = this;
|
||||
const client = new WechatOpenClient(ctx);
|
||||
|
||||
// Redis 中的 refresh token 可能丢失,从 wms_wechat_app 兜底读取
|
||||
let refreshToken = null;
|
||||
try {
|
||||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||||
refreshToken = record && record.authorizer_refresh_token
|
||||
? String(record.authorizer_refresh_token)
|
||||
: null;
|
||||
} catch (e) {
|
||||
ctx.logger.warn(`[wechatOpen.events] 读取授权记录失败 appid=${appid}: ${e.message}`);
|
||||
}
|
||||
|
||||
ctx.logger.info(`[wechatOpen.events] 发送客服消息 appid=${appid} openid=${openid} content=${content}`);
|
||||
const result = await client.sendCustomMessage(appid, openid, content, refreshToken);
|
||||
ctx.logger.info(`[wechatOpen.events] 客服消息发送结果: ${JSON.stringify(result)}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送关注欢迎消息(失败仅记录日志,不阻断事件处理)。
|
||||
* @param {string} appid 授权方 AppID。
|
||||
* @param {string} openid 用户 openid。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async sendWelcomeMessage(appid, openid) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
await this.sendMessage(appid, openid, '欢迎关注!感谢您的支持!');
|
||||
} catch (e) {
|
||||
ctx.logger.error(`[wechatOpen.events] 发送欢迎消息失败: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatOpenController;
|
||||
|
||||
@ -677,6 +677,48 @@ class WechatOpenClient {
|
||||
async clearAuthState(state) {
|
||||
await this.cacheDel(`wechat_auth_state:${state}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送客服文本消息(POST cgi-bin/message/custom/send,使用 authorizer_access_token
|
||||
* 代授权方调用,用于用户关注欢迎语、关键词自动回复等场景)。
|
||||
*
|
||||
* @param {string} appid 授权方(小程序/公众号)AppID。
|
||||
* @param {string} touser 用户 openid。
|
||||
* @param {string} content 文本内容。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg)。
|
||||
*/
|
||||
async sendCustomMessage(appid, touser, content, refreshToken) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/cgi-bin/message/custom/send`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: {
|
||||
touser,
|
||||
msgtype: 'text',
|
||||
text: { content },
|
||||
},
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
// authorizer_access_token 失效(40001/40014)时清缓存重试一次
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] message/custom/send token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatOpenClient;
|
||||
|
||||
@ -98,6 +98,20 @@ function pkcs7Decode(buf) {
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* PKCS#7 填充(微信 AES 块大小为 32 字节)。
|
||||
* @param {Buffer} buf 原始 buffer。
|
||||
* @return {Buffer} 填充后的 buffer。
|
||||
*/
|
||||
function pkcs7Encode(buf) {
|
||||
const blockSize = 32;
|
||||
const pad = blockSize - (buf.length % blockSize);
|
||||
const result = Buffer.alloc(buf.length + pad);
|
||||
buf.copy(result);
|
||||
result.fill(pad, buf.length);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* AES-256-CBC 解密微信密文。
|
||||
* @param {string} encrypted base64 密文。
|
||||
@ -212,6 +226,72 @@ function parseXml(xml) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加密被动回复消息(完整流程:明文组装 → PKCS#7 → AES-256-CBC → base64 → 签名 → 组装 XML)。
|
||||
* 用于第三方平台模式下回复授权方(小程序/公众号)用户消息:
|
||||
* 16 字节随机串 + 4 字节大端消息长度 + 明文 XML + component_appid,密钥与推送解密共用组件密钥。
|
||||
* @param {object} opts 参数。
|
||||
* @param {string} opts.token 第三方平台消息校验 Token。
|
||||
* @param {string} opts.encodingAesKey 第三方平台消息加解密 Key(43 位)。
|
||||
* @param {string} opts.componentAppid 第三方平台 AppID。
|
||||
* @param {string} opts.plainXml 明文回复 XML。
|
||||
* @param {string} opts.nonce 微信回传的随机串(用于回复签名)。
|
||||
* @return {{ code: number, encryptedXml: string }} code=0 时 encryptedXml 为加密回复 XML。
|
||||
*/
|
||||
function encryptMsg(opts) {
|
||||
const {
|
||||
token,
|
||||
encodingAesKey,
|
||||
componentAppid,
|
||||
plainXml,
|
||||
nonce,
|
||||
} = opts || {};
|
||||
|
||||
if (!token || !encodingAesKey || !componentAppid || !plainXml) {
|
||||
return { code: ERROR_CODES.ILLEGAL_BUFFER, encryptedXml: '' };
|
||||
}
|
||||
|
||||
// 1. AES Key(encodingAesKey 43 位补 '=' 后 base64 解码为 32 字节)
|
||||
let aesKey;
|
||||
try {
|
||||
aesKey = Buffer.from(String(encodingAesKey) + '=', 'base64');
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, encryptedXml: '' };
|
||||
}
|
||||
if (aesKey.length !== 32) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, encryptedXml: '' };
|
||||
}
|
||||
|
||||
// 2. 组装明文:16 字节随机串 + 4 字节大端长度 + 明文 XML + component_appid
|
||||
const random = crypto.randomBytes(16);
|
||||
const plainBuf = Buffer.from(String(plainXml), 'utf8');
|
||||
const lenBuf = Buffer.alloc(4);
|
||||
lenBuf.writeUInt32BE(plainBuf.length, 0);
|
||||
const appidBuf = Buffer.from(String(componentAppid), 'utf8');
|
||||
const padded = pkcs7Encode(Buffer.concat([ random, lenBuf, plainBuf, appidBuf ]));
|
||||
|
||||
// 3. AES-256-CBC 加密(iv = key 前 16 字节,手动填充)
|
||||
let encrypt;
|
||||
try {
|
||||
const iv = aesKey.subarray(0, 16);
|
||||
const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, iv);
|
||||
cipher.setAutoPadding(false);
|
||||
encrypt = Buffer.concat([ cipher.update(padded), cipher.final() ]).toString('base64');
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.DECRYPT_AES_ERROR, encryptedXml: '' };
|
||||
}
|
||||
|
||||
// 4. 签名与组装回复 XML
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const signature = getSignature(token, timestamp, nonce, encrypt);
|
||||
const encryptedXml = `<xml><Encrypt><![CDATA[${encrypt}]]></Encrypt>`
|
||||
+ `<MsgSignature><![CDATA[${signature}]]></MsgSignature>`
|
||||
+ `<TimeStamp>${timestamp}</TimeStamp>`
|
||||
+ `<Nonce><![CDATA[${String(nonce)}]]></Nonce></xml>`;
|
||||
|
||||
return { code: ERROR_CODES.OK, encryptedXml };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ERROR_CODES,
|
||||
sha1,
|
||||
@ -220,4 +300,5 @@ module.exports = {
|
||||
extractEncrypt,
|
||||
decryptMsg,
|
||||
parseXml,
|
||||
encryptMsg,
|
||||
};
|
||||
|
||||
@ -12,6 +12,10 @@ module.exports = app => {
|
||||
router.get('/Authorization', controller.wechatOpen.authorization);
|
||||
router.post('/Authorization', controller.wechatOpen.authorization);
|
||||
|
||||
// 授权方(小程序/公众号)消息与事件推送(GET=URL验证,POST=事件推送)
|
||||
router.get('/events/appid/:appid', controller.wechatOpen.events);
|
||||
router.post('/events/appid/:appid', controller.wechatOpen.events);
|
||||
|
||||
// 内部网关接口
|
||||
router.post('/internal/v1/gateway', controller.gateway.internal);
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user