feat(wechat): 微信开放平台第三方平台接入:授权事件回调、加解密、OpenAPI 客户端、oauth 登录态中间层与工牌扫码
This commit is contained in:
parent
b6baece8ad
commit
258232f98d
338
app/controller/wechatOpen.js
Normal file
338
app/controller/wechatOpen.js
Normal file
@ -0,0 +1,338 @@
|
||||
'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;
|
||||
677
app/lib/wechat_open_client.js
Normal file
677
app/lib/wechat_open_client.js
Normal file
@ -0,0 +1,677 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 微信开放平台第三方平台 API 客户端。
|
||||
* 封装组件级接口调用与 token 管理(Redis 缓存,Key 与参考实现一致):
|
||||
* - component_access_token:调用授权方接口的组件凭证(约 2 小时)。
|
||||
* - App:{appid}:authorization_code:授权码(authorized 事件推送后暂存)。
|
||||
* - App:{appid}:authorizer_refresh_token:授权方刷新令牌(长期)。
|
||||
* - App:{appid}:AuthorizerAccessToken:授权方接口调用凭证(约 2 小时)。
|
||||
*
|
||||
* 配置读取 app.config.wechatOpen:
|
||||
* - component_appid / component_secret / token / encoding_aes_key / api_base
|
||||
*/
|
||||
|
||||
const DEFAULT_API_BASE = 'https://api.weixin.qq.com';
|
||||
|
||||
/** 缓存预留提前量(秒):token 在过期前提前失效,避免临界调用失败。 */
|
||||
const EXPIRE_MARGIN = 300;
|
||||
|
||||
class WechatOpenClient {
|
||||
/**
|
||||
* @param {object} ctx Egg 上下文。
|
||||
*/
|
||||
constructor(ctx) {
|
||||
this.ctx = ctx;
|
||||
this.app = ctx.app;
|
||||
this.config = (this.app && this.app.config && this.app.config.wechatOpen) || {};
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 Redis 客户端(cache 库),不可用时返回 null。
|
||||
* @return {object|null} ioredis 客户端。
|
||||
*/
|
||||
redis() {
|
||||
return this.app && this.app.redis && typeof this.app.redis.get === 'function'
|
||||
? this.app.redis.get('cache')
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取缓存。
|
||||
* @param {string} key Redis key。
|
||||
* @return {Promise<string|null>} 缓存值。
|
||||
*/
|
||||
async cacheGet(key) {
|
||||
const redis = this.redis();
|
||||
if (!redis) return null;
|
||||
return redis.get(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入缓存。
|
||||
* @param {string} key Redis key。
|
||||
* @param {string} value 值。
|
||||
* @param {number} ttl 过期秒数。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async cacheSet(key, value, ttl) {
|
||||
const redis = this.redis();
|
||||
if (!redis) return;
|
||||
await redis.set(key, value, 'EX', ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除缓存。
|
||||
* @param {...string} keys Redis keys。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async cacheDel(...keys) {
|
||||
const redis = this.redis();
|
||||
if (!redis || keys.length === 0) return;
|
||||
await redis.del(...keys);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起微信 API POST 请求(JSON)。
|
||||
* @param {string} path API 路径(不含 base)。
|
||||
* @param {object} body 请求体。
|
||||
* @param {string} [token] component_access_token(作为 URL query 拼接)。
|
||||
* @return {Promise<object>} 响应 JSON。
|
||||
*/
|
||||
async apiPost(path, body, token) {
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
let url = base.replace(/\/$/, '') + path;
|
||||
if (token) {
|
||||
url += `${url.includes('?') ? '&' : '?'}component_access_token=${encodeURIComponent(token)}`;
|
||||
}
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携带 component_access_token 发起 POST 请求;遇 40001(invalid credential,token 被别处刷新顶掉)
|
||||
* 时自动清除缓存 token、重取后重试一次。
|
||||
*
|
||||
* @param {string} path API 路径(不含 base)。
|
||||
* @param {object} body 请求体。
|
||||
* @return {Promise<object>} 响应 JSON(必要时重试后)。
|
||||
*/
|
||||
async apiPostWithComponentToken(path, body) {
|
||||
let result = await this.apiPost(path, body, await this.getComponentAccessToken());
|
||||
if (result && Number(result.errcode) === 40001) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] component_access_token 失效(40001),清除缓存重试: ${path}`);
|
||||
}
|
||||
await this.cacheDel('component_access_token');
|
||||
result = await this.apiPost(path, body, await this.getComponentAccessToken());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存 ComponentVerifyTicket(component_verify_ticket 事件推送后调用)。
|
||||
* @param {string} ticket 推送的 Ticket。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async saveComponentVerifyTicket(ticket) {
|
||||
// 微信每 10 分钟推送一次,ticket 有效期 12 小时。
|
||||
// 缓存 12 小时:异常未及时收到推送时,继续用上一次可用 ticket 换取 component_access_token(官方建议)。
|
||||
await this.cacheSet('ComponentVerifyTicket', ticket, 12 * 3600);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取组件接口调用凭证 component_access_token(缓存优先)。
|
||||
* @return {Promise<string>} component_access_token。
|
||||
*/
|
||||
async getComponentAccessToken() {
|
||||
const cached = await this.cacheGet('component_access_token');
|
||||
if (cached) return cached;
|
||||
|
||||
const ticket = await this.cacheGet('ComponentVerifyTicket');
|
||||
if (!ticket) {
|
||||
throw new Error('ComponentVerifyTicket 不存在,请等待微信推送后重试');
|
||||
}
|
||||
|
||||
const result = await this.apiPost('/cgi-bin/component/api_component_token', {
|
||||
component_appid: this.config.component_appid,
|
||||
component_appsecret: this.config.component_secret,
|
||||
component_verify_ticket: ticket,
|
||||
});
|
||||
|
||||
if (result && result.component_access_token) {
|
||||
const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN;
|
||||
await this.cacheSet('component_access_token', result.component_access_token, Math.max(ttl, 60));
|
||||
return result.component_access_token;
|
||||
}
|
||||
throw new Error(`获取 component_access_token 失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存授权码(authorized/updateauthorized 事件推送后调用)。
|
||||
* @param {string} authorizerAppid 授权方小程序 AppID。
|
||||
* @param {string} authorizationCode 授权码。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async saveAuthorizationCode(authorizerAppid, authorizationCode) {
|
||||
// 授权码有效期 1 小时
|
||||
await this.cacheSet(`App:${authorizerAppid}:authorization_code`, authorizationCode, 3600);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用授权码换取授权方令牌(api_query_auth)。
|
||||
* @param {string} authorizationCode 授权码。
|
||||
* @return {Promise<object>} authorization_info(含 authorizer_refresh_token/
|
||||
* authorizer_access_token/expires_in/func_info 等)。
|
||||
*/
|
||||
async queryAuth(authorizationCode) {
|
||||
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_query_auth', {
|
||||
component_appid: this.config.component_appid,
|
||||
authorization_code: authorizationCode,
|
||||
});
|
||||
if (result && result.authorization_info) {
|
||||
return result.authorization_info;
|
||||
}
|
||||
throw new Error(`获取 authorizer_refresh_token 失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取/刷新授权方接口调用凭证 authorizer_access_token(缓存优先)。
|
||||
* @param {string} appid 授权方小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取)。
|
||||
* @return {Promise<object>} { authorizerAccessToken, authorizerRefreshToken }。
|
||||
*/
|
||||
async getAuthorizerAccessToken(appid, refreshToken) {
|
||||
const tokenKey = `App:${appid}:AuthorizerAccessToken`;
|
||||
const cached = await this.cacheGet(tokenKey);
|
||||
if (cached) {
|
||||
return { authorizerAccessToken: cached, authorizerRefreshToken: refreshToken || null };
|
||||
}
|
||||
|
||||
let token = refreshToken || (await this.cacheGet(`App:${appid}:authorizer_refresh_token`));
|
||||
if (!token) {
|
||||
throw new Error(`App:${appid} 的 authorizer_refresh_token 不存在`);
|
||||
}
|
||||
|
||||
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_authorizer_token', {
|
||||
component_appid: this.config.component_appid,
|
||||
authorizer_appid: appid,
|
||||
authorizer_refresh_token: token,
|
||||
});
|
||||
|
||||
if (result && result.authorizer_access_token) {
|
||||
const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN;
|
||||
await this.cacheSet(tokenKey, result.authorizer_access_token, Math.max(ttl, 60));
|
||||
if (result.authorizer_refresh_token) {
|
||||
token = result.authorizer_refresh_token;
|
||||
await this.cacheSet(`App:${appid}:authorizer_refresh_token`, token, 30 * 24 * 3600);
|
||||
}
|
||||
return { authorizerAccessToken: result.authorizer_access_token, authorizerRefreshToken: token };
|
||||
}
|
||||
throw new Error(`获取 authorizer_access_token 失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取授权方基本信息(api_get_authorizer_info:昵称/头像/原始ID)。
|
||||
* @param {string} appid 授权方小程序 AppID。
|
||||
* @return {Promise<object>} authorizer_info。
|
||||
*/
|
||||
async getAuthorizerInfo(appid) {
|
||||
const detail = await this.getAuthorizerDetail(appid);
|
||||
if (detail && detail.authorizer_info) {
|
||||
return detail.authorizer_info;
|
||||
}
|
||||
throw new Error(`获取授权方信息失败: ${JSON.stringify(detail)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取授权账号详情(api_get_authorizer_info 完整返回:authorizer_info + authorization_info)。
|
||||
* @param {string} appid 授权方小程序 AppID。
|
||||
* @return {Promise<object>} { authorizer_info, authorization_info }。
|
||||
*/
|
||||
async getAuthorizerDetail(appid) {
|
||||
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_get_authorizer_info', {
|
||||
component_appid: this.config.component_appid,
|
||||
authorizer_appid: appid,
|
||||
});
|
||||
if (result && (result.authorizer_info || result.authorization_info)) {
|
||||
return result;
|
||||
}
|
||||
throw new Error(`获取授权账号详情失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建预授权码(用于生成授权链接)。
|
||||
* @return {Promise<string>} pre_auth_code。
|
||||
*/
|
||||
async createPreAuthCode() {
|
||||
const cached = await this.cacheGet('preauthcode');
|
||||
if (cached) return cached;
|
||||
|
||||
const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_create_preauthcode', {
|
||||
component_appid: this.config.component_appid,
|
||||
});
|
||||
if (result && result.pre_auth_code) {
|
||||
await this.cacheSet('preauthcode', result.pre_auth_code, result.expires_in || 1800);
|
||||
return result.pre_auth_code;
|
||||
}
|
||||
throw new Error(`创建预授权码失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询小程序认证进度(POST wxa/sec/queryauth,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取,Redis 丢失可用 DB 值兜底)。
|
||||
* @param {string} taskid 认证任务 id(发起认证接口返回)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/task_status/apply_status/orderid/auth_url 等)。
|
||||
*/
|
||||
async queryMiniProgramAuth(appid, refreshToken, taskid) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/sec/queryauth`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: { taskid },
|
||||
});
|
||||
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] wxa/sec/queryauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起小程序认证(wxa/sec/wxaapi/wxaauth,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* 材料图片由前端上传换取 media_id 后一步提交;请求体字段白名单由业务层透传。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {object} body 认证请求体(contact_type/contact_name/各 media_id 材料等)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/taskid/auth_url/apply_status)。
|
||||
*/
|
||||
async wxaauth(appid, refreshToken, body) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/sec/wxaapi/wxaauth`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 60000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
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] wxa/sec/wxaapi/wxaauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传认证材料图片到微信换取 media_id(wxa/sec/wxaapi/uploadmedia,
|
||||
* authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* 采用 multipart/form-data:media=图片文件(写入临时文件后按路径上传,保证文件名带扩展名)、
|
||||
* media_type=image;成功后返回 media_id(3 天内有效,供 wxaauth 提交)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {Buffer} buffer 图片内容。
|
||||
* @param {string} filename 文件名(含扩展名,如 idcard.jpg)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/media_id/media_md5)。
|
||||
*/
|
||||
async uploadAuthMedia(appid, refreshToken, buffer, filename) {
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
|
||||
const tmpFile = path.join(
|
||||
os.tmpdir(),
|
||||
`wxauth-${Date.now()}-${Math.random().toString(36).slice(2, 10)}-${path.basename(filename || 'image.jpg')}`
|
||||
);
|
||||
await fs.promises.writeFile(tmpFile, buffer);
|
||||
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/sec/wxaapi/uploadmedia`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 60000,
|
||||
data: { media_type: 'image' },
|
||||
files: { media: tmpFile },
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
try {
|
||||
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] wxa/sec/wxaapi/uploadmedia token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
await fs.promises.unlink(tmpFile).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取小程序模板列表(wxa/gettemplatelist,仅支持 component_access_token,GET 请求)。
|
||||
*
|
||||
* @param {number} [templateType] 0=普通模板、1=标准模板,不传返回全部。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/template_list)。
|
||||
*/
|
||||
async getTemplateList(templateType) {
|
||||
const request = async () => {
|
||||
const componentAccessToken = await this.getComponentAccessToken();
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/gettemplatelist`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'GET',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
data: {
|
||||
access_token: componentAccessToken,
|
||||
...(templateType !== undefined && templateType !== null ? { template_type: templateType } : {}),
|
||||
},
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
if (result && Number(result.errcode) === 40001) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn('[wechatOpen] gettemplatelist 40001 component_access_token 失效,清除缓存重试');
|
||||
}
|
||||
await this.cacheDel('component_access_token');
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交代码审核(wxa/submit_audit,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {object} body 请求体(item_list/version_desc 等,均为可选)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/auditid)。
|
||||
*/
|
||||
async submitAudit(appid, refreshToken, body) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/submit_audit`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 60000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
if (result && [ 40001, 40014 ].includes(Number(result.errcode))) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn(`[wechatOpen] wxa/submit_audit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取体验版二维码(wxa/get_qrcode,使用 authorizer_access_token 代商家调用,权限集 18/86)。
|
||||
*
|
||||
* 成功返回图片二进制(contentType=image/jpeg),失败返回微信 JSON(errcode/errmsg)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {string} [path] 二维码扫码进入的页面路径(可选,自动 urlencode)。
|
||||
* @return {Promise<object>} { errcode, errmsg } 或 { errcode: 0, contentType, buffer }。
|
||||
*/
|
||||
async getTrialQRCode(appid, refreshToken, path) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
let url = `${base.replace(/\/$/, '')}/wxa/get_qrcode`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
if (path) {
|
||||
url += `&path=${encodeURIComponent(path)}`;
|
||||
}
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'GET',
|
||||
timeout: 30000,
|
||||
});
|
||||
const contentType = String((response.headers && response.headers['content-type']) || '');
|
||||
if (contentType.includes('image')) {
|
||||
return { errcode: 0, errmsg: 'ok', contentType, buffer: response.data };
|
||||
}
|
||||
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] wxa/get_qrcode token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传代码并生成体验版(wxa/commit,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {object} body { template_id, ext_json, user_version, user_desc }。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg)。
|
||||
*/
|
||||
async commitTemplate(appid, refreshToken, body) {
|
||||
const request = async () => {
|
||||
const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken);
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/commit`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 60000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
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] wxa/commit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速注册企业小程序(fastregisterweapp,仅支持第三方平台 component_access_token)。
|
||||
*
|
||||
* @param {string} action create=创建小程序 / search=查询创建任务状态。
|
||||
* @param {object} body 请求体。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg)。
|
||||
*/
|
||||
async fastRegisterWeapp(action, body) {
|
||||
const request = async () => {
|
||||
const componentAccessToken = await this.getComponentAccessToken();
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/cgi-bin/component/fastregisterweapp`
|
||||
+ `?action=${encodeURIComponent(action)}`
|
||||
+ `&component_access_token=${encodeURIComponent(componentAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
data: body,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
if (result && Number(result.errcode) === 40001) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn('[wechatOpen] fastregisterweapp 40001 component_access_token 失效,清除缓存重试');
|
||||
}
|
||||
await this.cacheDel('component_access_token');
|
||||
result = await request();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 小程序登录凭证校验(jscode2session):第三方平台代小程序实现登录。
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} jsCode wx.login 获取的 code。
|
||||
* @return {Promise<object>} { openid, session_key, unionid }。
|
||||
*/
|
||||
async jscode2session(appid, jsCode) {
|
||||
const request = async () => {
|
||||
const componentAccessToken = await this.getComponentAccessToken();
|
||||
const base = this.config.api_base || DEFAULT_API_BASE;
|
||||
const url = `${base.replace(/\/$/, '')}/sns/component/jscode2session`
|
||||
+ `?appid=${encodeURIComponent(appid)}`
|
||||
+ '&grant_type=authorization_code'
|
||||
+ `&component_appid=${encodeURIComponent(this.config.component_appid)}`
|
||||
+ `&component_access_token=${encodeURIComponent(componentAccessToken)}`
|
||||
+ `&js_code=${encodeURIComponent(jsCode)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'GET',
|
||||
dataType: 'json',
|
||||
timeout: 30000,
|
||||
});
|
||||
return response && response.data !== undefined ? response.data : response;
|
||||
};
|
||||
|
||||
let result = await request();
|
||||
|
||||
// 40001:component_access_token 被别处刷新顶掉(not latest),清除缓存重取后重试一次
|
||||
if (result && Number(result.errcode) === 40001) {
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.warn('[wechatOpen] jscode2session 40001 component_access_token 失效,清除缓存重试');
|
||||
}
|
||||
await this.cacheDel('component_access_token');
|
||||
result = await request();
|
||||
}
|
||||
|
||||
// 调试:打印微信原始返回报文(仅 openid/session_key/unionid,无昵称头像)
|
||||
if (this.ctx && this.ctx.logger) {
|
||||
this.ctx.logger.info(`[wechatOpen] jscode2session appid=${appid} 返回: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
if (result && result.openid) {
|
||||
return result;
|
||||
}
|
||||
throw new Error(`jscode2session 失败: ${JSON.stringify(result)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理授权方相关缓存(unauthorized 取消授权事件后调用)。
|
||||
* @param {string} appid 授权方小程序 AppID。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async clearAuthorizerCache(appid) {
|
||||
await this.cacheDel(
|
||||
`App:${appid}:authorization_code`,
|
||||
`App:${appid}:authorizer_refresh_token`,
|
||||
`App:${appid}:AuthorizerAccessToken`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存授权 state(发起授权时缓存仓库信息,回跳时凭 state 取回)。
|
||||
* @param {string} state 随机 state。
|
||||
* @param {number|string} warehouseId 仓库ID。
|
||||
* @param {number} [ttl=600] 过期秒数。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async saveAuthState(state, warehouseId, ttl = 600) {
|
||||
await this.cacheSet(
|
||||
`wechat_auth_state:${state}`,
|
||||
JSON.stringify({ warehouse_id: warehouseId, created_at: Math.floor(Date.now() / 1000) }),
|
||||
ttl
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取授权 state 对应的仓库信息。
|
||||
* @param {string} state 随机 state。
|
||||
* @return {Promise<object|null>} { warehouse_id, created_at },不存在/过期返回 null。
|
||||
*/
|
||||
async getAuthState(state) {
|
||||
const cached = await this.cacheGet(`wechat_auth_state:${state}`);
|
||||
if (!cached) return null;
|
||||
try {
|
||||
return JSON.parse(cached);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除授权 state 缓存(回调消费后调用,保证一次性)。
|
||||
* @param {string} state 随机 state。
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async clearAuthState(state) {
|
||||
await this.cacheDel(`wechat_auth_state:${state}`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatOpenClient;
|
||||
223
app/lib/wechat_open_crypt.js
Normal file
223
app/lib/wechat_open_crypt.js
Normal file
@ -0,0 +1,223 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
const { XMLParser } = require('fast-xml-parser');
|
||||
|
||||
/**
|
||||
* 微信开放平台第三方平台消息加解密工具(Node 版 WXBizMsgCrypt)。
|
||||
* 对应微信官方示例(PHP WXBizMsgCrypt)能力:
|
||||
* - URL 有效性验证(首次配置服务器地址时的 echostr 校验)
|
||||
* - 事件推送消息解密(AES-256-CBC + PKCS#7,密文格式:
|
||||
* 16 字节随机串 + 4 字节大端消息长度 + 明文 XML + component_appid)
|
||||
*
|
||||
* 错误码沿用微信官方定义:
|
||||
* -40001 签名验证错误 / -40004 encodingAesKey 非法 / -40005 appid 校验错误 /
|
||||
* -40007 AES 解密失败 / -40008 解密后 buffer 非法 / -40010 base64 解码失败。
|
||||
*/
|
||||
|
||||
const ERROR_CODES = {
|
||||
OK: 0,
|
||||
VALIDATE_SIGNATURE_ERROR: -40001,
|
||||
ILLEGAL_AES_KEY: -40004,
|
||||
VALIDATE_APPID_ERROR: -40005,
|
||||
DECRYPT_AES_ERROR: -40007,
|
||||
ILLEGAL_BUFFER: -40008,
|
||||
DECODE_BASE64_ERROR: -40010,
|
||||
};
|
||||
|
||||
/**
|
||||
* 计算 SHA1(hex)。
|
||||
* @param {string} input 输入字符串。
|
||||
* @return {string} SHA1 摘要。
|
||||
*/
|
||||
function sha1(input) {
|
||||
return crypto.createHash('sha1').update(input, 'utf8').digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成消息签名:sha1(sort(token, timestamp, nonce, encrypt))。
|
||||
* @param {string} token 第三方平台消息校验 Token。
|
||||
* @param {string} timestamp 时间戳。
|
||||
* @param {string} nonce 随机串。
|
||||
* @param {string} [encrypt=''] 加密内容(URL 验证时为空)。
|
||||
* @return {string} 签名。
|
||||
*/
|
||||
function getSignature(token, timestamp, nonce, encrypt = '') {
|
||||
const arr = [ token, String(timestamp), String(nonce), String(encrypt || '') ].sort();
|
||||
return sha1(arr.join(''));
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 URL 有效性签名:signature === sha1(sort(token, timestamp, nonce))。
|
||||
* @param {string} token 第三方平台消息校验 Token。
|
||||
* @param {string} signature 微信回传的 signature。
|
||||
* @param {string} timestamp 时间戳。
|
||||
* @param {string} nonce 随机串。
|
||||
* @return {boolean} 是否通过。
|
||||
*/
|
||||
function verifyUrlSignature(token, signature, timestamp, nonce) {
|
||||
if (!token || !signature || timestamp === undefined || timestamp === null || nonce === undefined || nonce === null) {
|
||||
return false;
|
||||
}
|
||||
const expected = getSignature(token, timestamp, nonce);
|
||||
return expected === String(signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析加密推送 XML,提取 <Encrypt> 内容。
|
||||
* @param {string} encryptedXml 微信推送的加密 XML。
|
||||
* @return {string} Encrypt 密文(base64 字符串)。
|
||||
*/
|
||||
function extractEncrypt(encryptedXml) {
|
||||
if (!encryptedXml) return '';
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
parseTagValue: false,
|
||||
parseAttributeValue: false,
|
||||
trimValues: false,
|
||||
});
|
||||
let parsed;
|
||||
try {
|
||||
parsed = parser.parse(encryptedXml.trim());
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
return (parsed && parsed.xml && parsed.xml.Encrypt) || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* PKCS#7 去除填充。
|
||||
* @param {Buffer} buf 解密后的带填充 buffer。
|
||||
* @return {Buffer} 去填充后的 buffer。
|
||||
*/
|
||||
function pkcs7Decode(buf) {
|
||||
const pad = buf[buf.length - 1];
|
||||
if (pad >= 1 && pad <= 32) {
|
||||
return buf.subarray(0, buf.length - pad);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* AES-256-CBC 解密微信密文。
|
||||
* @param {string} encrypted base64 密文。
|
||||
* @param {Buffer} aesKey 32 字节 AES Key。
|
||||
* @return {{ code: number, buf: Buffer }} 解密结果(失败时 buf 为空 Buffer)。
|
||||
*/
|
||||
function aesDecrypt(encrypted, aesKey) {
|
||||
const encryptedBuf = Buffer.from(String(encrypted), 'base64');
|
||||
if (!encryptedBuf.length) {
|
||||
return { code: ERROR_CODES.DECODE_BASE64_ERROR, buf: Buffer.alloc(0) };
|
||||
}
|
||||
try {
|
||||
const iv = aesKey.subarray(0, 16);
|
||||
const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, iv);
|
||||
decipher.setAutoPadding(false);
|
||||
const decoded = pkcs7Decode(Buffer.concat([ decipher.update(encryptedBuf), decipher.final() ]));
|
||||
return { code: ERROR_CODES.OK, buf: decoded };
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.DECRYPT_AES_ERROR, buf: Buffer.alloc(0) };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密事件推送消息(完整流程:签名校验 → base64/AES 解密 → 报文解析 → appid 校验)。
|
||||
* @param {object} opts 参数。
|
||||
* @param {string} opts.token 第三方平台消息校验 Token。
|
||||
* @param {string} opts.encodingAesKey 第三方平台消息加解密 Key(43 位)。
|
||||
* @param {string} opts.componentAppid 第三方平台 AppID。
|
||||
* @param {string} opts.msgSignature 消息签名 msg_signature。
|
||||
* @param {string|number} opts.timestamp 时间戳。
|
||||
* @param {string} opts.nonce 随机串。
|
||||
* @param {string} opts.encryptedXml 微信推送的加密 XML。
|
||||
* @return {{ code: number, msg: string }} code=0 时 msg 为解密后的明文 XML。
|
||||
*/
|
||||
function decryptMsg(opts) {
|
||||
const {
|
||||
token,
|
||||
encodingAesKey,
|
||||
componentAppid,
|
||||
msgSignature,
|
||||
timestamp,
|
||||
nonce,
|
||||
encryptedXml,
|
||||
} = opts || {};
|
||||
|
||||
const encrypt = extractEncrypt(encryptedXml);
|
||||
if (!encrypt) {
|
||||
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '加密 XML 中未找到 Encrypt 内容' };
|
||||
}
|
||||
|
||||
// 1. 校验消息签名
|
||||
const expectedSignature = getSignature(token, timestamp, nonce, encrypt);
|
||||
if (expectedSignature !== String(msgSignature)) {
|
||||
return { code: ERROR_CODES.VALIDATE_SIGNATURE_ERROR, msg: '消息签名校验失败' };
|
||||
}
|
||||
|
||||
// 2. AES Key(encodingAesKey 43 位补 '=' 后 base64 解码为 32 字节)
|
||||
let aesKey;
|
||||
try {
|
||||
aesKey = Buffer.from(String(encodingAesKey) + '=', 'base64');
|
||||
} catch (e) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 非法' };
|
||||
}
|
||||
if (aesKey.length !== 32) {
|
||||
return { code: ERROR_CODES.ILLEGAL_AES_KEY, msg: 'encodingAesKey 解码后长度不是 32 字节' };
|
||||
}
|
||||
|
||||
// 3. AES 解密
|
||||
const decrypted = aesDecrypt(encrypt, aesKey);
|
||||
if (decrypted.code !== ERROR_CODES.OK) {
|
||||
return { code: decrypted.code, msg: 'AES 解密失败' };
|
||||
}
|
||||
|
||||
// 4. 解析明文(二进制 buffer):16 字节随机串 + 4 字节大端长度 + 消息体 + appid
|
||||
const content = decrypted.buf;
|
||||
if (content.length < 20) {
|
||||
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后 buffer 长度非法' };
|
||||
}
|
||||
const msgLen = content.readUInt32BE(16);
|
||||
if (20 + msgLen > content.length) {
|
||||
return { code: ERROR_CODES.ILLEGAL_BUFFER, msg: '解密后消息长度非法' };
|
||||
}
|
||||
const xmlContent = content.subarray(20, 20 + msgLen).toString('utf8');
|
||||
const fromAppid = content.subarray(20 + msgLen).toString('utf8');
|
||||
|
||||
// 5. 校验 appid
|
||||
if (fromAppid !== String(componentAppid)) {
|
||||
return { code: ERROR_CODES.VALIDATE_APPID_ERROR, msg: `appid 校验失败: ${fromAppid}` };
|
||||
}
|
||||
|
||||
return { code: ERROR_CODES.OK, msg: xmlContent };
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析明文 XML 为对象({ AppId, InfoType, ... })。
|
||||
* @param {string} xml 明文 XML。
|
||||
* @return {object} 解析后的对象(失败返回空对象)。
|
||||
*/
|
||||
function parseXml(xml) {
|
||||
if (!xml) return {};
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: false,
|
||||
parseTagValue: false,
|
||||
parseAttributeValue: false,
|
||||
trimValues: false,
|
||||
});
|
||||
try {
|
||||
const parsed = parser.parse(xml.trim());
|
||||
return (parsed && parsed.xml) || {};
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ERROR_CODES,
|
||||
sha1,
|
||||
getSignature,
|
||||
verifyUrlSignature,
|
||||
extractEncrypt,
|
||||
decryptMsg,
|
||||
parseXml,
|
||||
};
|
||||
156
app/model/user_oauth.js
Normal file
156
app/model/user_oauth.js
Normal file
@ -0,0 +1,156 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 用户第三方授权表模型。
|
||||
* 保存用户通过第三方厂商(微信等)OAuth 登录后的授权信息与令牌信息。
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const UserOauth = app.model.define('userOauth', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
user_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '用户ID(关联 account.id)',
|
||||
},
|
||||
app_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '微信应用ID(关联 wms_wechat_app.id),用于取对应应用 token 处理',
|
||||
},
|
||||
provider: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '厂商,如 wechat/mini_program',
|
||||
},
|
||||
platform: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '平台,如 h5/app/mp',
|
||||
},
|
||||
unionid: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '厂商统一ID(同一厂商跨应用唯一,部分平台无)',
|
||||
},
|
||||
openid: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '平台内唯一ID',
|
||||
},
|
||||
nickname: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '昵称',
|
||||
},
|
||||
sex: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '性别:0=未知,1=男,2=女',
|
||||
},
|
||||
country: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '国家',
|
||||
},
|
||||
province: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '省',
|
||||
},
|
||||
city: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '市',
|
||||
},
|
||||
headimgurl: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '头像URL',
|
||||
},
|
||||
login_time: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '最近登录时间(unix秒级时间戳)',
|
||||
},
|
||||
login_count: {
|
||||
type: INTEGER(11),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '累计登录次数',
|
||||
},
|
||||
expire_in: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '令牌过期周期(秒)',
|
||||
},
|
||||
expire_time: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '令牌过期时间(unix秒级时间戳)',
|
||||
},
|
||||
session_key: {
|
||||
type: STRING(45),
|
||||
allowNull: true,
|
||||
comment: '会话密钥(微信小程序登录态)',
|
||||
},
|
||||
refresh_token: {
|
||||
type: STRING(110),
|
||||
allowNull: true,
|
||||
comment: '刷新令牌',
|
||||
},
|
||||
access_token: {
|
||||
type: STRING(110),
|
||||
allowNull: true,
|
||||
comment: '访问令牌',
|
||||
},
|
||||
login_code: {
|
||||
type: STRING(128),
|
||||
allowNull: true,
|
||||
comment: '登录码({uuid,id_6} JSON 的 base64,一次性消费)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_user_oauth',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '用户第三方授权表',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'app_id', 'provider', 'openid' ],
|
||||
name: 'uk_app_provider_openid',
|
||||
},
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'login_code' ],
|
||||
name: 'uk_login_code',
|
||||
},
|
||||
{
|
||||
fields: [ 'user_id' ],
|
||||
name: 'idx_user_id',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return UserOauth;
|
||||
};
|
||||
203
app/model/wechat_app.js
Normal file
203
app/model/wechat_app.js
Normal file
@ -0,0 +1,203 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 微信开放平台授权小程序表模型。
|
||||
* 记录仓库(主体)授权的小程序信息与令牌,供业务按小程序维度调用微信接口。
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, TINYINT, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const WechatApp = app.model.define('wechatApp', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
comment: '主键',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库ID(绑定关系,NULL=已授权待绑定仓库)',
|
||||
},
|
||||
appid: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
comment: '小程序AppID',
|
||||
},
|
||||
nickname: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '小程序名称',
|
||||
},
|
||||
user_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '小程序原始ID(gh_xxx)',
|
||||
},
|
||||
head_img: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '小程序头像URL',
|
||||
},
|
||||
authorizer_refresh_token: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '授权方刷新令牌(长期有效,防 Redis 丢失)',
|
||||
},
|
||||
auth_time: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '授权时间(unix秒级时间戳)',
|
||||
},
|
||||
func_info: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '授权权限集合(JSON 字符串,来自 api_query_auth)',
|
||||
},
|
||||
template_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '当前上传的代码模板ID(wxa/commit 成功后记录)',
|
||||
},
|
||||
user_version: {
|
||||
type: STRING(64),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '当前上传的代码版本号(wxa/commit 成功后记录)',
|
||||
},
|
||||
audit_status: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '代码审核状态:0=未提交,1=审核中,2=审核通过,3=审核驳回',
|
||||
},
|
||||
audit_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '微信审核单ID(wxa/submit_audit 返回的 auditid)',
|
||||
},
|
||||
audit_reason: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '代码审核驳回原因',
|
||||
},
|
||||
principal_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '主体名称',
|
||||
},
|
||||
signature: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '小程序账号介绍',
|
||||
},
|
||||
alias: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '微信号(可能为空)',
|
||||
},
|
||||
qrcode_url: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '二维码图片URL',
|
||||
},
|
||||
service_type_id: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '账号类型id(0 普通小程序等)',
|
||||
},
|
||||
verify_type_id: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '认证类型id(-1 未认证,0 微信认证,1 新浪微博认证,3 资质通过未名称认证,4 同3+微博)',
|
||||
},
|
||||
account_status: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '账号状态(1 正常,14 已注销,16 已封禁,18 已告警,19 已冻结)',
|
||||
},
|
||||
register_type: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '小程序注册方式(0 普通,6 法人扫脸创建企业小程序等)',
|
||||
},
|
||||
business_info: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '功能开通状况 JSON',
|
||||
},
|
||||
mini_program_info: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '小程序配置信息 JSON(network/categories/visit_status)',
|
||||
},
|
||||
auth_task_id: {
|
||||
type: STRING(64),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '微信认证任务ID(发起认证接口返回)',
|
||||
},
|
||||
auth_task_status: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '认证任务流程状态(task_status 0-15)',
|
||||
},
|
||||
auth_apply_status: {
|
||||
type: TINYINT,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '认证审核单状态(apply_status 0-5)',
|
||||
},
|
||||
is_enabled: {
|
||||
type: TINYINT(1),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '是否启用:1=启用,0=停用',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_wechat_app',
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '微信开放平台授权小程序表(仓库绑定)',
|
||||
indexes: [
|
||||
{
|
||||
unique: true,
|
||||
fields: [ 'appid' ],
|
||||
name: 'uk_appid',
|
||||
},
|
||||
{
|
||||
fields: [ 'warehouse_id' ],
|
||||
name: 'idx_warehouse_id',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return WechatApp;
|
||||
};
|
||||
@ -8,6 +8,10 @@ module.exports = app => {
|
||||
router.get('/auth/platformOauthBind', controller.home.platformOauthBind);
|
||||
router.get('/query/pddCode/:code', controller.home.queryPddCode);
|
||||
|
||||
// 微信开放平台第三方平台授权事件接收(GET=URL验证,POST=事件推送)
|
||||
router.get('/Authorization', controller.wechatOpen.authorization);
|
||||
router.post('/Authorization', controller.wechatOpen.authorization);
|
||||
|
||||
// 内部网关接口
|
||||
router.post('/internal/v1/gateway', controller.gateway.internal);
|
||||
|
||||
|
||||
@ -16,6 +16,7 @@ class MainService extends Service {
|
||||
this._noNeedLogin = null;
|
||||
this._noNeedRight = null;
|
||||
this._noNeedAuth = null;
|
||||
this._noNeedBind = null;
|
||||
this.user = null;
|
||||
this.userId = null;
|
||||
}
|
||||
@ -307,6 +308,7 @@ class MainService extends Service {
|
||||
const _noNeedRight = (this._noNeedRight || '').split(',');
|
||||
const _noNeedAuth = (this._noNeedAuth || '').split(',');
|
||||
const _noNeedLog = (this._noNeedLog || '').split(',');
|
||||
const _noNeedBind = (this._noNeedBind || '').split(',');
|
||||
const api_path = `${servicePath}.${actionName}`;
|
||||
const result = {
|
||||
status: 401,
|
||||
@ -358,6 +360,51 @@ class MainService extends Service {
|
||||
// 设置新的 token 到响应头
|
||||
ctx.set('Authorization', `Bearer ${newToken}`);
|
||||
}
|
||||
|
||||
// 3.5 中间层:白名单内的接口优先按真实用户放行(正常登录 token 或已绑定 oauth token),
|
||||
// 未绑定真实用户的微信登录态(oauth_id + user_id=0)作为兜底放行,业务方法经 ctx.oauth 取微信身份。
|
||||
if (_noNeedBind.indexOf('*') > -1 || _noNeedBind.indexOf(actionName) > -1) {
|
||||
let oauth = null;
|
||||
const oauthId = Number(decoded.oauth_id || 0);
|
||||
if (Number.isInteger(oauthId) && oauthId > 0) {
|
||||
oauth = await ctx.model.UserOauth.findByPk(oauthId, { raw: true });
|
||||
if (oauth) {
|
||||
ctx.oauth = oauth;
|
||||
ctx.oauthId = oauth.id;
|
||||
}
|
||||
}
|
||||
|
||||
// 1. 有真实用户(oauth.user_id 或 token id)→ 按正常用户上下文放行
|
||||
const userId = oauth ? Number(oauth.user_id || 0) : Number(decoded.id || decoded.userId || 0);
|
||||
if (userId > 0) {
|
||||
const bindUser = await ctx.service.systems.auth.user.findById(userId);
|
||||
if (bindUser) {
|
||||
if (bindUser.status !== 1) {
|
||||
result.status = 403;
|
||||
result.message = '账号已被禁用';
|
||||
return result;
|
||||
}
|
||||
this.setUserContext(ctx, bindUser, decoded);
|
||||
result.status = 200;
|
||||
result.message = 'ok';
|
||||
result.user = bindUser;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 未绑定真实用户的微信登录态 → 兜底放行(ctx.oauth 可用)
|
||||
if (oauth) {
|
||||
result.status = 200;
|
||||
result.message = 'ok';
|
||||
return result;
|
||||
}
|
||||
|
||||
// 3. 既无用户也无微信登录态 → 401
|
||||
result.status = 401;
|
||||
result.message = '未提供有效的微信登录态';
|
||||
return result;
|
||||
}
|
||||
|
||||
// 4. 获取用户信息
|
||||
const user = await ctx.service.systems.auth.user.findById(decoded.id || decoded.userId);
|
||||
|
||||
@ -619,11 +666,12 @@ class MainService extends Service {
|
||||
ctx.jwtPayload = decoded;
|
||||
}
|
||||
|
||||
systemInit(_noNeedLogin, _noNeedRight, _noNeedLog = '*', _noNeedAuth = '*') {
|
||||
systemInit(_noNeedLogin, _noNeedRight, _noNeedLog = '*', _noNeedAuth = '*', _noNeedBind = '') {
|
||||
this._noNeedLogin = _noNeedLogin;
|
||||
this._noNeedRight = _noNeedRight;
|
||||
this._noNeedLog = _noNeedLog;
|
||||
this._noNeedAuth = _noNeedAuth;
|
||||
this._noNeedBind = _noNeedBind;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -3399,11 +3399,18 @@ class indexService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据 token(ye4s 登录临时码 tmp_code)查询用户信息。
|
||||
* 根据 token 查询用户信息(免登录、免鉴权,工作台工牌扫码用)。
|
||||
*
|
||||
* 支持两种 token:
|
||||
* 1. 微信工牌码(登录码):base64 的 {uuid:'{oauth_id}_{6位随机}',form:'wechat'},
|
||||
* 按 uuid 前缀取 wms_user_oauth.id → 返回 nickname / user_id;
|
||||
* 已绑定账号(user_id>0)时返回 wms_account_store_employee 的工号名称(real_name),
|
||||
* 未绑定时直接返回 wms_user_oauth.nickname。
|
||||
* 2. ye4s 登录临时码:对应 ye4s_user.tmp_code(旧流程兜底)。
|
||||
*
|
||||
* @param {Object} data 请求参数
|
||||
* @param {string} data.token ye4s 登录临时码(对应 ye4s_user.tmp_code)
|
||||
* @return {Promise<Object>} 统一响应结构;命中时返回 real_name 与 wms_account_id,未命中时返回失败响应(code=404)
|
||||
* @param {string} data.token 微信工牌码(base64)或 ye4s 登录临时码
|
||||
* @return {Promise<Object>} 统一响应结构;命中时返回 real_name 与 user_id/wms_account_id,未命中时返回失败响应(code=404)
|
||||
*/
|
||||
async queryUserByToken(data = {}) {
|
||||
const { ctx } = this;
|
||||
@ -3413,11 +3420,24 @@ class indexService extends MainService {
|
||||
return this.fail('token 不能为空', { code: 400 });
|
||||
}
|
||||
|
||||
const rawToken = String(token).trim();
|
||||
|
||||
// 微信工牌码(base64 + uuid + wechat 来源):走 wms_user_oauth 查询
|
||||
const wechatBadge = this.parseWechatBadgeCode(rawToken);
|
||||
if (wechatBadge) {
|
||||
try {
|
||||
return await this.queryUserByWechatBadge(wechatBadge.oauthId);
|
||||
} catch (error) {
|
||||
ctx.logger.error('工牌查询用户失败:', error);
|
||||
return this.fail(error.message || '查询用户失败', { code: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const ye4sClient = ctx.app.mysql.get('ye4s');
|
||||
const rows = await ye4sClient.select('ye4s_user', {
|
||||
where: {
|
||||
tmp_code: String(token).trim(),
|
||||
tmp_code: rawToken,
|
||||
},
|
||||
columns: [ 'real_name', 'wms_account_id' ],
|
||||
limit: 1,
|
||||
@ -3438,5 +3458,84 @@ class indexService extends MainService {
|
||||
return this.fail(error.message || '查询用户失败', { code: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析微信工牌码:base64 的 {uuid:'{oauth_id}_{6位随机}',form:'wechat'}
|
||||
* - 解码为 JSON 且来源为 wechat 时返回 { oauthId }(wms_user_oauth.id)
|
||||
* - 其他内容(ye4s 临时码等)返回 null,由调用方走旧逻辑
|
||||
*
|
||||
* @param {string} token 工牌码原文
|
||||
* @return {{oauthId: number}|null} 解析结果
|
||||
*/
|
||||
parseWechatBadgeCode(token) {
|
||||
try {
|
||||
const text = String(token || '').trim();
|
||||
// 快速预判:长度与字符集需符合 base64,避免每条码都走解码
|
||||
if (!text || text.length < 16 || !/^[A-Za-z0-9+/=_-]+$/.test(text)) {
|
||||
return null;
|
||||
}
|
||||
const b64 = text.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const decoded = Buffer.from(b64, 'base64').toString('utf8');
|
||||
if (!decoded || !decoded.trim().startsWith('{')) {
|
||||
return null;
|
||||
}
|
||||
const payload = JSON.parse(decoded);
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
return null;
|
||||
}
|
||||
const form = payload.form || payload.source || '';
|
||||
const uuid = payload.uuid || '';
|
||||
if (String(form) !== 'wechat' || !uuid) {
|
||||
return null;
|
||||
}
|
||||
// uuid 形如 {oauth_id}_{6位随机},取前缀作为 wms_user_oauth.id
|
||||
const oauthId = Number(String(uuid).split('_')[0]);
|
||||
if (!Number.isInteger(oauthId) || oauthId <= 0) {
|
||||
return null;
|
||||
}
|
||||
return { oauthId };
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信工牌查询用户:按 wms_user_oauth.id 取 nickname/user_id;
|
||||
* 已绑定账号(user_id>0)时返回 wms_account_store_employee 的工号名称(real_name),
|
||||
* 未绑定/无工号记录时直接返回 wms_user_oauth.nickname。
|
||||
*
|
||||
* @param {number} oauthId wms_user_oauth.id
|
||||
* @return {Promise<Object>} 统一响应结构
|
||||
*/
|
||||
async queryUserByWechatBadge(oauthId) {
|
||||
const { ctx } = this;
|
||||
|
||||
const oauth = await ctx.model.UserOauth.findByPk(oauthId);
|
||||
if (!oauth) {
|
||||
return this.fail('用户不存在', { code: 404 });
|
||||
}
|
||||
|
||||
const userId = Number(oauth.user_id) || 0;
|
||||
let realName = oauth.nickname || '';
|
||||
|
||||
// 已绑定账号:拉取 wms_account_store_employee 工号名称(real_name,status=1)
|
||||
if (userId > 0) {
|
||||
const employee = await ctx.model.AccountStoreEmployee.findOne({
|
||||
where: { account_id: userId, status: 1 },
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
if (employee && employee.real_name) {
|
||||
realName = employee.real_name;
|
||||
}
|
||||
}
|
||||
|
||||
return this.success('查询成功', {
|
||||
real_name: realName,
|
||||
user_id: userId > 0 ? userId : null,
|
||||
wms_account_id: userId > 0 ? userId : null,
|
||||
nickname: oauth.nickname || '',
|
||||
code: 200,
|
||||
});
|
||||
}
|
||||
}
|
||||
module.exports = indexService;
|
||||
|
||||
@ -6,9 +6,9 @@ class SettingWarehouseMethodsService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert';
|
||||
const _noNeedRight = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert,getweChatApp';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert';
|
||||
const _noNeedAuth = 'getSettings,getFieldMeta,saveSettings,getFrontConfig,saveFrontConfig,saveFrontCert,getweChatApp';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -183,6 +183,31 @@ class SettingWarehouseMethodsService extends MainService {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前仓库启用的微信小程序授权配置(wms_wechat_app)。
|
||||
*
|
||||
* 仅返回一条启用(is_enabled=1)记录,配置统一封装在响应 data 字段中,
|
||||
* data 为对象而非数组;无可用记录时 data 为 null。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getweChatApp() {
|
||||
const targetService = this.service && this.service.systems && this.service.systems.setting && this.service.systems.setting.warehouse;
|
||||
|
||||
if (!targetService || typeof targetService.getWechatApp !== 'function') {
|
||||
return this.fail('获取微信小程序配置失败', { code: 500 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await targetService.getWechatApp();
|
||||
return this.success('ok', { data: result });
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '获取微信小程序配置失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingWarehouseMethodsService;
|
||||
|
||||
@ -9,7 +9,9 @@ class userService extends MainService {
|
||||
const _noNeedRight = '*';
|
||||
const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode';
|
||||
const _noNeedAuth = '*';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
// info:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问
|
||||
const _noNeedBind = 'info';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth, _noNeedBind);
|
||||
}
|
||||
async login(data) {
|
||||
const { service } = this;
|
||||
|
||||
322
app/service/systemMethods/wechat.js
Normal file
322
app/service/systemMethods/wechat.js
Normal file
@ -0,0 +1,322 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
/**
|
||||
* 微信开放平台 method 层(system.json module: wechat)。
|
||||
*/
|
||||
class WechatService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
// getAuthUrl:需登录、免权限、不记系统日志;loginByCode:免登录、免权限、免鉴权;
|
||||
// pushLoginCode/queryauth/registerMiniprogram/getTemplateList/commit/getTrialQRCode/submitAudit/userList:需登录、免权限(PC 已登录用户操作);
|
||||
// bindUser/updateInfo/uploadHeadimg/getMyLoginCode:微信登录态中间层(_noNeedBind),未绑定真实用户也可访问
|
||||
this.systemInit('loginByCode', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo', '*', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo', 'bindUser,updateInfo,uploadHeadimg,getMyLoginCode');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前微信登录用户的登录码(至少微信登录):无则生成写入,有则直接返回。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getMyLoginCode() {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.getMyLoginCode();
|
||||
if (result && result.success === true) {
|
||||
return this.success(result.message || '获取成功', result.data);
|
||||
}
|
||||
return this.fail((result && result.message) || '获取失败');
|
||||
} catch (e) {
|
||||
return this.fail('获取登录码失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async getAuthUrl(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.getAuthUrl(data || {});
|
||||
return this.success('获取成功', result);
|
||||
} catch (e) {
|
||||
return this.fail(e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 小程序登录码登录(免登录):入参 code + app_id,返回 token + user(参考 auth.login)。
|
||||
*
|
||||
* @param {Object} data 请求参数。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async loginByCode(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.loginByCode(data || {});
|
||||
if (result.code) {
|
||||
return this.success('登录成功', result);
|
||||
}
|
||||
return this.fail('登录失败:' + result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('登录失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定用户(微信登录态中间层):用户名密码一致则绑定并签发新 token。
|
||||
*
|
||||
* @param {Object} data 请求参数(username/password)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async bindUser(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.bindUser(data || {});
|
||||
if (result.code) {
|
||||
return this.success('绑定成功', result);
|
||||
}
|
||||
return this.fail('绑定失败:' + result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('绑定失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认登录码(需登录,PC 已登录用户确认小程序登录)。
|
||||
*
|
||||
* @param {Object} data 请求参数(code)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async pushLoginCode(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.pushLoginCode(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '操作成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('确认登录失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询当前仓库小程序认证状态(需登录)。
|
||||
*
|
||||
* @param {Object} data 请求参数(taskid)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async queryauth(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.queryauth(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '查询成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('查询认证状态失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起小程序认证(需登录):前端上传材料换取 media_id 后一步提交。
|
||||
*
|
||||
* @param {Object} data 请求参数(contact_type/contact_name 必填,其余白名单字段透传)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async wxaauth(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.wxaauth(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '认证已发起', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('发起认证失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取并同步当前仓库小程序基础信息(需登录)。
|
||||
*
|
||||
* 调微信 api_get_authorizer_info 拉取授权账号详情(authorizer_info + authorization_info),
|
||||
* 将基础信息/认证类型/权限集等落库 wms_wechat_app 后返回完整数据。
|
||||
*
|
||||
* @param {Object} data 请求参数(无)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getAuthorizerInfo(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.getAuthorizerInfo(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '获取成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('获取小程序基础信息失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速注册企业小程序(需登录)。
|
||||
*
|
||||
* @param {Object} data 请求参数(name/code/code_type/legal_persona_wechat/legal_persona_name/component_phone)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async registerMiniprogram(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.registerMiniprogram(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '操作成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('注册小程序失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新微信账号资料(微信登录态中间层,仅未绑定用户)。
|
||||
*
|
||||
* @param {Object} data 请求参数(nickname/headimgurl)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async updateInfo(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.updateInfo(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '更新成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('更新失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传微信账号头像(微信登录态中间层,至少微信登录即可)。
|
||||
*
|
||||
* @param {Object} data 请求参数(image: 裁剪后的 PNG base64)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async uploadHeadimg(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.uploadHeadimg(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '上传成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('上传头像失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取小程序模板库列表(需登录,Redis 缓存 24h)。
|
||||
*
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getTemplateList() {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.getTemplateList();
|
||||
if (result.code) {
|
||||
return this.success(result.message || '获取成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('获取模板列表失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传代码并生成体验版(需登录)。
|
||||
*
|
||||
* @param {Object} data 请求参数(template_id/ext_json/user_version/user_desc)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async commit(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.commit(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '上传成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('上传代码失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取体验版二维码(需登录)。
|
||||
*
|
||||
* @param {Object} data 请求参数(可选 path)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getTrialQRCode(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.getTrialQRCode(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '获取成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('获取体验版二维码失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交代码审核(需登录)。
|
||||
*
|
||||
* @param {Object} data 请求参数(item_list/version_desc 等,均为可选)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async submitAudit(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.submitAudit(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '提交成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('提交代码审核失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取当前仓库小程序的用户列表(需登录,支持 where/pagination/sort)。
|
||||
*
|
||||
* @param {Object} data 请求参数(可选 app_id/where/pagination/sort)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async userList(data = {}) {
|
||||
try {
|
||||
// where 字段白名单:仅允许按用户表常规字段过滤,禁止探测敏感列
|
||||
const allowedWhereFields = new Set([
|
||||
'id',
|
||||
'user_id',
|
||||
'app_id',
|
||||
'openid',
|
||||
'unionid',
|
||||
'nickname',
|
||||
'sex',
|
||||
'login_time',
|
||||
'login_count',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
]);
|
||||
const rawWhere = data.where && typeof data.where === 'object' ? data.where : {};
|
||||
const filteredWhere = {};
|
||||
for (const key of Object.keys(rawWhere)) {
|
||||
if (allowedWhereFields.has(key)) {
|
||||
filteredWhere[key] = rawWhere[key];
|
||||
}
|
||||
}
|
||||
data.where = filteredWhere;
|
||||
|
||||
this.prepareWhereContext(data);
|
||||
const result = await this.service.systems.wechat.userList(data);
|
||||
if (result.code) {
|
||||
return this.success(result.message || '获取成功', result.data);
|
||||
}
|
||||
return this.fail(result.message);
|
||||
} catch (e) {
|
||||
return this.fail('获取用户列表失败:' + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatService;
|
||||
@ -305,6 +305,38 @@ class UserService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布微信登录事件(唤醒 user.getLoginWechatCode 打开的长轮询)。
|
||||
*
|
||||
* @param {string} clientCode 客户端编码。
|
||||
* @param {object} [payload={}] 附加事件数据(如 ye4s_user_id)。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async publishWechatLoginEvent(clientCode, payload = {}) {
|
||||
const { app } = this;
|
||||
if (!clientCode) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
|
||||
if (!cacheRedis) {
|
||||
return;
|
||||
}
|
||||
|
||||
const channel = this.getWechatLoginEventChannel(clientCode);
|
||||
const eventData = {
|
||||
client_code: clientCode,
|
||||
event_at: new Date().toISOString(),
|
||||
...payload,
|
||||
};
|
||||
|
||||
try {
|
||||
await cacheRedis.publish(channel, JSON.stringify(eventData));
|
||||
} catch (error) {
|
||||
app.coreLogger.warn(`发布微信登录事件失败: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async waitForWechatBindEvent(accountId, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) {
|
||||
const { app } = this;
|
||||
const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null;
|
||||
@ -1629,14 +1661,62 @@ class UserService extends Service {
|
||||
|
||||
/**
|
||||
* 获取用户信息(重构版)
|
||||
* @return {Object} 用户信息
|
||||
* @param {Object} [data={}] 入参。
|
||||
* @param {string} [data.wechat_appId] 小程序 AppID:传入时按该小程序归属仓库过滤工号列表,
|
||||
* 仅保留非仓库工号(货主)与该仓库工号;未传入/查不到仓库时保持原逻辑。
|
||||
* @return {Object} 用户信息
|
||||
*/
|
||||
async info() {
|
||||
async info(data = {}) {
|
||||
const { ctx } = this;
|
||||
try {
|
||||
// 微信登录态中间层:未绑定真实用户时返回微信层信息(不 401)
|
||||
if (!ctx.userId && !ctx.user && ctx.oauth) {
|
||||
const oauth = ctx.oauth;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
id: Number(oauth.user_id) || 0,
|
||||
is_bound: Number(oauth.user_id) > 0,
|
||||
oauth_id: oauth.id,
|
||||
user_id: Number(oauth.user_id) || 0,
|
||||
openid: oauth.openid,
|
||||
unionid: oauth.unionid || '',
|
||||
nickname: oauth.nickname || '',
|
||||
headimgurl: oauth.headimgurl || '',
|
||||
login_time: oauth.login_time,
|
||||
login_count: oauth.login_count,
|
||||
},
|
||||
code: 200,
|
||||
};
|
||||
}
|
||||
|
||||
const userId = ctx.userId || (ctx.user && ctx.user.id);
|
||||
const user = await this.findById(userId);
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 401,
|
||||
};
|
||||
}
|
||||
|
||||
// 可选:传入 wechat_appId 时按小程序归属仓库过滤工号列表
|
||||
// (只保留非仓库工号(货主)与仅该仓库工号)
|
||||
const appId = typeof data.wechat_appId === 'string' ? data.wechat_appId.trim() : '';
|
||||
if (appId) {
|
||||
const wechatApp = await ctx.model.WechatApp.findOne({
|
||||
where: { appid: appId, is_enabled: 1 },
|
||||
attributes: [ 'id', 'appid', 'warehouse_id' ],
|
||||
});
|
||||
const warehouseId = Number(wechatApp && wechatApp.warehouse_id);
|
||||
if (wechatApp && Number.isInteger(warehouseId) && warehouseId > 0 && Array.isArray(user.employees)) {
|
||||
user.employees = user.employees.filter(
|
||||
employee => String(employee.role_type) !== 'warehouse' || Number(employee.store_id) === warehouseId
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: user,
|
||||
|
||||
@ -403,6 +403,48 @@ class UploadService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务器端上传 Buffer(小文件直传,如前端裁剪后的头像)。
|
||||
*
|
||||
* @param {Buffer} buffer 文件内容 Buffer。
|
||||
* @param {Object} options 上传选项(key 必传或由 generateFileName 生成;
|
||||
* maxSizeBytes 覆盖大小上限;mimetype 限定后缀)。
|
||||
* @return {Promise<Object>} 上传结果(fileName/url/cdnUrl/cosUrl/etag 等)。
|
||||
*/
|
||||
async uploadBuffer(buffer, options = {}) {
|
||||
const { bucket, region, uploadurl, cdnurl } = this.getCosConfig();
|
||||
if (!Buffer.isBuffer(buffer) || buffer.length === 0) {
|
||||
throw new Error('上传内容为空');
|
||||
}
|
||||
|
||||
const filename = options.filename || 'image.png';
|
||||
this.validateFile({ filename, fileSize: buffer.length }, options);
|
||||
|
||||
const fileName = options.key || this.generateFileName(
|
||||
filename,
|
||||
options.mimeType || 'image/png',
|
||||
options.category
|
||||
);
|
||||
|
||||
const result = await this.cos.putObject({
|
||||
Bucket: bucket,
|
||||
Region: region,
|
||||
Key: fileName,
|
||||
Body: buffer,
|
||||
ContentLength: buffer.length,
|
||||
});
|
||||
|
||||
return {
|
||||
fileName,
|
||||
cosUrl: `${uploadurl}/${fileName}`,
|
||||
cdnUrl: `${cdnurl}/${fileName}`,
|
||||
url: `${cdnurl}/${fileName}`,
|
||||
etag: result.ETag,
|
||||
location: result.Location,
|
||||
uploadAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证文件
|
||||
* @param {Object} fileStream 文件流对象
|
||||
|
||||
1450
app/service/systems/wechat.js
Normal file
1450
app/service/systems/wechat.js
Normal file
File diff suppressed because it is too large
Load Diff
104
app/view/wechat_auth_callback.html
Normal file
104
app/view/wechat_auth_callback.html
Normal file
@ -0,0 +1,104 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-cn">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title><%= title %></title>
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 24px;
|
||||
background: #f5f7fb;
|
||||
color: #1f2937;
|
||||
font-family: "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
.card {
|
||||
max-width: 560px;
|
||||
margin: 40px auto;
|
||||
background: #ffffff;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 10px 30px rgba(15, 23, 42, 0.08);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.header {
|
||||
padding: 20px 24px;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.summary {
|
||||
margin: 16px 24px 0;
|
||||
padding: 16px;
|
||||
border-radius: 10px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.summary.success { background: #ecfdf3; color: #027a48; }
|
||||
.summary.error { background: #fef3f2; color: #b42318; }
|
||||
|
||||
.content {
|
||||
padding: 16px 24px 24px;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px dashed #e5e7eb;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.row:last-child { border-bottom: none; }
|
||||
|
||||
.label {
|
||||
width: 120px;
|
||||
color: #6b7280;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.value {
|
||||
word-break: break-all;
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin-top: 12px;
|
||||
font-size: 13px;
|
||||
color: #9ca3af;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<div class="header">
|
||||
<h1><%= title %></h1>
|
||||
</div>
|
||||
<div class="summary <%= resultLevel %>"><%= resultText %></div>
|
||||
<div class="content">
|
||||
<% if (resultLevel === 'success') { %>
|
||||
<div class="row">
|
||||
<div class="label">小程序AppID</div>
|
||||
<div class="value"><%= appid %></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="label">小程序名称</div>
|
||||
<div class="value"><%= nickname || '-' %></div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="label">绑定仓库ID</div>
|
||||
<div class="value"><%= warehouseId === null || warehouseId === undefined ? '-' : warehouseId %></div>
|
||||
</div>
|
||||
<div class="hint">授权信息已保存,可返回系统查看小程序列表。</div>
|
||||
<% } else { %>
|
||||
<div class="hint">请返回系统重新发起授权。</div>
|
||||
<% } %>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@ -48,6 +48,18 @@ module.exports = appInfo => {
|
||||
appKey: 23535631,
|
||||
security: 'd0cbd3935e3afa2b42b5dc600c08a795',
|
||||
};
|
||||
// 微信开放平台第三方平台(组件)配置:接收授权事件推送与调用授权方接口。
|
||||
// 值可被 config.local.js / config.prod.js 覆盖。
|
||||
config.wechatOpen = {
|
||||
component_appid: 'wx6e91ec813bcb7eec',
|
||||
component_secret: '8e76ea205dcc1d3e506ce6c102375bdd',
|
||||
token: 'lujS6QH8jUkabwOwMuAqe9odz7',
|
||||
encoding_aes_key: 'lujS6QH8jUkabwOwMuAqe9odz7jmKEnT37XMahpSmrU',
|
||||
api_base: 'https://api.weixin.qq.com',
|
||||
// 授权完成后的回跳地址(微信开放平台授权链接 redirect_uri,须为系统 /Authorization 路由;
|
||||
// 域名须在微信开放平台登记为授权回调域名,前端 nginx 已将 /Authorization 代理到本系统)
|
||||
redirect_uri: 'https://wms.wms.gztbyc.com/Authorization',
|
||||
};
|
||||
config.deepseek = {
|
||||
apiKey: process.env.DEEPSEEK_API_KEY || '',
|
||||
baseUrl: 'https://api.deepseek.com',
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user