339 lines
12 KiB
JavaScript
339 lines
12 KiB
JavaScript
'use strict';
|
||
|
||
const Controller = require('egg').Controller;
|
||
const wechatOpenCrypt = require('../lib/wechat_open_crypt');
|
||
const WechatOpenClient = require('../lib/wechat_open_client');
|
||
|
||
/**
|
||
* 微信开放平台第三方平台回调 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);
|
||
|
||
// 用授权码换取授权方令牌与权限集合
|
||
const authorizationInfo = await client.queryAuth(authorizationCode);
|
||
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;
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = WechatOpenController;
|