fix(wechat): 客服消息改 runInBackground 异步确保 5 秒响应,日志按官方检测步骤2/3/4与公众号/小程序测试号打标

This commit is contained in:
liufumingren 2026-10-12 19:14:23 +08:00
parent c3896bc68a
commit 4ae9ae852f

View File

@ -4,6 +4,32 @@ const Controller = require('egg').Controller;
const wechatOpenCrypt = require('../lib/wechat_open_crypt'); const wechatOpenCrypt = require('../lib/wechat_open_crypt');
const WechatOpenClient = require('../lib/wechat_open_client'); const WechatOpenClient = require('../lib/wechat_open_client');
/**
* 微信全网发布检测专用测试号(官方文档 5 组随机分配),用于日志标注公众号/小程序场景。
* 步骤2=公众号被动回复;步骤3=公众号客服消息;步骤4=小程序客服消息。
*/
const WECHAT_TEST_ACCOUNTS = {
mp: new Set([
'wx570bc396a51b8ff8', 'wx9252c5e0bb1836fc', 'wx8e1097c5bc82cde9',
'wx14550af28c71a144', 'wxa35b9c23cfe664eb',
]),
mini: new Set([
'wxd101a85aa106f53e', 'wxc39235c15087f6f3', 'wx7720d01d4b2a4500',
'wx05d483572dcd5d8b', 'wx5910277cae6fd970',
]),
};
/**
* 判断 appid 属于公众号/小程序测试号(用于日志标注,未知账号不影响处理)。
* @param {string} appid 授权方 AppID。
* @return {string} '公众号' | '小程序' | '未知账号'。
*/
function detectAccountType(appid) {
if (WECHAT_TEST_ACCOUNTS.mp.has(appid)) return '公众号';
if (WECHAT_TEST_ACCOUNTS.mini.has(appid)) return '小程序';
return '未知账号';
}
/** /**
* 微信开放平台第三方平台回调 Controller。 * 微信开放平台第三方平台回调 Controller。
* 接收微信服务器推送的授权事件(组件票据/授权成功/授权更新/取消授权), * 接收微信服务器推送的授权事件(组件票据/授权成功/授权更新/取消授权),
@ -404,9 +430,9 @@ class WechatOpenController extends Controller {
const msgType = String(data.MsgType || ''); const msgType = String(data.MsgType || '');
const event = String(data.Event || ''); const event = String(data.Event || '');
// 文本消息全量落盘(WARN 级):生产日志只落 WARN+,用于检测场景定位客服回复问题 // 文本消息全量落盘(WARN 级):生产日志只落 WARN+,用于检测场景定位回复问题
if (msgType === 'text') { if (msgType === 'text') {
ctx.logger.warn(`[wechatOpen.events] 收到文本消息 appid=${appid} openid=${data.FromUserName} content=${JSON.stringify(String(data.Content || ''))}`); ctx.logger.warn(`[wechatOpen.events] 收到文本消息 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} content=${JSON.stringify(String(data.Content || ''))}`);
} }
switch (msgType) { switch (msgType) {
@ -418,7 +444,7 @@ class WechatOpenController extends Controller {
// 记录文本消息并自动回复(有被动回复时返回加密 XML) // 记录文本消息并自动回复(有被动回复时返回加密 XML)
const reply = await this.autoReply(appid, data, nonce); const reply = await this.autoReply(appid, data, nonce);
if (reply) { if (reply) {
ctx.logger.info(`[wechatOpen.events] 被动回复用户消息 appid=${appid} openid=${data.FromUserName}`); ctx.logger.warn(`[wechatOpen.events] 被动回复已返回 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} length=${reply.length}`);
ctx.type = 'application/xml'; ctx.type = 'application/xml';
ctx.body = reply; ctx.body = reply;
return; return;
@ -536,35 +562,45 @@ class WechatOpenController extends Controller {
replyContent = '输入以下关键词获取帮助:\n1. 功能 - 查看功能列表\n2. 关于 - 了解更多信息'; replyContent = '输入以下关键词获取帮助:\n1. 功能 - 查看功能列表\n2. 关于 - 了解更多信息';
} else if (content.includes('TESTCOMPONENT_MSG_TYPE_TEXT')) { } else if (content.includes('TESTCOMPONENT_MSG_TYPE_TEXT')) {
replyContent = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback'; replyContent = 'TESTCOMPONENT_MSG_TYPE_TEXT_callback';
ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤2-公众号被动回复 appid=${appid} type=${detectAccountType(appid)}`);
} else if (content.includes('QUERY_AUTH_CODE')) { } else if (content.includes('QUERY_AUTH_CODE')) {
// 微信全网发布检测场景:文本携带授权码(QUERY_AUTH_CODE:<code>)。 // 微信全网发布检测场景(官方步骤3=公众号客服/步骤4=小程序客服):文本携带授权码
// 检测的 authorized 事件与文本消息几乎同时到达(实测仅差 1 秒), // (QUERY_AUTH_CODE:<code>)。检测的 authorized 事件与文本消息几乎同时到达(实测仅差
// 不能依赖 authorized 事件已换取令牌并落库,必须用文本中的授权码 // 1 秒),不能依赖 authorized 已换取令牌,必须用文本中的授权码调 api_query_auth。
// 直接调 api_query_auth 换令牌(官方检测意图),再回复客服消息。 // 官方要求「5 秒内返回空串」:客服消息流程放入后台异步执行,主流程立即返回。
noReply = true; noReply = true;
const authCode = content.replace('QUERY_AUTH_CODE:', '').trim(); const authCode = content.replace('QUERY_AUTH_CODE:', '').trim();
const client = new WechatOpenClient(ctx); const accountType = detectAccountType(appid);
let refreshToken = null; ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤3/4-客服消息回复 appid=${appid} type=${accountType} code=${authCode}`);
if (authCode) {
try { ctx.runInBackground(async () => {
const authorizationInfo = await client.queryAuth(authCode); const client = new WechatOpenClient(ctx);
refreshToken = authorizationInfo.authorizer_refresh_token || null; let refreshToken = null;
ctx.logger.warn(`[wechatOpen.events] QUERY_AUTH_CODE 换取令牌成功 appid=${appid} code=${authCode} has_refresh=${!!refreshToken}`); if (authCode) {
if (refreshToken) { try {
await client.cacheSet(`App:${appid}:authorizer_refresh_token`, refreshToken, 30 * 24 * 3600); const authorizationInfo = await client.queryAuth(authCode);
if (authorizationInfo.authorizer_access_token) { refreshToken = authorizationInfo.authorizer_refresh_token || null;
await client.cacheSet( ctx.logger.warn(`[wechatOpen.events] QUERY_AUTH_CODE 换取令牌成功 appid=${appid} code=${authCode} has_refresh=${!!refreshToken}`);
`App:${appid}:AuthorizerAccessToken`, if (refreshToken) {
authorizationInfo.authorizer_access_token, await client.cacheSet(`App:${appid}:authorizer_refresh_token`, refreshToken, 30 * 24 * 3600);
Math.max((authorizationInfo.expires_in || 7200) - 300, 60) if (authorizationInfo.authorizer_access_token) {
); await client.cacheSet(
`App:${appid}:AuthorizerAccessToken`,
authorizationInfo.authorizer_access_token,
Math.max((authorizationInfo.expires_in || 7200) - 300, 60)
);
}
} }
} catch (e) {
ctx.logger.warn(`[wechatOpen.events] QUERY_AUTH_CODE 换取令牌失败: ${e.message}`);
} }
} catch (e) {
ctx.logger.warn(`[wechatOpen.events] QUERY_AUTH_CODE 换取令牌失败: ${e.message}`);
} }
} try {
await this.sendMessage(appid, openid, `${authCode}_from_api`, refreshToken); await this.sendMessage(appid, openid, `${authCode}_from_api`, refreshToken);
} catch (e) {
ctx.logger.error(`[wechatOpen.events] 客服消息发送异常: ${e.message}`);
}
});
} else { } else {
replyContent = `收到您的消息:${content}\n我会尽快回复您!`; replyContent = `收到您的消息:${content}\n我会尽快回复您!`;
} }