708 lines
28 KiB
JavaScript
708 lines
28 KiB
JavaScript
'use strict';
|
||
|
||
const Controller = require('egg').Controller;
|
||
const wechatOpenCrypt = require('../lib/wechat_open_crypt');
|
||
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。
|
||
* 接收微信服务器推送的授权事件(组件票据/授权成功/授权更新/取消授权),
|
||
* 对应路由 GET|POST /Authorization。
|
||
*/
|
||
class WechatOpenController extends Controller {
|
||
/**
|
||
* 读取原始请求体(微信推送为 text/xml,bodyParser 默认不解析)。
|
||
* @return {Promise<string>} 原始请求体字符串。
|
||
*/
|
||
async readRawBody() {
|
||
const { ctx } = this;
|
||
if (ctx.request.rawBody) {
|
||
return String(ctx.request.rawBody);
|
||
}
|
||
return await new Promise((resolve, reject) => {
|
||
let data = '';
|
||
ctx.req.on('data', chunk => {
|
||
data += chunk;
|
||
});
|
||
ctx.req.on('end', () => resolve(data));
|
||
ctx.req.on('error', reject);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 授权事件接收入口(GET=URL 验证,POST=事件推送)。
|
||
* @return {Promise<void>}
|
||
*/
|
||
async authorization() {
|
||
const { ctx, app } = this;
|
||
const config = (app.config && app.config.wechatOpen) || {};
|
||
|
||
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 || '');
|
||
const state = String(ctx.query.state || '');
|
||
const authCode = String(ctx.query.auth_code || '');
|
||
|
||
// ─── URL 有效性验证(首次配置服务器地址时) ───────────────
|
||
if (echostr) {
|
||
const valid = wechatOpenCrypt.verifyUrlSignature(config.token, signature, timestamp, nonce);
|
||
ctx.logger.info(`[wechatOpen] URL 验证 ${valid ? '通过' : '失败'}`);
|
||
ctx.body = valid ? echostr : '签名验证失败';
|
||
return;
|
||
}
|
||
|
||
// ─── 授权回跳(微信授权完成后重定向 GET,带 state/auth_code;state 缺失同样走 view 提示) ───
|
||
if (ctx.method === 'GET') {
|
||
await this.handleAuthCallback(state, authCode);
|
||
return;
|
||
}
|
||
|
||
try {
|
||
const rawBody = await this.readRawBody();
|
||
if (!rawBody || !rawBody.trim()) {
|
||
ctx.logger.error('[wechatOpen] 接收到的推送体为空');
|
||
ctx.body = 'fail';
|
||
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] 消息解密失败 code=${decryptResult.code} msg=${decryptResult.msg}`);
|
||
ctx.body = 'fail';
|
||
return;
|
||
}
|
||
|
||
const msgObj = wechatOpenCrypt.parseXml(decryptResult.msg);
|
||
const infoType = String(msgObj.InfoType || '');
|
||
const event = String(msgObj.Event || '');
|
||
ctx.logger.info(`[wechatOpen] 收到推送 InfoType=${infoType} Event=${event}`);
|
||
|
||
// 小程序事件(如审核结果)用 Event 字段分发,组件事件用 InfoType 分发
|
||
await this.handleEvent(event || infoType, msgObj);
|
||
|
||
// 微信要求回显 success 表示处理成功
|
||
ctx.body = 'success';
|
||
} catch (e) {
|
||
ctx.logger.error(`[wechatOpen] 处理异常: ${e.message}`, e);
|
||
ctx.body = 'fail';
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 授权回跳处理:凭 state 取回仓库信息,用 auth_code 换取令牌并落库绑定仓库。
|
||
* @param {string} state 发起授权时缓存的随机 state。
|
||
* @param {string} authCode 微信回跳携带的授权码。
|
||
* @return {Promise<void>}
|
||
*/
|
||
async handleAuthCallback(state, authCode) {
|
||
const { ctx, app } = this;
|
||
const client = new WechatOpenClient(ctx);
|
||
const render = viewData => ctx.render('wechat_auth_callback.html', viewData);
|
||
|
||
if (!state) {
|
||
return render({ title: '微信授权结果', resultLevel: 'error', resultText: '缺少 state 参数,请从系统重新发起授权' });
|
||
}
|
||
|
||
const stateInfo = await client.getAuthState(state);
|
||
if (!stateInfo) {
|
||
return render({ title: '微信授权结果', resultLevel: 'error', resultText: '授权链接已过期或不存在,请重新发起授权' });
|
||
}
|
||
if (!authCode) {
|
||
return render({ title: '微信授权结果', resultLevel: 'error', resultText: '缺少 auth_code 参数' });
|
||
}
|
||
|
||
try {
|
||
// 用授权码换取授权方令牌(不依赖 authorized 事件时序)
|
||
const authorizationInfo = await client.queryAuth(authCode);
|
||
const authorizerAppid = authorizationInfo.authorizer_appid;
|
||
if (!authorizerAppid) throw new Error('授权信息缺少 authorizer_appid');
|
||
|
||
const nowSec = Math.floor(Date.now() / 1000);
|
||
const fields = {
|
||
warehouse_id: stateInfo.warehouse_id || null,
|
||
authorizer_refresh_token: authorizationInfo.authorizer_refresh_token || null,
|
||
auth_time: nowSec,
|
||
func_info: JSON.stringify(authorizationInfo.func_info || []),
|
||
is_enabled: 1,
|
||
};
|
||
|
||
// 拉取授权方完整信息(昵称/头像/原始ID/认证类型/主体等),失败不阻断
|
||
try {
|
||
const detail = await client.getAuthorizerDetail(authorizerAppid);
|
||
if (detail) {
|
||
Object.assign(
|
||
fields,
|
||
ctx.service.systems.wechat.buildAuthorizerPatch(
|
||
detail.authorizer_info,
|
||
detail.authorization_info || {}
|
||
)
|
||
);
|
||
}
|
||
} catch (e) {
|
||
ctx.logger.warn(`[wechatOpen] 获取授权方信息失败: ${e.message}`);
|
||
}
|
||
|
||
const existing = await app.model.WechatApp.findOne({ where: { appid: authorizerAppid } });
|
||
if (existing) {
|
||
await existing.update(fields);
|
||
} else {
|
||
await app.model.WechatApp.create({ appid: authorizerAppid, ...fields });
|
||
}
|
||
|
||
// 令牌写入 Redis 缓存(不落库)
|
||
await client.cacheSet(
|
||
`App:${authorizerAppid}:AuthorizerAccessToken`,
|
||
authorizationInfo.authorizer_access_token,
|
||
Math.max((authorizationInfo.expires_in || 7200) - 300, 60)
|
||
);
|
||
await client.cacheSet(
|
||
`App:${authorizerAppid}:authorizer_refresh_token`,
|
||
authorizationInfo.authorizer_refresh_token,
|
||
30 * 24 * 3600
|
||
);
|
||
|
||
// state 一次性消费
|
||
await client.clearAuthState(state);
|
||
|
||
ctx.logger.info(`[wechatOpen] 授权回调成功 appid=${authorizerAppid} warehouse_id=${fields.warehouse_id}`);
|
||
return render({
|
||
title: '微信授权结果',
|
||
resultLevel: 'success',
|
||
resultText: '授权成功,小程序已绑定仓库',
|
||
appid: authorizerAppid,
|
||
nickname: fields.nickname || '',
|
||
warehouseId: fields.warehouse_id || null,
|
||
});
|
||
} catch (e) {
|
||
ctx.logger.error(`[wechatOpen] 授权回调处理失败: ${e.message}`, e);
|
||
return render({
|
||
title: '微信授权结果',
|
||
resultLevel: 'error',
|
||
resultText: `授权处理失败:${e.message}`,
|
||
appid: '',
|
||
nickname: '',
|
||
warehouseId: null,
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按 InfoType 分发处理授权事件。
|
||
* @param {string} infoType 事件类型。
|
||
* @param {object} msgObj 解密后的消息对象。
|
||
* @return {Promise<void>}
|
||
*/
|
||
async handleEvent(infoType, msgObj) {
|
||
const { ctx, app } = this;
|
||
const client = new WechatOpenClient(ctx);
|
||
|
||
switch (infoType) {
|
||
case 'component_verify_ticket': {
|
||
// 组件票据:每 10 分钟推送一次,缓存后用于换取 component_access_token
|
||
const ticket = String(msgObj.ComponentVerifyTicket || '');
|
||
if (!ticket) {
|
||
ctx.logger.error('[wechatOpen] component_verify_ticket 事件缺少 ComponentVerifyTicket');
|
||
return;
|
||
}
|
||
await client.saveComponentVerifyTicket(ticket);
|
||
ctx.logger.info(`[wechatOpen] 已保存 ComponentVerifyTicket(AppId: ${msgObj.AppId})`);
|
||
break;
|
||
}
|
||
|
||
case 'authorized':
|
||
case 'updateauthorized': {
|
||
const authorizerAppid = String(msgObj.AuthorizerAppid || '');
|
||
const authorizationCode = String(msgObj.AuthorizationCode || '');
|
||
if (!authorizerAppid || !authorizationCode) {
|
||
ctx.logger.error(`[wechatOpen] ${infoType} 事件缺少 AuthorizerAppid/AuthorizationCode`);
|
||
return;
|
||
}
|
||
|
||
// 暂存授权码(供后续换取令牌使用)
|
||
await client.saveAuthorizationCode(authorizerAppid, authorizationCode);
|
||
|
||
// 用授权码换取授权方令牌与权限集合。
|
||
// 注意:同一 authorization_code 只能 queryAuth 成功一次。微信全网发布检测时,
|
||
// authorized 事件与 QUERY_AUTH_CODE 文本消息几乎同时推送(实测仅差 1 秒),
|
||
// 文本分支也会用同一 code 调 queryAuth——谁先到谁消费。此处失败不抛错重试,
|
||
// 令牌可由文本分支/授权回跳链路换得,保证「授权成功」检测项始终响应 success。
|
||
let authorizationInfo = null;
|
||
try {
|
||
authorizationInfo = await client.queryAuth(authorizationCode);
|
||
} catch (e) {
|
||
ctx.logger.warn(`[wechatOpen] ${infoType} 换取授权方令牌失败(可能已被 QUERY_AUTH_CODE 文本消费): ${e.message}`);
|
||
return;
|
||
}
|
||
const nowSec = Math.floor(Date.now() / 1000);
|
||
const fields = {
|
||
authorizer_refresh_token: authorizationInfo.authorizer_refresh_token || null,
|
||
auth_time: nowSec,
|
||
func_info: JSON.stringify(authorizationInfo.func_info || []),
|
||
is_enabled: 1,
|
||
};
|
||
|
||
// authorizer_access_token 存入 Redis 缓存(自动过期),不落库
|
||
await client.cacheSet(
|
||
`App:${authorizerAppid}:AuthorizerAccessToken`,
|
||
authorizationInfo.authorizer_access_token,
|
||
Math.max((authorizationInfo.expires_in || 7200) - 300, 60)
|
||
);
|
||
await client.cacheSet(
|
||
`App:${authorizerAppid}:authorizer_refresh_token`,
|
||
authorizationInfo.authorizer_refresh_token,
|
||
30 * 24 * 3600
|
||
);
|
||
|
||
// 拉取授权方完整信息(昵称/头像/原始ID/认证类型/主体等),失败不阻断
|
||
try {
|
||
const detail = await client.getAuthorizerDetail(authorizerAppid);
|
||
if (detail) {
|
||
Object.assign(
|
||
fields,
|
||
ctx.service.systems.wechat.buildAuthorizerPatch(
|
||
detail.authorizer_info,
|
||
detail.authorization_info || {}
|
||
)
|
||
);
|
||
}
|
||
} catch (e) {
|
||
ctx.logger.warn(`[wechatOpen] 获取授权方信息失败: ${e.message}`);
|
||
}
|
||
|
||
const existing = await app.model.WechatApp.findOne({ where: { appid: authorizerAppid } });
|
||
if (existing) {
|
||
await existing.update(fields);
|
||
ctx.logger.info(`[wechatOpen] 已更新授权记录 appid=${authorizerAppid}`);
|
||
} else {
|
||
await app.model.WechatApp.create({ appid: authorizerAppid, ...fields });
|
||
ctx.logger.info(`[wechatOpen] 已新增授权记录 appid=${authorizerAppid}`);
|
||
}
|
||
break;
|
||
}
|
||
|
||
case 'unauthorized': {
|
||
const authorizerAppid = String(msgObj.AuthorizerAppid || '');
|
||
if (!authorizerAppid) {
|
||
ctx.logger.error('[wechatOpen] unauthorized 事件缺少 AuthorizerAppid');
|
||
return;
|
||
}
|
||
// 清理令牌缓存
|
||
await client.clearAuthorizerCache(authorizerAppid);
|
||
// 停用授权记录(保留记录供追溯)
|
||
await app.model.WechatApp.update(
|
||
{ is_enabled: 0 },
|
||
{ where: { appid: authorizerAppid } }
|
||
);
|
||
ctx.logger.info(`[wechatOpen] 已停用授权记录 appid=${authorizerAppid}`);
|
||
break;
|
||
}
|
||
|
||
case 'weapp_audit_success': {
|
||
// 代码审核通过:按小程序原始ID(ToUserName=gh_xxx)定位记录,状态置 2
|
||
const originalId = String(msgObj.ToUserName || '').trim();
|
||
if (!originalId) {
|
||
ctx.logger.error('[wechatOpen] weapp_audit_success 缺少 ToUserName');
|
||
return;
|
||
}
|
||
await app.model.WechatApp.update(
|
||
{ audit_status: 2, audit_reason: '' },
|
||
{ where: { user_name: originalId } }
|
||
);
|
||
ctx.logger.info(`[wechatOpen] 审核通过 originalId=${originalId}`);
|
||
break;
|
||
}
|
||
|
||
case 'weapp_audit_fail': {
|
||
// 代码审核驳回:状态置 3 并记录驳回原因
|
||
const originalId = String(msgObj.ToUserName || '').trim();
|
||
if (!originalId) {
|
||
ctx.logger.error('[wechatOpen] weapp_audit_fail 缺少 ToUserName');
|
||
return;
|
||
}
|
||
await app.model.WechatApp.update(
|
||
{ audit_status: 3, audit_reason: String(msgObj.Reason || '') },
|
||
{ where: { user_name: originalId } }
|
||
);
|
||
ctx.logger.info(`[wechatOpen] 审核驳回 originalId=${originalId} reason=${msgObj.Reason || ''}`);
|
||
break;
|
||
}
|
||
|
||
default:
|
||
ctx.logger.info(`[wechatOpen] 未处理的 InfoType: ${infoType}`);
|
||
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 || '');
|
||
|
||
// 文本消息全量落盘(WARN 级):生产日志只落 WARN+,用于检测场景定位回复问题
|
||
if (msgType === 'text') {
|
||
ctx.logger.warn(`[wechatOpen.events] 收到文本消息 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} content=${JSON.stringify(String(data.Content || ''))}`);
|
||
}
|
||
|
||
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.warn(`[wechatOpen.events] 被动回复已返回 appid=${appid} type=${detectAccountType(appid)} openid=${data.FromUserName} length=${reply.length}`);
|
||
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)。
|
||
* 签名使用第三方平台(组件)Token 校验(与 /Authorization 的 URL 验证一致)。
|
||
* appid 记录不存在时不阻断验证:首次配置服务器地址、微信全网发布检测等场景下,
|
||
* 微信会先发 echostr 验证 URL,此时可能尚无授权记录,仍按组件 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;
|
||
|
||
// 对应小程序应已授权登记;未登记仅告警,不阻断 URL 验证
|
||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||
if (!record) {
|
||
ctx.logger.warn(`[wechatOpen.events] URL 验证:appid 尚无授权记录(首次配置或检测场景),仍按组件 Token 验签 appid=${appid}`);
|
||
}
|
||
|
||
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';
|
||
ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤2-公众号被动回复 appid=${appid} type=${detectAccountType(appid)}`);
|
||
} else if (content.includes('QUERY_AUTH_CODE')) {
|
||
// 微信全网发布检测场景(官方步骤3=公众号客服/步骤4=小程序客服):文本携带授权码
|
||
// (QUERY_AUTH_CODE:<code>)。检测的 authorized 事件与文本消息几乎同时到达(实测仅差
|
||
// 1 秒),不能依赖 authorized 已换取令牌,必须用文本中的授权码调 api_query_auth。
|
||
// 官方要求「5 秒内返回空串」:客服消息流程放入后台异步执行,主流程立即返回。
|
||
noReply = true;
|
||
const authCode = content.replace('QUERY_AUTH_CODE:', '').trim();
|
||
const accountType = detectAccountType(appid);
|
||
ctx.logger.warn(`[wechatOpen.events] 命中官方检测步骤3/4-客服消息回复 appid=${appid} type=${accountType} code=${authCode}`);
|
||
|
||
ctx.runInBackground(async () => {
|
||
const client = new WechatOpenClient(ctx);
|
||
let refreshToken = null;
|
||
if (authCode) {
|
||
try {
|
||
const authorizationInfo = await client.queryAuth(authCode);
|
||
refreshToken = authorizationInfo.authorizer_refresh_token || null;
|
||
ctx.logger.warn(`[wechatOpen.events] QUERY_AUTH_CODE 换取令牌成功 appid=${appid} code=${authCode} has_refresh=${!!refreshToken}`);
|
||
if (refreshToken) {
|
||
await client.cacheSet(`App:${appid}:authorizer_refresh_token`, refreshToken, 30 * 24 * 3600);
|
||
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}`);
|
||
}
|
||
}
|
||
try {
|
||
await this.sendMessage(appid, openid, `${authCode}_from_api`, refreshToken);
|
||
} catch (e) {
|
||
ctx.logger.error(`[wechatOpen.events] 客服消息发送异常: ${e.message}`);
|
||
}
|
||
});
|
||
} 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);
|
||
}
|
||
|
||
/**
|
||
* 发送客服文本消息(refreshToken 优先,其次从 DB 兜底读取,避免 Redis 丢失导致失败)。
|
||
* @param {string} appid 授权方 AppID。
|
||
* @param {string} openid 用户 openid。
|
||
* @param {string} content 文本内容。
|
||
* @param {string} [refreshToken] 授权方刷新令牌(调用方已获取时传入)。
|
||
* @return {Promise<object>} 微信原始响应。
|
||
*/
|
||
async sendMessage(appid, openid, content, refreshToken) {
|
||
const { ctx, app } = this;
|
||
const client = new WechatOpenClient(ctx);
|
||
|
||
// Redis 中的 refresh token 可能丢失,从 wms_wechat_app 兜底读取
|
||
let token = refreshToken || null;
|
||
try {
|
||
const record = await app.model.WechatApp.findOne({ where: { appid } });
|
||
if (record && record.authorizer_refresh_token) {
|
||
token = String(record.authorizer_refresh_token);
|
||
}
|
||
} catch (e) {
|
||
ctx.logger.warn(`[wechatOpen.events] 读取授权记录失败 appid=${appid}: ${e.message}`);
|
||
}
|
||
|
||
ctx.logger.warn(`[wechatOpen.events] 发送客服消息 appid=${appid} openid=${openid} content=${JSON.stringify(content)} has_token=${!!token}`);
|
||
const result = await client.sendCustomMessage(appid, openid, content, token);
|
||
ctx.logger.warn(`[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;
|