From 258232f98d3eaa759f9ff98eda772731a58c3cfb Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 23 Sep 2026 02:46:28 +0800 Subject: [PATCH] =?UTF-8?q?feat(wechat):=20=E5=BE=AE=E4=BF=A1=E5=BC=80?= =?UTF-8?q?=E6=94=BE=E5=B9=B3=E5=8F=B0=E7=AC=AC=E4=B8=89=E6=96=B9=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0=E6=8E=A5=E5=85=A5=EF=BC=9A=E6=8E=88=E6=9D=83=E4=BA=8B?= =?UTF-8?q?=E4=BB=B6=E5=9B=9E=E8=B0=83=E3=80=81=E5=8A=A0=E8=A7=A3=E5=AF=86?= =?UTF-8?q?=E3=80=81OpenAPI=20=E5=AE=A2=E6=88=B7=E7=AB=AF=E3=80=81oauth=20?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E6=80=81=E4=B8=AD=E9=97=B4=E5=B1=82=E4=B8=8E?= =?UTF-8?q?=E5=B7=A5=E7=89=8C=E6=89=AB=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controller/wechatOpen.js | 338 ++++ app/lib/wechat_open_client.js | 677 ++++++++ app/lib/wechat_open_crypt.js | 223 +++ app/model/user_oauth.js | 156 ++ app/model/wechat_app.js | 203 +++ app/router.js | 4 + app/service/main.js | 50 +- app/service/systemMethods/index.js | 107 +- .../systemMethods/setting/warehouse.js | 29 +- app/service/systemMethods/user.js | 4 +- app/service/systemMethods/wechat.js | 322 ++++ app/service/systems/auth/user.js | 84 +- app/service/systems/upload.js | 42 + app/service/systems/wechat.js | 1450 +++++++++++++++++ app/view/wechat_auth_callback.html | 104 ++ config/config.default.js | 12 + 16 files changed, 3795 insertions(+), 10 deletions(-) create mode 100644 app/controller/wechatOpen.js create mode 100644 app/lib/wechat_open_client.js create mode 100644 app/lib/wechat_open_crypt.js create mode 100644 app/model/user_oauth.js create mode 100644 app/model/wechat_app.js create mode 100644 app/service/systemMethods/wechat.js create mode 100644 app/service/systems/wechat.js create mode 100644 app/view/wechat_auth_callback.html diff --git a/app/controller/wechatOpen.js b/app/controller/wechatOpen.js new file mode 100644 index 0000000..f6cc871 --- /dev/null +++ b/app/controller/wechatOpen.js @@ -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} 原始请求体字符串。 + */ + 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} + */ + 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} + */ + 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} + */ + 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; diff --git a/app/lib/wechat_open_client.js b/app/lib/wechat_open_client.js new file mode 100644 index 0000000..ef2621f --- /dev/null +++ b/app/lib/wechat_open_client.js @@ -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} 缓存值。 + */ + 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} + */ + 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} + */ + 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} 响应 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} 响应 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} + */ + async saveComponentVerifyTicket(ticket) { + // 微信每 10 分钟推送一次,ticket 有效期 12 小时。 + // 缓存 12 小时:异常未及时收到推送时,继续用上一次可用 ticket 换取 component_access_token(官方建议)。 + await this.cacheSet('ComponentVerifyTicket', ticket, 12 * 3600); + } + + /** + * 获取组件接口调用凭证 component_access_token(缓存优先)。 + * @return {Promise} 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} + */ + async saveAuthorizationCode(authorizerAppid, authorizationCode) { + // 授权码有效期 1 小时 + await this.cacheSet(`App:${authorizerAppid}:authorization_code`, authorizationCode, 3600); + } + + /** + * 使用授权码换取授权方令牌(api_query_auth)。 + * @param {string} authorizationCode 授权码。 + * @return {Promise} 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} { 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} 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} { 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} 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} 微信原始响应(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} 微信原始响应(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} 微信原始响应(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} 微信原始响应(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} 微信原始响应(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} { 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} 微信原始响应(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} 微信原始响应(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} { 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} + */ + 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} + */ + 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} { 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} + */ + async clearAuthState(state) { + await this.cacheDel(`wechat_auth_state:${state}`); + } +} + +module.exports = WechatOpenClient; diff --git a/app/lib/wechat_open_crypt.js b/app/lib/wechat_open_crypt.js new file mode 100644 index 0000000..74869c1 --- /dev/null +++ b/app/lib/wechat_open_crypt.js @@ -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,提取 内容。 + * @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, +}; diff --git a/app/model/user_oauth.js b/app/model/user_oauth.js new file mode 100644 index 0000000..4f9efbf --- /dev/null +++ b/app/model/user_oauth.js @@ -0,0 +1,156 @@ +'use strict'; + +/** + * 用户第三方授权表模型。 + * 保存用户通过第三方厂商(微信等)OAuth 登录后的授权信息与令牌信息。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 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; +}; diff --git a/app/model/wechat_app.js b/app/model/wechat_app.js new file mode 100644 index 0000000..d65ace8 --- /dev/null +++ b/app/model/wechat_app.js @@ -0,0 +1,203 @@ +'use strict'; + +/** + * 微信开放平台授权小程序表模型。 + * 记录仓库(主体)授权的小程序信息与令牌,供业务按小程序维度调用微信接口。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} 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; +}; diff --git a/app/router.js b/app/router.js index 438c229..c099dd4 100644 --- a/app/router.js +++ b/app/router.js @@ -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); diff --git a/app/service/main.js b/app/service/main.js index b2a13bc..089852d 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -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; } } diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index fca447d..1f63bc3 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -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} 统一响应结构;命中时返回 real_name 与 wms_account_id,未命中时返回失败响应(code=404) + * @param {string} data.token 微信工牌码(base64)或 ye4s 登录临时码 + * @return {Promise} 统一响应结构;命中时返回 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} 统一响应结构 + */ + 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; diff --git a/app/service/systemMethods/setting/warehouse.js b/app/service/systemMethods/setting/warehouse.js index 49e6b4d..cc30231 100644 --- a/app/service/systemMethods/setting/warehouse.js +++ b/app/service/systemMethods/setting/warehouse.js @@ -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} 统一响应结果。 + */ + 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; diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index b2afa4f..3808e91 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -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; diff --git a/app/service/systemMethods/wechat.js b/app/service/systemMethods/wechat.js new file mode 100644 index 0000000..738b1ec --- /dev/null +++ b/app/service/systemMethods/wechat.js @@ -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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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} 统一响应结果。 + */ + 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; diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index f6476ce..8b5916d 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -305,6 +305,38 @@ class UserService extends Service { } } + /** + * 发布微信登录事件(唤醒 user.getLoginWechatCode 打开的长轮询)。 + * + * @param {string} clientCode 客户端编码。 + * @param {object} [payload={}] 附加事件数据(如 ye4s_user_id)。 + * @return {Promise} 无返回值。 + */ + 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, diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index 61297f6..2213650 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -403,6 +403,48 @@ class UploadService extends Service { } } + /** + * 服务器端上传 Buffer(小文件直传,如前端裁剪后的头像)。 + * + * @param {Buffer} buffer 文件内容 Buffer。 + * @param {Object} options 上传选项(key 必传或由 generateFileName 生成; + * maxSizeBytes 覆盖大小上限;mimetype 限定后缀)。 + * @return {Promise} 上传结果(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 文件流对象 diff --git a/app/service/systems/wechat.js b/app/service/systems/wechat.js new file mode 100644 index 0000000..12139c9 --- /dev/null +++ b/app/service/systems/wechat.js @@ -0,0 +1,1450 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('node:crypto'); +const WechatOpenClient = require('../../lib/wechat_open_client'); + +const STATE_TTL_SECONDS = 600; + +/** + * 生成登录码:{uuid, form} JSON 的 base64 字符串。 + * uuid 格式为 `{id}_{6位随机数}`(id 为 wms_user_oauth.id),form 固定 wechat; + * 登录码一次性消费,校验时 base64 解码即可取回 uuid/form。 + * @param {number|string} id wms_user_oauth.id(主键)。 + * @return {string} base64 登录码。 + */ +function buildLoginCode(id) { + const payload = { + uuid: `${id}_${String(Math.floor(Math.random() * 1000000)).padStart(6, '0')}`, + form: 'wechat', + }; + return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'); +} + +/** + * 微信开放平台授权业务(systems 层)。 + * 供 systemMethods.wechat 与 wechatOpen controller 复用底层客户端。 + */ +class WechatSystemsService extends Service { + /** + * 生成微信开放平台小程序授权链接(PC 版)。 + * state 为随机串,仓库信息缓存到 Redis(key: wechat_auth_state:{state}), + * 授权回跳 /Authorization 时凭 state 取回仓库并落库绑定。 + * @param {object} data 入参。 + * @param {number} [data.warehouse_id] 仓库ID,缺省取当前登录用户所属仓库。 + * @return {Promise<{auth_url: string, state: string, expires_in: number}>} 授权链接。 + */ + async getAuthUrl(data = {}) { + const { ctx, app } = this; + const config = app.config.wechatOpen || {}; + + const warehouseId = (data && data.warehouse_id) || (ctx.user && ctx.user.store_id) || null; + if (!warehouseId) throw new Error('仓库ID不能为空'); + if (!config.redirect_uri) throw new Error('wechatOpen.redirect_uri 未配置'); + + const client = new WechatOpenClient(ctx); + + // 1. state = 随机串,缓存仓库信息(用于授权回跳时绑定仓库) + const state = `wx${Date.now()}${crypto.randomBytes(6).toString('hex')}`; + await client.saveAuthState(state, warehouseId, STATE_TTL_SECONDS); + + // 2. 获取预授权码 + const preAuthCode = await client.createPreAuthCode(); + + // 3. 组装 PC 端授权链接 + // - auth_type:授权账号类型(1=仅公众号,2=仅小程序,3=公众号+小程序;这里业务只有小程序,用 2)。 + // 注意 auth_type 不是"权限范围",权限范围由 category_id_list / 商家在授权页勾选控制。 + // - category_id_list:指定权限集 id 列表(竖线分隔)。业务所需:18=小程序代码管理(commit/submit_audit/ + // queryauth/get_qrcode 等)、86=体验版二维码;getTemplateList/jscode2session/快速注册不需要商家权限集。 + // 前提:18/86 必须在微信开放平台后台「权限集」中配置并全网发布,否则商家授权页看不到。 + // - 微信 componentloginpage 不支持 state 参数:state 必须拼进 redirect_uri 的 query, + // 授权完成后微信回跳时会保留 redirect_uri 已有参数并追加 auth_code/expires_in, + // 后端凭 state 从缓存取回仓库绑定信息。 + const stateSep = config.redirect_uri.includes('?') ? '&' : '?'; + const redirectUriWithState = `${config.redirect_uri}${stateSep}state=${encodeURIComponent(state)}`; + const authUrl = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage' + + `?component_appid=${encodeURIComponent(config.component_appid)}` + + `&pre_auth_code=${encodeURIComponent(preAuthCode)}` + + `&redirect_uri=${encodeURIComponent(redirectUriWithState)}` + + '&auth_type=2' + + '&category_id_list=18|86'; + + return { auth_url: authUrl, state, expires_in: STATE_TTL_SECONDS }; + } + + /** + * 解析微信应用记录:支持按主键 `app_id` 或按小程序原始 `appid` 定位。 + * + * 为什么需要两种入参: + * - `app_id`(wms_wechat_app.id):PC 端后台等已知业务库的场景; + * - `appid`(wx.getAccountInfoSync().miniProgram.appId):**开放平台第三方平台的模板小程序**场景。 + * 同一份模板代码授权给多个仓库后会生成不同 AppID 的小程序,构建期无法写死, + * 只能由小程序端在**运行时**取真实 AppID 上报,后端反查授权记录。 + * + * 优先级:`app_id` > `appid`(两者都传时以主键为准,保持向后兼容)。 + * + * @param {object} data 入参。 + * @param {number|string} [data.app_id] wms_wechat_app.id。 + * @param {string} [data.appid] 小程序原始 AppID。 + * @return {Promise<{record: object|null, message: string}>} 应用记录;失败时 record 为 null 并给出原因。 + */ + async resolveWechatApp(data = {}) { + const { ctx } = this; + + const appId = Number(data.app_id); + if (Number.isInteger(appId) && appId > 0) { + const record = await ctx.model.WechatApp.findByPk(appId); + if (!record) return { record: null, message: '微信应用不存在' }; + return { record, message: '' }; + } + + const appid = typeof data.appid === 'string' ? data.appid.trim() : ''; + if (appid) { + // appid 在 wms_wechat_app 上有唯一索引 uk_appid;过滤 is_enabled 与 getWechatApp 口径一致 + const record = await ctx.model.WechatApp.findOne({ + where: { appid, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) return { record: null, message: `小程序未授权或已停用:${appid}` }; + return { record, message: '' }; + } + + return { record: null, message: '缺少 app_id / appid 参数' }; + } + + /** + * 小程序登录码登录(免登录):wx.login 的 code 换取 openid/session_key,查/建 wms_user_oauth。 + * + * 参考 auth.login 返回结构;wms_user_oauth 无记录时创建记录(user_id=0 未绑定), + * JWT payload 记录 oauth_id(wms_user_oauth.id,区别于正常登录的用户 id 字段)。 + * + * @param {object} data 入参。 + * @param {string} data.code wx.login 获取的 code。 + * @param {number|string} [data.app_id] wms_wechat_app.id(主键),优先级最高。 + * @param {string} [data.appid] 小程序原始 AppID(如 wx3xxxxx),按 appid 反查应用记录。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 登录结果。 + */ + async loginByCode(data = {}) { + const { ctx, app } = this; + + const code = typeof data.code === 'string' ? data.code.trim() : ''; + if (!code) { + return { success: false, data: null, code: 0, message: '缺少 code 参数' }; + } + + const { record: wechatApp, message } = await this.resolveWechatApp(data); + if (!wechatApp) { + return { success: false, data: null, code: 0, message }; + } + if (Number(wechatApp.is_enabled) !== 1) { + return { success: false, data: null, code: 0, message: '微信应用已停用' }; + } + const appId = wechatApp.id; + + const client = new WechatOpenClient(ctx); + const session = await client.jscode2session(wechatApp.appid, code); + + const nowSec = Math.floor(Date.now() / 1000); + const where = { app_id: appId, provider: 'wechat', openid: session.openid }; + let oauth = await ctx.model.UserOauth.findOne({ where }); + if (oauth) { + await oauth.update({ + unionid: session.unionid || oauth.unionid || null, + session_key: session.session_key || oauth.session_key || null, + login_time: nowSec, + login_count: (Number(oauth.login_count) || 0) + 1, + }); + } else { + oauth = await ctx.model.UserOauth.create({ + user_id: 0, + app_id: appId, + provider: 'wechat', + platform: 'mp', + unionid: session.unionid || null, + openid: session.openid, + session_key: session.session_key || null, + login_time: nowSec, + login_count: 1, + }); + // 用主键 id 生成登录码并回写 + await oauth.update({ login_code: buildLoginCode(oauth.id) }); + } + + // JWT:记录 oauth_id(wms_user_oauth.id),区别于正常登录的用户 id 字段 + const tokenPayload = { + id: Number(oauth.user_id) || 0, + oauth_id: oauth.id, + platform_code: ctx.header.platform || 'miniprogram', + }; + const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, { + expiresIn: app.config.jwt.expiresIn, + }); + + return { + success: true, + data: { + token, + user: { + id: Number(oauth.user_id) || 0, + oauth_id: oauth.id, + openid: oauth.openid, + unionid: oauth.unionid || '', + nickname: oauth.nickname || '', + headimgurl: oauth.headimgurl || '', + login_time: oauth.login_time, + login_count: oauth.login_count, + }, + }, + code: 200, + message: '登录成功', + }; + } + + /** + * 获取当前微信登录用户的登录码(至少微信登录)。 + * 凭 ctx.oauth(微信登录态,JWT oauth_id 解析)定位 wms_user_oauth 记录: + * - 已有 login_code:直接返回; + * - 无 login_code:生成({uuid:`{id}_{6位随机}`,form:'wechat'} 的 base64)并写入后返回。 + * + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getMyLoginCode() { + const { ctx } = this; + const oauth = ctx.oauth; + if (!oauth || !oauth.id) { + return { success: false, data: null, code: 0, message: '请使用微信登录' }; + } + + if (oauth.login_code) { + return { success: true, data: { login_code: oauth.login_code, oauth_id: oauth.id }, code: 200, message: '获取成功' }; + } + + const loginCode = buildLoginCode(oauth.id); + await ctx.model.UserOauth.update( + { login_code: loginCode }, + { where: { id: oauth.id } } + ); + return { success: true, data: { login_code: loginCode, oauth_id: oauth.id }, code: 200, message: '获取成功' }; + } + + /** + * 绑定用户(微信登录态中间层接口):传入用户名密码,一致则绑定 wms_user_oauth.user_id + * 并签发绑定后的新 token(id=账号ID,oauth_id 保留)。 + * + * 已绑定(user_id>0)时仅允许本人幂等调用(凭据一致返回已绑定),不允许换绑。 + * + * @param {object} data 入参。 + * @param {string} data.username 用户名/手机号/邮箱。 + * @param {string} data.password 密码。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 绑定结果。 + */ + async bindUser(data = {}) { + const { ctx, app } = this; + + const oauthId = Number(ctx.oauthId || (ctx.oauth && ctx.oauth.id) || 0); + if (!Number.isInteger(oauthId) || oauthId <= 0) { + return { success: false, data: null, code: 401, message: '微信登录态不存在' }; + } + + const username = typeof data.username === 'string' ? data.username.trim() : ''; + const password = typeof data.password === 'string' ? data.password : ''; + if (!username || !password) { + return { success: false, data: null, code: 0, message: '用户名和密码不能为空' }; + } + + const record = await ctx.model.UserOauth.findByPk(oauthId); + if (!record) { + return { success: false, data: null, code: 0, message: '微信登录态不存在' }; + } + + const authService = ctx.service.systems.auth.user; + + // 已绑定:只允许本人幂等调用(凭据一致返回已绑定),不允许换绑 + if (Number(record.user_id) > 0) { + const bindAccount = await ctx.model.Account.findByPk(record.user_id); + const isOwner = (bindAccount && String(bindAccount.username || '').trim() === username) + ? await bindAccount.verifyPassword(password) + : false; + if (isOwner) { + return this.buildBindResult(record, bindAccount, ctx, app, '已绑定'); + } + return { success: false, data: null, code: 0, message: '该微信已绑定其他账号,无法更换绑定' }; + } + + // 校验账号密码(复用登录的查找与状态校验) + const account = await authService.findUserByIdentifier(username, 'auto'); + if (!account) { + return { success: false, data: null, code: 0, message: '用户名或密码错误' }; + } + try { + authService.checkUserStatus(account); + } catch (statusError) { + return { success: false, data: null, code: 0, message: statusError.message || '账号状态异常' }; + } + const isPasswordValid = await account.verifyPassword(password); + if (!isPasswordValid) { + return { success: false, data: null, code: 0, message: '用户名或密码错误' }; + } + + // 绑定并签发新 token(token 中 id 指向绑定账号) + await record.update({ + user_id: account.id, + login_time: Math.floor(Date.now() / 1000), + }); + + return this.buildBindResult(record, account, ctx, app, '绑定成功'); + } + + /** + * 组装绑定结果并签发绑定后的 JWT。 + * + * @param {Object} record wms_user_oauth 记录实例。 + * @param {Object} account wms_account 记录实例。 + * @param {Object} ctx Egg 上下文。 + * @param {Object} app Egg 应用。 + * @param {string} message 提示文案。 + * @return {Object} 统一绑定结果。 + */ + buildBindResult(record, account, ctx, app, message) { + const tokenPayload = { + id: account.id, + oauth_id: record.id, + platform_code: ctx.header.platform || 'miniprogram', + }; + const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, { + expiresIn: app.config.jwt.expiresIn, + }); + + return { + success: true, + data: { + token, + user: { + id: account.id, + username: account.username || '', + real_name: account.real_name || '', + phone: account.phone || '', + oauth_id: record.id, + openid: record.openid, + unionid: record.unionid || '', + nickname: record.nickname || '', + headimgurl: record.headimgurl || '', + }, + }, + code: 200, + message, + }; + } + + /** + * 确认登录码(需登录,PC/Web 端已登录用户),复用旧 user.getLoginWechatCode 生成的码。 + * + * 使用当前鉴权账号反查 ye4s_user(wms_account_id=当前账号),将 ye4s_user_id 写入旧登录码 + * 缓存(user:wechat:login:code:{code} 与 user:wechat:login:client:{client_code} 双写), + * 小程序端按旧链路 user.getLoginWechatCode 轮询到后直接返回登录成功。 + * + * @param {object} data 入参。 + * @param {string} data.code 旧登录码(6 位字母+数字)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async pushLoginCode(data = {}) { + const { ctx, app } = this; + + const accountId = Number(ctx.userId || (ctx.user && ctx.user.id)); + if (!Number.isInteger(accountId) || accountId <= 0) { + return { success: false, data: null, code: 401, message: '未登录' }; + } + + const authService = ctx.service.systems.auth.user; + const code = authService.parseWechatBindCode(data.code); + if (!code) { + return { success: false, data: null, code: 0, message: '登录码格式不正确' }; + } + + // 读旧登录码缓存(user:wechat:login:code:{code}),从中取 client_code + const cachedState = await app.getCacheAsync(authService.getWechatLoginCodeCacheKey(code)); + const clientCode = authService.parseWechatBindCode(cachedState && cachedState.client_code); + if (!cachedState || !clientCode) { + return { success: false, data: null, code: 0, message: '登录码不存在或已过期' }; + } + + // 反查当前账号的 ye4s 绑定(旧链路凭 ye4s_user_id 完成登录) + const ye4sBinding = await authService.findYe4sBindingByAccountId(accountId); + const ye4sUserId = Number(ye4sBinding && ye4sBinding.id); + if (!Number.isInteger(ye4sUserId) || ye4sUserId <= 0) { + return { success: false, data: null, code: 0, message: '当前账号未绑定微信登录账号,无法确认' }; + } + + // 双写:旧轮询方读 client key 时即可直接登录 + const nextState = { + ...cachedState, + ye4s_user_id: ye4sUserId, + confirmed_by: accountId, + confirmed_at: Math.floor(Date.now() / 1000), + }; + const ttl = authService.getRemainingSecondsByExpiresAt(cachedState.expires_at, 60); + await Promise.all([ + authService.setWechatLoginClientCache(clientCode, nextState, ttl), + authService.setWechatLoginCodeCache(code, nextState, ttl), + ]); + + // 发布登录事件,唤醒已打开的长轮询请求(否则要等 60s 超时后才会重读缓存) + await authService.publishWechatLoginEvent(clientCode, { ye4s_user_id: ye4sUserId }); + + return { success: true, data: { code, client_code: clientCode, status: 'success' }, code: 200, message: '登录已确认' }; + } + + /** + * 查询当前仓库小程序的认证状态(需登录,权限集 18)。 + * + * 判定顺序: + * 1) 本地 wms_wechat_app.verify_type_id >= 0(已认证)→ 直接返回本地认证信息,不调微信; + * 2) 未认证(null/-1)→ taskid(入参优先,其次库中 auth_task_id)调微信 wxa/sec/queryauth 查进度; + * 3) 未认证且无 taskid → 返回「尚未认证且无认证任务」状态(code 200,is_verified=false)。 + * 查询成功回写 auth_task_id/auth_task_status/auth_apply_status;apply_status=4(认证通过)时回写 verify_type_id=0。 + * + * @param {object} data 入参。 + * @param {string} [data.taskid] 认证任务 id(发起认证接口 wxa/sec/wxaapi/wxaauth 返回;缺省用库中 auth_task_id)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 认证状态结果。 + */ + async queryauth(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + const VERIFY_TYPE_TEXT = { + [-1]: '未认证', + 0: '微信认证', + 1: '新浪微博认证', + 3: '资质通过未名称认证', + 4: '资质通过+微博认证', + }; + + // 1) 已认证:直接返回本地认证信息(不再调微信查进度) + const verifyTypeId = record.verify_type_id === null || record.verify_type_id === undefined + ? null + : Number(record.verify_type_id); + if (verifyTypeId !== null && verifyTypeId >= 0) { + return { + success: true, + data: { + is_verified: true, + appid: record.appid, + verify_type_id: verifyTypeId, + verify_type_text: VERIFY_TYPE_TEXT[verifyTypeId] || '已认证', + principal_name: record.principal_name, + signature: record.signature, + service_type_id: record.service_type_id, + account_status: record.account_status, + }, + code: 200, + message: '小程序已认证', + }; + } + + // 2) 未认证:taskid 入参优先,其次库中 auth_task_id + let taskid = typeof data.taskid === 'string' ? data.taskid.trim() : ''; + if (!taskid && record.auth_task_id) { + taskid = String(record.auth_task_id).trim(); + } + if (!taskid) { + return { + success: true, + data: { is_verified: false, appid: record.appid, taskid: null, task_status: null, apply_status: null }, + code: 200, + message: '尚未认证,且无认证任务', + }; + } + + // 3) 查认证进度(微信 wxa/sec/queryauth) + const client = new WechatOpenClient(ctx); + const result = await client.queryMiniProgramAuth(record.appid, record.authorizer_refresh_token, taskid); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `查询认证状态失败: ${errmsg}` }; + } + + const TASK_STATUS_TEXT = { + 0: '初始状态', 1: '任务超时(24小时内有效)', 2: '用户授权拒绝', 3: '用户授权同意', + 4: '发起人脸流程', 5: '人脸认证失败', 6: '人脸认证ok', 7: '已提交手机号下发验证码', + 8: '手机验证失败', 9: '手机验证成功', 11: '创建认证审核单失败', 12: '创建认证审核单成功', + 14: '验证失败', 15: '等待支付', + }; + const APPLY_STATUS_TEXT = { + 0: '审核单不存在', 1: '待支付', 2: '审核中', 3: '打回重填', 4: '认证通过', 5: '认证最终失败', + }; + + const applyStatus = result.apply_status !== undefined ? Number(result.apply_status) : null; + + // 认证任务ID与状态落库(发起认证接口返回的 taskid 亦通过本接口回写); + // 认证通过(apply_status=4)时回写 verify_type_id=0(微信认证),后续 queryauth 直接返回认证信息 + await record.update({ + auth_task_id: taskid, + auth_task_status: result.task_status !== undefined ? Number(result.task_status) : null, + auth_apply_status: applyStatus, + ...(applyStatus === 4 ? { verify_type_id: 0 } : {}), + }); + + return { + success: true, + data: { + ...result, + appid: record.appid, + is_verified: applyStatus === 4, + task_status_text: TASK_STATUS_TEXT[Number(result.task_status)] || '未知', + apply_status_text: applyStatus !== null ? (APPLY_STATUS_TEXT[applyStatus] || '未知') : '', + }, + code: 200, + message: applyStatus === 4 ? '认证通过' : '查询成功', + }; + } + + /** + * 发起小程序认证(需登录,wxa/sec/wxaapi/wxaauth,代商家调用需权限集 18)。 + * + * 后端分步:图片字段传 COS 文件 URL(http/https),后端下载文件 → wxa/sec/wxaapi/uploadmedia + * 换 media_id → 替换请求体 → 调 wxaauth 一步提交。 + * 成功后回写 wms_wechat_app.auth_task_id/auth_apply_status,返回 taskid/auth_url。 + * + * @param {object} data 入参(微信 wxaauth 请求体字段白名单: + * contact_type/contact_name 必填;图片字段 contact_cert_photo/business_license_copy/ + * legal_persona_idcard_copy/legal_persona_media/pic_list(项 pic_url)/qualification_list(项 + * licence_list|certificate_list 的 value)/statement_list(项 value) 支持传 COS URL, + * 后端自动换 media_id;其余字段透传)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async wxaauth(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + // 已认证不允许重复发起 + const verifyTypeId = record.verify_type_id === null || record.verify_type_id === undefined + ? null + : Number(record.verify_type_id); + if (verifyTypeId !== null && verifyTypeId >= 0) { + return { success: false, data: null, code: 0, message: '小程序已认证,无需重复发起' }; + } + + // 判断授权权限:需包含代码管理权限集 18 + if (!this.hasFuncScope(record.func_info, 18)) { + return { success: false, data: null, code: 0, message: '小程序未授权代码管理权限(权限集 18),请重新授权' }; + } + + // 白名单透传微信请求体字段 + const ALLOWED_KEYS = [ + 'contact_type', 'contact_name', 'contact_idcard_number', 'contact_mobile', + 'contact_cert_photo', 'contact_nationality', 'contact_address', 'contact_email', + 'business_license_copy', 'business_license_number', 'business_license_address', + 'business_license_expiration_date', 'legal_persona_media', 'legal_persona_idcard_copy', + 'legal_persona_name', 'legal_persona_idcard_number', 'legal_persona_address', + 'legal_persona_idcard_expiration_date', 'business_license_type', 'apply_type', + 'extra_wxa_secure_info', 'nickname', 'pic_list', 'qualification_list', + 'qualification_extra', 'license_list', 'statement_list', 'store_name', + 'store_main_industry', 'store_scale', 'store_floor', 'store_address', 'open_type', 'pay_type', + ]; + const body = {}; + for (const key of ALLOWED_KEYS) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + body[key] = data[key]; + } + } + if (body.contact_type === undefined || body.contact_name === undefined) { + return { success: false, data: null, code: 0, message: 'contact_type/contact_name 为必填' }; + } + + const client = new WechatOpenClient(ctx); + + // 分步①:图片字段传 COS URL 时,后端下载并上传微信换 media_id + try { + await this.resolveBodyMedia(body, client, record); + } catch (e) { + return { success: false, data: null, code: 0, message: e.message || '上传认证材料失败' }; + } + + // 分步②:发起认证 + const result = await client.wxaauth(record.appid, record.authorizer_refresh_token, body); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `发起认证失败: ${errmsg}` }; + } + + // 回写认证任务 ID 与状态(taskid 供 queryauth 查询进度) + await record.update({ + auth_task_id: typeof result.taskid === 'string' ? result.taskid : String(result.taskid || ''), + auth_task_status: null, + auth_apply_status: result.apply_status !== undefined ? Number(result.apply_status) : null, + }); + + return { + success: true, + data: { appid: record.appid, ...result }, + code: 200, + message: '认证已发起,请前往微信完成认证', + }; + } + + /** + * 将请求体中的图片字段从 COS URL 替换为微信 media_id(http/https 开头的值视为 COS URL, + * 其余值视为已是 media_id 原样保留)。 + * + * @param {object} body wxaauth 请求体(就地修改)。 + * @param {WechatOpenClient} client 微信客户端。 + * @param {object} record wms_wechat_app 记录。 + * @return {Promise} + */ + async resolveBodyMedia(body, client, record) { + // 顶层字符串图片字段 + const IMAGE_STRING_FIELDS = [ 'contact_cert_photo', 'business_license_copy', 'legal_persona_idcard_copy', 'legal_persona_media' ]; + for (const key of IMAGE_STRING_FIELDS) { + if (typeof body[key] === 'string' && body[key]) { + body[key] = await this.resolveMediaValue(body[key], client, record); + } + } + + // pic_list:[{ pic_url }] + if (Array.isArray(body.pic_list)) { + for (const item of body.pic_list) { + if (item && typeof item === 'object' && typeof item.pic_url === 'string') { + item.pic_url = await this.resolveMediaValue(item.pic_url, client, record); + } + } + } + + // qualification_list:[{ licence_list: [{ value }], certificate_list: [{ value }] }] + if (Array.isArray(body.qualification_list)) { + for (const q of body.qualification_list) { + if (q && typeof q === 'object') { + for (const subKey of [ 'licence_list', 'certificate_list' ]) { + if (Array.isArray(q[subKey])) { + for (const item of q[subKey]) { + if (item && typeof item === 'object' && typeof item.value === 'string') { + item.value = await this.resolveMediaValue(item.value, client, record); + } + } + } + } + } + } + } + + // statement_list:[{ value }] + if (Array.isArray(body.statement_list)) { + for (const item of body.statement_list) { + if (item && typeof item === 'object' && typeof item.value === 'string') { + item.value = await this.resolveMediaValue(item.value, client, record); + } + } + } + } + + /** + * 单个图片字段解析:http/https 开头(COS URL)→ 下载 → uploadmedia 换 media_id; + * 其他值视为已传 media_id 原样返回。 + * + * @param {string} value 字段值。 + * @param {WechatOpenClient} client 微信客户端。 + * @param {object} record wms_wechat_app 记录。 + * @return {Promise} media_id。 + */ + async resolveMediaValue(value, client, record) { + const trimmed = String(value).trim(); + if (!/^https?:\/\//i.test(trimmed)) { + return value; + } + + const buffer = await this.downloadFromUrl(trimmed); + const filename = this.resolveMediaFilename(trimmed); + const result = await client.uploadAuthMedia(record.appid, record.authorizer_refresh_token, buffer, filename); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + throw new Error(`上传认证材料失败(${filename}): ${errmsg}`); + } + if (!result.media_id) { + throw new Error(`上传认证材料失败(${filename}): 微信未返回 media_id`); + } + return result.media_id; + } + + /** + * 下载 COS 文件 URL 内容为 Buffer。 + * + * @param {string} url 文件 URL。 + * @return {Promise} 文件内容。 + */ + async downloadFromUrl(url) { + const response = await this.ctx.curl(url, { + method: 'GET', + timeout: 30000, + }); + if (!response || !response.data || !Buffer.isBuffer(response.data) || response.data.length === 0) { + throw new Error(`下载文件失败: ${url}`); + } + return response.data; + } + + /** + * 从 URL 提取图片文件名(path 扩展名限定 jpg/jpeg/png,默认 image.jpg)。 + * + * @param {string} url 文件 URL。 + * @return {string} 文件名。 + */ + resolveMediaFilename(url) { + try { + const pathname = decodeURIComponent(url.split('?')[0].split('#')[0]); + const match = pathname.match(/\/([^/]+\.(jpe?g|png))$/i); + if (match) return match[1]; + } catch (e) { + // ignore + } + return 'image.jpg'; + } + + /** + * 快速注册企业小程序(需登录,fastregisterweapp?action=create)。 + * + * 注册任务创建后法人微信会收到模板消息做人脸核身;审核结果通过 + * notify_third_fasteregister 事件推送到授权事件接收 URL。 + * + * @param {object} data 入参。 + * @param {string} data.name 企业名(与工商登记一致;无主体名称个体工商户填「个体户+法人姓名」)。 + * @param {string} data.code 企业代码。 + * @param {number} data.code_type 企业代码类型:1 统一社会信用代码(18位)、2 组织机构代码(9位)、3 营业执照注册号(15位)。 + * @param {string} data.legal_persona_wechat 法人微信号。 + * @param {string} data.legal_persona_name 法人姓名。 + * @param {string} [data.component_phone] 第三方联系电话。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async registerMiniprogram(data = {}) { + const { ctx } = this; + + const name = typeof data.name === 'string' ? data.name.trim() : ''; + const code = typeof data.code === 'string' ? data.code.trim() : ''; + const codeType = Number(data.code_type); + const legalPersonaWechat = typeof data.legal_persona_wechat === 'string' ? data.legal_persona_wechat.trim() : ''; + const legalPersonaName = typeof data.legal_persona_name === 'string' ? data.legal_persona_name.trim() : ''; + const componentPhone = typeof data.component_phone === 'string' ? data.component_phone.trim() : ''; + + if (!name || !code || !legalPersonaWechat || !legalPersonaName) { + return { success: false, data: null, code: 0, message: '缺少参数: name/code/legal_persona_wechat/legal_persona_name 均为必填' }; + } + if (![ 1, 2, 3 ].includes(codeType)) { + return { success: false, data: null, code: 0, message: 'code_type 必须为 1(统一社会信用代码)/2(组织机构代码)/3(营业执照注册号)' }; + } + + const client = new WechatOpenClient(ctx); + const result = await client.fastRegisterWeapp('create', { + name, + code, + code_type: codeType, + legal_persona_wechat: legalPersonaWechat, + legal_persona_name: legalPersonaName, + component_phone: componentPhone, + }); + + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `注册小程序失败: ${errmsg}` }; + } + + return { + success: true, + data: { ...result }, + code: 200, + message: '注册任务已创建,法人确认与审核结果将通过 notify_third_fasteregister 事件推送', + }; + } + + /** + * 更新微信账号资料(微信登录态中间层,仅未绑定真实用户的微信账号)。 + * + * 前端(小程序)在未绑定账号时更新自己的昵称/头像(nickname/headimgurl), + * 已绑定真实用户的账号不支持修改。 + * + * @param {object} data 入参。 + * @param {string} [data.nickname] 昵称(≤255 字符)。 + * @param {string} [data.headimgurl] 头像 URL(≤500 字符)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async updateInfo(data = {}) { + const { ctx } = this; + + const oauthId = Number(ctx.oauthId || (ctx.oauth && ctx.oauth.id) || 0); + if (!Number.isInteger(oauthId) || oauthId <= 0) { + return { success: false, data: null, code: 401, message: '微信登录态不存在' }; + } + + const record = await ctx.model.UserOauth.findByPk(oauthId); + if (!record) { + return { success: false, data: null, code: 0, message: '微信登录态不存在' }; + } + if (Number(record.user_id) > 0) { + return { success: false, data: null, code: 0, message: '账号已绑定,不支持修改微信资料' }; + } + + const hasNickname = typeof data.nickname === 'string'; + const hasHeadimgurl = typeof data.headimgurl === 'string'; + if (!hasNickname && !hasHeadimgurl) { + return { success: false, data: null, code: 0, message: '缺少需要更新的字段: nickname/headimgurl' }; + } + + const patch = {}; + if (hasNickname) { + const nickname = data.nickname.trim(); + if (nickname.length > 255) { + return { success: false, data: null, code: 0, message: 'nickname 长度不能超过 255 字符' }; + } + patch.nickname = nickname; + } + if (hasHeadimgurl) { + const headimgurl = data.headimgurl.trim(); + if (headimgurl.length > 500) { + return { success: false, data: null, code: 0, message: 'headimgurl 长度不能超过 500 字符' }; + } + patch.headimgurl = headimgurl; + } + + await record.update(patch); + + return { + success: true, + data: { + oauth_id: record.id, + nickname: record.nickname || '', + headimgurl: record.headimgurl || '', + }, + code: 200, + message: '更新成功', + }; + } + + /** + * 生成头像上传 COS key(不依赖仓库上下文,未绑定微信账号也可用)。 + * + * @return {string} COS key。 + */ + buildHeadimgKey() { + const now = new Date(); + const pad = value => String(value).padStart(2, '0'); + const timestamp = [ + now.getFullYear(), + pad(now.getMonth() + 1), + pad(now.getDate()), + pad(now.getHours()), + pad(now.getMinutes()), + pad(now.getSeconds()), + ].join(''); + const random = Math.random().toString(36).substring(2, 10); + return `headimg/wechat/${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}/${timestamp}${random}.png`; + } + + /** + * 上传微信账号头像(微信登录态中间层,至少微信登录即可,未绑定也可)。 + * + * 前端裁剪后以 base64 上传(data URL 或裸 base64),限制:仅 PNG、大小小于 500K; + * 上传成功后回写 wms_user_oauth.headimgurl 并返回 URL。 + * + * @param {object} data 入参。 + * @param {string} data.image 裁剪后的 PNG 图片 base64(支持 data:image/png;base64, 前缀)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async uploadHeadimg(data = {}) { + const { ctx } = this; + + const oauthId = Number(ctx.oauthId || (ctx.oauth && ctx.oauth.id) || 0); + if (!Number.isInteger(oauthId) || oauthId <= 0) { + return { success: false, data: null, code: 401, message: '微信登录态不存在' }; + } + + const raw = typeof data.image === 'string' ? data.image.trim() : ''; + if (!raw) { + return { success: false, data: null, code: 0, message: '缺少 image 参数' }; + } + + let base64 = raw; + if (raw.startsWith('data:')) { + const commaIndex = raw.indexOf(','); + if (commaIndex === -1) { + return { success: false, data: null, code: 0, message: '图片数据格式不正确' }; + } + base64 = raw.slice(commaIndex + 1); + } + + let buffer = null; + try { + buffer = Buffer.from(base64, 'base64'); + } catch (e) { + buffer = null; + } + if (!buffer || buffer.length === 0) { + return { success: false, data: null, code: 0, message: '图片数据解析失败' }; + } + + // 大小限制:小于 500K + if (buffer.length >= 500 * 1024) { + return { success: false, data: null, code: 0, message: '图片大小不能超过 500K' }; + } + + // 仅 PNG:校验文件头魔数 + const PNG_MAGIC = Buffer.from([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a ]); + if (buffer.length < PNG_MAGIC.length || !buffer.subarray(0, PNG_MAGIC.length).equals(PNG_MAGIC)) { + return { success: false, data: null, code: 0, message: '仅支持 PNG 图片,请裁剪后重新上传' }; + } + + const uploadService = ctx.service.systems.upload; + if (!uploadService || typeof uploadService.uploadBuffer !== 'function') { + return { success: false, data: null, code: 0, message: '上传服务不可用' }; + } + + const uploadResult = await uploadService.uploadBuffer(buffer, { + filename: 'headimg.png', + mimeType: 'image/png', + category: 'image', + key: this.buildHeadimgKey(), + maxSizeBytes: 500 * 1024, + }); + + // 回写 wms_user_oauth.headimgurl(记录不存在也不阻断返回) + const record = await ctx.model.UserOauth.findByPk(oauthId); + if (record) { + await record.update({ headimgurl: uploadResult.url }); + } + + return { + success: true, + data: { + oauth_id: oauthId, + url: uploadResult.url, + headimgurl: uploadResult.url, + }, + code: 200, + message: '上传成功', + }; + } + + /** + * 获取小程序模板库列表(需登录),只拉取普通模板(template_type=0),Redis 缓存 24h。 + * + * 有缓存直接返回缓存列表;无缓存时调微信 gettemplatelist 拉取并写入缓存。 + * + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getTemplateList() { + const { ctx } = this; + + const client = new WechatOpenClient(ctx); + const CACHE_KEY = 'wechat:template:list:normal'; + const CACHE_TTL_SECONDS = 24 * 3600; + + const cached = await client.cacheGet(CACHE_KEY); + if (cached) { + try { + const list = JSON.parse(cached); + if (Array.isArray(list)) { + return { success: true, data: { list, from_cache: true }, code: 200, message: '获取成功' }; + } + } catch (e) { + // 缓存损坏,忽略并重新拉取 + } + } + + const result = await client.getTemplateList(0); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `获取模板列表失败: ${errmsg}` }; + } + + const list = Array.isArray(result.template_list) ? result.template_list : []; + await client.cacheSet(CACHE_KEY, JSON.stringify(list), CACHE_TTL_SECONDS); + + return { success: true, data: { list, from_cache: false }, code: 200, message: '获取成功' }; + } + + /** + * 判断授权权限集合中是否包含指定权限集 ID。 + * + * @param {string|Array} funcInfo wms_wechat_app.func_info(JSON 字符串或数组)。 + * @param {number} scopeId 权限集 ID。 + * @return {boolean} 包含返回 true。 + */ + hasFuncScope(funcInfo, scopeId) { + try { + const list = typeof funcInfo === 'string' ? JSON.parse(funcInfo || '[]') : (Array.isArray(funcInfo) ? funcInfo : []); + return list.some(item => Number(item && item.funcscope_category && item.funcscope_category.id) === scopeId); + } catch (e) { + return false; + } + } + + /** + * 将 api_get_authorizer_info 返回转为 wms_wechat_app 落库补丁。 + * + * @param {object} authorizerInfo authorizer_info。 + * @param {object} authorizationInfo authorization_info(可选)。 + * @return {object} 落库字段补丁。 + */ + buildAuthorizerPatch(authorizerInfo, authorizationInfo = {}) { + const info = authorizerInfo || {}; + const patch = {}; + if (info.nick_name) patch.nickname = info.nick_name; + if (info.user_name) patch.user_name = info.user_name; + if (info.head_img) patch.head_img = info.head_img; + if (info.principal_name !== undefined) patch.principal_name = info.principal_name; + if (info.signature !== undefined) patch.signature = info.signature; + if (info.alias !== undefined) patch.alias = info.alias; + if (info.qrcode_url !== undefined) patch.qrcode_url = info.qrcode_url; + if (info.service_type_info) patch.service_type_id = Number(info.service_type_info.id); + if (info.verify_type_info) patch.verify_type_id = Number(info.verify_type_info.id); + if (info.account_status !== undefined) patch.account_status = Number(info.account_status); + if (info.register_type !== undefined) patch.register_type = Number(info.register_type); + if (info.business_info) patch.business_info = JSON.stringify(info.business_info); + if (info.MiniProgramInfo) patch.mini_program_info = JSON.stringify(info.MiniProgramInfo); + if (authorizationInfo && Array.isArray(authorizationInfo.func_info)) { + patch.func_info = JSON.stringify(authorizationInfo.func_info); + } + if (authorizationInfo && authorizationInfo.authorizer_refresh_token) { + patch.authorizer_refresh_token = authorizationInfo.authorizer_refresh_token; + } + return patch; + } + + /** + * 获取并同步当前仓库小程序的基础信息(需登录,api_get_authorizer_info)。 + * + * 调微信拉取授权账号详情(authorizer_info + authorization_info),将基础信息/ + * 认证类型/权限集等落库 wms_wechat_app 后返回完整数据。 + * + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getAuthorizerInfo() { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + const client = new WechatOpenClient(ctx); + const detail = await client.getAuthorizerDetail(record.appid); + if (!detail || (!detail.authorizer_info && !detail.authorization_info)) { + return { success: false, data: detail || null, code: 0, message: '获取授权账号详情失败' }; + } + + const patch = this.buildAuthorizerPatch(detail.authorizer_info, detail.authorization_info || {}); + if (Object.keys(patch).length > 0) { + await record.update(patch); + } + + return { + success: true, + data: { + appid: record.appid, + authorizer_info: detail.authorizer_info || null, + authorization_info: detail.authorization_info || null, + }, + code: 200, + message: '获取成功', + }; + } + + /** + * 上传代码并生成体验版(需登录,wxa/commit,代商家调用需权限集 18)。 + * + * 流程:取当前仓库启用小程序 → 校验入参 → 校验授权权限集 18 → 从模板库取模板 + * (校验存在并取模板的 user_version/user_desc 作为版本号与代码描述,不需要外部传) + * → ext_json 由后端默认生成({ extEnable: true, extAppid: 小程序appid },前端不传) + * → 调微信 commit → 成功后回写 wms_wechat_app.template_id/user_version。 + * + * @param {object} data 入参。 + * @param {number|string} data.template_id 代码模板 ID(getTemplateList 获取)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async commit(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + const templateId = Number(data.template_id); + if (!Number.isInteger(templateId) || templateId <= 0) { + return { success: false, data: null, code: 0, message: 'template_id 必须为正整数' }; + } + + // 判断授权权限:需包含代码管理权限集 18 + if (!this.hasFuncScope(record.func_info, 18)) { + return { success: false, data: null, code: 0, message: '小程序未授权代码管理权限(权限集 18),请重新授权' }; + } + + const client = new WechatOpenClient(ctx); + + // 从模板库取模板:校验存在,并直接取模板的 user_version/user_desc 作为上传版本号与代码描述(不需要外部传) + const templateResult = await client.getTemplateList(0); + if (!templateResult || Number(templateResult.errcode) !== 0) { + const errmsg = templateResult && templateResult.errmsg ? templateResult.errmsg : (templateResult ? JSON.stringify(templateResult) : '无响应'); + return { success: false, data: templateResult || null, code: 0, message: `获取模板列表失败: ${errmsg}` }; + } + + const list = Array.isArray(templateResult.template_list) ? templateResult.template_list : []; + const template = list.find(item => Number(item.template_id) === templateId); + if (!template) { + return { success: false, data: null, code: 0, message: `模板不存在: template_id=${templateId}` }; + } + + const userVersion = typeof template.user_version === 'string' ? template.user_version.trim() : ''; + if (!userVersion || userVersion.length > 64) { + return { success: false, data: null, code: 0, message: '模板缺少合法版本号(user_version 必填且长度不能超过 64 字符),请先在模板库设置版本号' }; + } + + const userDesc = typeof template.user_desc === 'string' ? template.user_desc.trim() : ''; + if (!userDesc) { + return { success: false, data: null, code: 0, message: '模板缺少代码描述(user_desc),请先在模板库设置代码描述' }; + } + + // ext_json 由后端默认生成:只开启 extEnable 与 extAppid,前端不传 + const extJson = JSON.stringify({ extEnable: true, extAppid: record.appid }); + + const result = await client.commitTemplate(record.appid, record.authorizer_refresh_token, { + template_id: templateId, + ext_json: extJson, + user_version: userVersion, + user_desc: userDesc, + }); + + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `上传代码失败: ${errmsg}` }; + } + + // 上传成功,记录模板 id 与版本号 + await record.update({ template_id: templateId, user_version: userVersion }); + + return { + success: true, + data: { appid: record.appid, template_id: templateId, user_version: userVersion, user_desc: userDesc, ext_json: extJson, ...result }, + code: 200, + message: '上传成功,已生成体验版', + }; + } + + /** + * 提交代码审核(需登录,wxa/submit_audit,代商家调用需权限集 18)。 + * + * 仅当前无审核中的版本(audit_status != 1)时允许提交;成功后记录 + * audit_status=1(审核中)与 audit_id(微信审核单 ID)。 + * + * @param {object} data 入参(微信 submit_audit 请求体字段,均为可选: + * item_list/feedback_info/feedback_stuff/preview_info/version_desc/ + * privacy_api_not_use/order_info/ugc_declare)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async submitAudit(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + // 判断授权权限:需包含代码管理权限集 18 + if (!this.hasFuncScope(record.func_info, 18)) { + return { success: false, data: null, code: 0, message: '小程序未授权代码管理权限(权限集 18),请重新授权' }; + } + + // 仅未审核(audit_status != 1)时允许提交 + if (Number(record.audit_status) === 1) { + return { success: false, data: null, code: 0, message: '已有审核中的版本,请等待审核结果' }; + } + + // 白名单透传微信请求体字段 + const ALLOWED_KEYS = [ 'item_list', 'feedback_info', 'feedback_stuff', 'preview_info', 'version_desc', 'privacy_api_not_use', 'order_info', 'ugc_declare' ]; + const body = {}; + for (const key of ALLOWED_KEYS) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + body[key] = data[key]; + } + } + + const client = new WechatOpenClient(ctx); + const result = await client.submitAudit(record.appid, record.authorizer_refresh_token, body); + + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `提交代码审核失败: ${errmsg}` }; + } + + const auditId = Number(result.auditid); + await record.update({ + audit_status: 1, + audit_id: Number.isFinite(auditId) ? auditId : null, + audit_reason: '', + }); + + return { + success: true, + data: { appid: record.appid, auditid: result.auditid }, + code: 200, + message: '提交审核成功', + }; + } + + /** + * 生成体验版二维码 COS key。 + * + * @param {number} warehouseId 仓库 ID。 + * @return {string} COS key。 + */ + buildTrialQrCodeKey(warehouseId) { + const now = new Date(); + const pad = value => String(value).padStart(2, '0'); + const timestamp = [ + now.getFullYear(), + pad(now.getMonth() + 1), + pad(now.getDate()), + pad(now.getHours()), + pad(now.getMinutes()), + pad(now.getSeconds()), + ].join(''); + const random = Math.random().toString(36).substring(2, 10); + return `qrcode/wechat/${warehouseId}/${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}/${timestamp}${random}.jpg`; + } + + /** + * 获取体验版二维码(需登录,wxa/get_qrcode,代商家调用需权限集 18 或 86)。 + * + * 微信返回的二维码图片(jpeg)转存 COS,返回 URL。 + * + * @param {object} data 入参。 + * @param {string} [data.path] 扫码后进入的页面路径(可选,如 page/index?action=1)。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async getTrialQRCode(data = {}) { + const { ctx } = this; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + const record = await ctx.model.WechatApp.findOne({ + where: { warehouse_id: warehouseId, is_enabled: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!record) { + return { success: false, data: null, code: 0, message: '当前仓库未授权小程序' }; + } + + // 判断授权权限:需包含权限集 18(代码管理)或 86(体验版二维码) + if (!this.hasFuncScope(record.func_info, 18) && !this.hasFuncScope(record.func_info, 86)) { + return { success: false, data: null, code: 0, message: '小程序未授权相关权限(权限集 18/86),请重新授权' }; + } + + const path = typeof data.path === 'string' ? data.path.trim() : ''; + + const client = new WechatOpenClient(ctx); + const result = await client.getTrialQRCode(record.appid, record.authorizer_refresh_token, path); + if (!result || Number(result.errcode) !== 0) { + const errmsg = result && result.errmsg ? result.errmsg : (result ? JSON.stringify(result) : '无响应'); + return { success: false, data: result || null, code: 0, message: `获取体验版二维码失败: ${errmsg}` }; + } + + const uploadService = ctx.service.systems.upload; + if (!uploadService || typeof uploadService.uploadBuffer !== 'function') { + return { success: false, data: null, code: 0, message: '上传服务不可用' }; + } + + const uploadResult = await uploadService.uploadBuffer(result.buffer, { + filename: 'QRCode.jpg', + mimeType: 'jpg', + category: 'image', + key: this.buildTrialQrCodeKey(warehouseId), + maxSizeBytes: 2 * 1024 * 1024, + }); + + return { + success: true, + data: { appid: record.appid, url: uploadResult.url }, + code: 200, + message: '获取成功', + }; + } + + /** + * 拉取当前仓库小程序(wms_wechat_app)的用户列表(wms_user_oauth)。 + * + * 口径:当前登录用户所属仓库(ctx.user.store_id)下启用的小程序; + * 可选 app_id 指定单个应用(须属于当前仓库且启用,否则报错)。 + * 支持 where(operator 结构,由 method 层 prepareWhereContext 解析)、 + * pagination(page/pageSize)、sort(sortField/sortOrder 白名单)。 + * 响应排除 session_key/access_token/refresh_token 等敏感字段,并附 is_bound(user_id>0)。 + * + * @param {object} data 入参。 + * @param {number} [data.app_id] 指定 wms_wechat_app.id(可选)。 + * @param {object} [data.pagination] 分页 { page, pageSize }。 + * @param {object} [data.sort] 排序 { sortField, sortOrder }。 + * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 + */ + async userList(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!Number.isInteger(warehouseId) || warehouseId <= 0) { + return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; + } + + // 1. 定位当前仓库启用的小程序(可选 app_id 指定单个,须属于当前仓库) + const requestedAppId = Number(data.app_id); + const hasRequestedAppId = Number.isInteger(requestedAppId) && requestedAppId > 0; + const appWhere = { warehouse_id: warehouseId, is_enabled: 1 }; + if (hasRequestedAppId) { + appWhere.id = requestedAppId; + } + const apps = await ctx.model.WechatApp.findAll({ + where: appWhere, + attributes: [ 'id', 'appid', 'nickname' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (!Array.isArray(apps) || apps.length === 0) { + const message = hasRequestedAppId + ? '指定小程序不属于当前仓库或已停用' + : '当前仓库未授权小程序'; + return { success: false, data: null, code: 0, message }; + } + const appIds = apps + .map(item => Number(item.id)) + .filter(id => Number.isInteger(id) && id > 0); + + // 2. where:复用 method 层 prepareWhereContext 的解析结果;兼容直接调用时自行解析 + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const { parseWhereConditions } = require('../../lib/query_condition_parser'); + const rawWhere = data && data.where && typeof data.where === 'object' ? data.where : {}; + const parsed = parseWhereConditions({ where: rawWhere, app }); + if (!parsed.ok) { + return { success: false, data: null, code: 0, message: `where 参数解析失败: ${parsed.reason}` }; + } + parsedResult = parsed.result; + } + + const andConditions = [ + { provider: 'wechat' }, + { app_id: { [Op.in]: appIds } }, + ]; + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + // 3. 分页 + 排序 + const pagination = data.pagination && typeof data.pagination === 'object' ? data.pagination : {}; + const page = Math.max(Number(pagination.page) || 1, 1); + const pageSize = Math.max(Number(pagination.pageSize) || 20, 1); + const sort = data.sort && typeof data.sort === 'object' ? data.sort : {}; + const validSortFields = [ + 'id', + 'user_id', + 'app_id', + 'openid', + 'unionid', + 'nickname', + 'sex', + 'login_time', + 'login_count', + 'created_at', + 'updated_at', + ]; + const sortField = validSortFields.includes(String(sort.sortField || '').trim()) + ? String(sort.sortField).trim() + : 'updated_at'; + const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC'; + + // 4. 查询(排除敏感 token 字段) + const { count, rows } = await ctx.model.UserOauth.findAndCountAll({ + where: { [Op.and]: andConditions }, + attributes: { + exclude: [ 'session_key', 'refresh_token', 'access_token', 'expire_in', 'expire_time', 'login_code' ], + }, + order: [[ sortField, sortOrder ], [ 'id', 'DESC' ]], + limit: pageSize, + offset: (page - 1) * pageSize, + raw: true, + }); + + const list = rows.map(row => ({ + ...row, + id: Number(row.id), + user_id: Number(row.user_id), + app_id: Number(row.app_id), + is_bound: Number(row.user_id) > 0, + })); + + return { + success: true, + data: { + list, + apps: apps.map(item => ({ + id: Number(item.id), + appid: item.appid, + nickname: item.nickname || '', + })), + pagination: { page, pageSize, total: count }, + }, + code: 200, + message: '获取成功', + }; + } +} + +// 挂载静态方法,供登录码校验/重置等场景复用 +WechatSystemsService.buildLoginCode = buildLoginCode; + +module.exports = WechatSystemsService; diff --git a/app/view/wechat_auth_callback.html b/app/view/wechat_auth_callback.html new file mode 100644 index 0000000..ad2fb97 --- /dev/null +++ b/app/view/wechat_auth_callback.html @@ -0,0 +1,104 @@ + + + + + + <%= title %> + + + +
+
+

<%= title %>

+
+
<%= resultText %>
+
+ <% if (resultLevel === 'success') { %> +
+
小程序AppID
+
<%= appid %>
+
+
+
小程序名称
+
<%= nickname || '-' %>
+
+
+
绑定仓库ID
+
<%= warehouseId === null || warehouseId === undefined ? '-' : warehouseId %>
+
+
授权信息已保存,可返回系统查看小程序列表。
+ <% } else { %> +
请返回系统重新发起授权。
+ <% } %> +
+
+ + diff --git a/config/config.default.js b/config/config.default.js index 43f0f3e..b6fec10 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -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',