'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 }; // 协议版本:loginByCode 时自动更新到该小程序最新协议版本 id(无需前端传入) const latestAgreement = await ctx.model.WechatAgreementVersion.findOne({ where: { appid: wechatApp.appid }, order: [[ 'id', 'DESC' ]], attributes: [ 'id' ], raw: true, }); const latestAgreementVersionId = latestAgreement ? Number(latestAgreement.id) : null; 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, agreement_version_id: latestAgreementVersionId, }); } 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, agreement_version_id: latestAgreementVersionId, }); // 用主键 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 管理员操作):传入工号 id(wms_account_store_employee.id) * 与微信绑定记录 id(wms_user_oauth.id),查工号关联的账号 id(account_id),校验后写入 * wms_user_oauth.user_id 完成绑定;不签发 token(不改变当前登录态)。 * * 已绑定同一账号时幂等返回成功;已绑定其他账号、工号已解除/不属于当前仓库、 * 微信记录非 wechat 或不属于当前仓库小程序、账号被禁用时拒绝。 * * @param {object} data 入参。 * @param {number} data.id 工号 id(wms_account_store_employee.id)。 * @param {number} data.oauth_id 微信绑定记录 id(wms_user_oauth.id,来自 wechat.userList 结果)。 * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 绑定结果。 */ async bindByEmployee(data = {}) { const { ctx } = this; const employeeId = Number(data.id); const oauthId = Number(data.oauth_id); if (!Number.isInteger(employeeId) || employeeId <= 0) { return { success: false, data: null, code: 0, message: 'id(工号 id)为必填' }; } if (!Number.isInteger(oauthId) || oauthId <= 0) { return { success: false, data: null, code: 0, message: 'oauth_id(微信绑定记录 id)为必填' }; } // 工号存在且有效 const employee = await ctx.model.AccountStoreEmployee.findByPk(employeeId, { raw: true }); if (!employee) { return { success: false, data: null, code: 0, message: '工号不存在' }; } if (Number(employee.status) !== 1) { return { success: false, data: null, code: 0, message: '工号已解除,无法绑定' }; } const accountId = Number(employee.account_id); if (!Number.isInteger(accountId) || accountId <= 0) { return { success: false, data: null, code: 0, message: '工号未关联账号' }; } // 只能操作当前仓库的工号 const warehouseId = Number(ctx.user && ctx.user.store_id); if (Number.isInteger(warehouseId) && warehouseId > 0 && Number(employee.store_id) !== warehouseId) { return { success: false, data: null, code: 0, message: '工号不属于当前仓库' }; } // 微信绑定记录 const oauth = await ctx.model.UserOauth.findByPk(oauthId, { raw: true }); if (!oauth) { return { success: false, data: null, code: 0, message: '微信绑定记录不存在' }; } if (String(oauth.provider || '').trim() !== 'wechat') { return { success: false, data: null, code: 0, message: '该记录不是微信登录记录' }; } if (Number(oauth.user_id) > 0 && Number(oauth.user_id) !== accountId) { return { success: false, data: null, code: 0, message: '该微信已绑定其他账号,无法更换绑定' }; } // 微信记录所属应用须为当前仓库启用的小程序(oauth.app_id 关联 wms_wechat_app.id) if (Number(oauth.app_id) > 0 && Number.isInteger(warehouseId) && warehouseId > 0) { const wechatApp = await ctx.model.WechatApp.findOne({ where: { id: Number(oauth.app_id) }, attributes: [ 'id', 'warehouse_id' ], raw: true, }); if (!wechatApp) { return { success: false, data: null, code: 0, message: '微信记录关联的应用不存在' }; } if (Number(wechatApp.warehouse_id) > 0 && Number(wechatApp.warehouse_id) !== warehouseId) { return { success: false, data: null, code: 0, message: '微信记录不属于当前仓库的小程序' }; } } // 账号存在且未禁用 const account = await ctx.model.Account.findByPk(accountId, { raw: true }); if (!account) { return { success: false, data: null, code: 0, message: '工号关联的账号不存在' }; } if (Number(account.status) !== 1) { return { success: false, data: null, code: 0, message: '工号关联的账号已被禁用' }; } // 写绑定(幂等:已绑定同一账号直接返回成功) const alreadyBound = Number(oauth.user_id) === accountId; if (!alreadyBound) { await ctx.model.UserOauth.update( { user_id: accountId }, { where: { id: oauthId } } ); } return { success: true, data: { oauth_id: oauthId, openid: oauth.openid, unionid: oauth.unionid || '', nickname: oauth.nickname || '', already_bound: alreadyBound, employee: { id: Number(employee.id), account_id: accountId, store_id: Number(employee.store_id), real_name: employee.real_name || '', }, account: { id: Number(account.id), username: account.username || '', real_name: account.real_name || '', }, }, code: 200, message: alreadyBound ? '该微信已绑定此工号账号' : '绑定成功', }; } /** * 获取小程序用户须知富文本(免登录):传入 appId(小程序 AppID),按 appid 查询 * wms_wechat_app.user_agreement 返回;Redis 缓存 24 小时(key wechat:userAgreement:{appid}), * 有缓存直接使用缓存。 * * @param {object} data 入参。 * @param {string} data.appId 小程序 AppID(wx...)。 * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 */ async getUserAgreementText(data = {}) { const { ctx } = this; const appid = typeof data.appId === 'string' ? data.appId.trim() : ''; if (!appid) { return { success: false, data: null, code: 0, message: 'appId(小程序 AppID)为必填' }; } const client = new WechatOpenClient(ctx); const CACHE_KEY = `wechat:userAgreement:${appid}`; const CACHE_TTL_SECONDS = 24 * 3600; const cached = await client.cacheGet(CACHE_KEY); if (cached !== null && cached !== undefined) { try { const parsed = JSON.parse(cached); if (parsed && typeof parsed === 'object' && parsed.version_id !== undefined) { return { success: true, data: { appid, ...parsed, from_cache: true }, code: 200, message: '获取成功' }; } } catch (e) { // 缓存格式异常,忽略并重新查库 } } // 拉取只拉最新版本(副表 wms_wechat_agreement_version,id 自增即最新) const record = await ctx.model.WechatAgreementVersion.findOne({ where: { appid }, order: [[ 'id', 'DESC' ]], raw: true, }); if (!record) { return { success: false, data: null, code: 0, message: '未找到对应小程序或该小程序暂无用户须知' }; } const payload = { version_id: Number(record.id), text: record.content || '', }; await client.cacheSet(CACHE_KEY, JSON.stringify(payload), CACHE_TTL_SECONDS); return { success: true, data: { appid, ...payload, from_cache: false }, code: 200, message: '获取成功' }; } /** * 获取当前仓库小程序用户须知(需登录):按 ctx.user.store_id 取启用小程序, * 无小程序时提示「无小程序,需要先绑定」。 * * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 */ async getUserAgreement() { const { ctx } = this; const record = await this.findWarehouseWechatApp(ctx); if (!record) { return { success: false, data: null, code: 0, message: '无小程序,需要先绑定' }; } const latest = await this.findLatestAgreementVersion(ctx, record.appid); if (!latest) { return { success: false, data: null, code: 0, message: '该小程序暂无用户须知' }; } return { success: true, data: { appid: record.appid, nickname: record.nickname || '', version_id: Number(latest.id), text: latest.content || '', }, code: 200, message: '获取成功', }; } /** * 设置当前仓库小程序用户须知(需登录):提交一次自动新增版本(直接插入,id 自增即最新), * 并清除 getUserAgreementText 的 24h 缓存;无小程序时提示「无小程序,需要先绑定」。 * * @param {object} data 入参。 * @param {string} data.text 用户须知富文本(可传空字符串)。 * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 */ async setUserAgreement(data = {}) { const { ctx } = this; if (!Object.prototype.hasOwnProperty.call(data, 'text') || typeof data.text !== 'string') { return { success: false, data: null, code: 0, message: 'text(用户须知富文本)为必填且须为字符串' }; } const record = await this.findWarehouseWechatApp(ctx); if (!record) { return { success: false, data: null, code: 0, message: '无小程序,需要先绑定' }; } const appid = record.appid; // 提交一次自动新增版本:直接插入新行,id 自增即最新(无需维护版本号) const created = await ctx.model.WechatAgreementVersion.create({ appid, content: data.text, }); // 清除 24h 缓存,避免 getUserAgreementText 拉到旧内容 const client = new WechatOpenClient(ctx); await client.cacheDel(`wechat:userAgreement:${appid}`); return { success: true, data: { appid, nickname: record.nickname || '', version_id: Number(created.id), text: data.text, }, code: 200, message: '设置成功', }; } /** * 按当前登录仓库取启用的小程序(供 getUserAgreement/setUserAgreement 复用)。 * * @param {object} ctx Egg 上下文。 * @return {Promise} wms_wechat_app 行(raw);未识别仓库或无小程序返回 null。 */ async findWarehouseWechatApp(ctx) { const warehouseId = Number(ctx.user && ctx.user.store_id); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { return null; } return ctx.model.WechatApp.findOne({ where: { warehouse_id: warehouseId, is_enabled: 1 }, order: [[ 'id', 'ASC' ]], raw: true, }); } /** * 取指定 appid 的最新协议版本(副表 wms_wechat_agreement_version,id 自增即最新, * ORDER BY id DESC)。 * * @param {object} ctx Egg 上下文。 * @param {string} appid 小程序 AppID。 * @return {Promise} 版本行(raw);无版本返回 null。 */ async findLatestAgreementVersion(ctx, appid) { return ctx.model.WechatAgreementVersion.findOne({ where: { appid }, order: [[ 'id', 'DESC' ]], raw: true, }); } /** * 获取指定协议版本内容(需登录免权限):传入版本记录 id(wms_wechat_agreement_version.id, * 可在 wechat.userList 的 agreement_version_id 获取),校验该版本对应 appid 属于当前仓库的 * 启用小程序后返回协议内容。 * * @param {object} data 入参。 * @param {number} data.id 协议版本记录 id。 * @return {Promise<{success: boolean, data: object|null, code: number, message: string}>} 结果。 */ async getAgreementVersion(data = {}) { const { ctx } = this; const versionId = Number(data.id); if (!Number.isInteger(versionId) || versionId <= 0) { return { success: false, data: null, code: 0, message: 'id(协议版本记录 id)为必填' }; } const version = await ctx.model.WechatAgreementVersion.findByPk(versionId, { raw: true }); if (!version) { return { success: false, data: null, code: 0, message: '协议版本不存在' }; } // 校验仓库:该版本的 appid 必须属于当前仓库的启用小程序 const warehouseId = Number(ctx.user && ctx.user.store_id); if (!Number.isInteger(warehouseId) || warehouseId <= 0) { return { success: false, data: null, code: 0, message: '未识别到当前仓库' }; } const app = await ctx.model.WechatApp.findOne({ where: { appid: version.appid, warehouse_id: warehouseId, is_enabled: 1 }, attributes: [ 'id', 'appid', 'nickname' ], raw: true, }); if (!app) { return { success: false, data: null, code: 0, message: '该协议版本不属于当前仓库的小程序' }; } return { success: true, data: { id: Number(version.id), appid: version.appid, nickname: app.nickname || '', text: version.content || '', created_at: version.created_at || null, }, code: 200, message: '获取成功', }; } /** * 清理未使用且非最终版的用户须知历史版本(真实删除,释放 MySQL 磁盘空间)。 * * 保留规则:① 各 appid 的最终版(id 最大);② 被 wms_user_oauth.agreement_version_id * 引用的版本(老用户可能仍停留在旧协议)。其余版本真实删除(模型 paranoid=false)。 * 由定时任务 app/schedule/wechat_agreement_cleanup.js 每 1 小时调用一次。 * * @param {number} [batchSize] 单批删除条数(默认 500)。 * @return {Promise<{deleted: number, kept_latest: number, kept_in_use: number, total: number}>} 清理统计。 */ async cleanupUnusedAgreementVersions(batchSize = 500) { const { ctx } = this; const { Op } = this.app.Sequelize; const versions = await ctx.model.WechatAgreementVersion.findAll({ attributes: [ 'id', 'appid' ], raw: true, }); if (versions.length === 0) { return { deleted: 0, kept_latest: 0, kept_in_use: 0, total: 0 }; } // 各 appid 最终版(id 最大) const latestIdByAppid = new Map(); for (const v of versions) { const cur = latestIdByAppid.get(v.appid); if (!cur || Number(v.id) > cur.id) { latestIdByAppid.set(v.appid, { id: Number(v.id) }); } } // 被 oauth 引用的版本(正在使用) const oauthRows = await ctx.model.UserOauth.findAll({ where: { agreement_version_id: { [Op.ne]: null } }, attributes: [ 'agreement_version_id' ], raw: true, }); const usedIds = new Set(); for (const row of oauthRows) { usedIds.add(Number(row.agreement_version_id)); } // 未使用且非最终版 → 真实删除 const deleteIds = []; for (const v of versions) { const id = Number(v.id); const latest = latestIdByAppid.get(v.appid); if (usedIds.has(id) || (latest && latest.id === id)) { continue; } deleteIds.push(id); } let deleted = 0; const chunkSize = Number(batchSize) > 0 ? Math.floor(Number(batchSize)) : 500; for (let i = 0; i < deleteIds.length; i += chunkSize) { const chunk = deleteIds.slice(i, i + chunkSize); const destroyed = await ctx.model.WechatAgreementVersion.destroy({ where: { id: chunk }, }); deleted += Number(destroyed) || 0; } return { deleted, kept_latest: latestIdByAppid.size, kept_in_use: usedIds.size, total: versions.length, }; } /** * 确认登录码(需登录,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/wxaauth 新版接口,代商家调用需权限集 18)。 * * 后端分步:图片字段传 COS 文件 URL(http/https),后端下载文件 → wxa/sec/uploadauthmaterial * 换 mediaid → 替换请求体 → 以 { auth_data } 包裹调 wxaauth 一步提交。 * 成功后回写 wms_wechat_app.auth_task_id/auth_apply_status,返回 taskid/auth_url。 * * @param {object} data 入参(新版 wxaauth auth_data 字段白名单: * customer_type/account_name/account_name_type/pay_type/third_party_phone 与 * contact_info{name,email} 必填;invoice_info/qualification/qualification_other/ * account_supplemental/auth_identification/auth_ident_material/service_appid/taskid 可选; * 图片字段 qualification、qualification_other[]、account_supplemental[]、 * auth_ident_material[] 支持传 COS URL,后端自动换 mediaid;其余字段透传)。 * @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),请重新授权' }; } // 新版 auth_data 字段白名单透传(2024 版小程序认证接口) const ALLOWED_KEYS = [ 'customer_type', 'taskid', 'contact_info', 'invoice_info', 'qualification', 'qualification_other', 'account_name', 'account_name_type', 'account_supplemental', 'pay_type', 'auth_identification', 'auth_ident_material', 'third_party_phone', 'service_appid', ]; const authData = {}; for (const key of ALLOWED_KEYS) { if (Object.prototype.hasOwnProperty.call(data, key)) { authData[key] = data[key]; } } // 必填校验 if (authData.customer_type === undefined || authData.customer_type === null || authData.customer_type === '') { return { success: false, data: null, code: 0, message: 'customer_type 为必填(1 企业 / 12 个体工商户 / 15 个人)' }; } if (!authData.account_name) { return { success: false, data: null, code: 0, message: 'account_name(小程序账号名称)为必填' }; } if (authData.account_name_type === undefined || authData.account_name_type === null || authData.account_name_type === '') { return { success: false, data: null, code: 0, message: 'account_name_type 为必填(1 基于自选词汇 / 2 基于商标)' }; } if (authData.pay_type === undefined || authData.pay_type === null || authData.pay_type === '') { return { success: false, data: null, code: 0, message: 'pay_type 为必填(1 消耗服务商预购包 / 2 小程序开发者自行支付)' }; } if (!authData.third_party_phone) { return { success: false, data: null, code: 0, message: 'third_party_phone(第三方联系电话)为必填' }; } const contactInfo = authData.contact_info; if (!contactInfo || typeof contactInfo !== 'object' || !contactInfo.name || !contactInfo.email) { return { success: false, data: null, code: 0, message: 'contact_info.name / contact_info.email 为必填' }; } const client = new WechatOpenClient(ctx); // 分步①:图片字段传 COS URL 时,后端下载并上传微信换 mediaid try { await this.resolveBodyMedia(authData, client, record); } catch (e) { return { success: false, data: null, code: 0, message: e.message || '上传认证材料失败' }; } // 分步②:发起认证(请求体为 { auth_data } 包裹) const result = await client.wxaauth(record.appid, record.authorizer_refresh_token, { auth_data: authData }); 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 替换为微信 mediaid(http/https 开头的值视为 COS URL, * 其余值视为已是 mediaid 原样保留)。 * * 新版字段:qualification(单张字符串)、qualification_other/account_supplemental/ * auth_ident_material(字符串数组)。 * * @param {object} body wxaauth auth_data 请求体(就地修改)。 * @param {WechatOpenClient} client 微信客户端。 * @param {object} record wms_wechat_app 记录。 * @return {Promise} */ async resolveBodyMedia(body, client, record) { // 单张字符串图片字段 if (typeof body.qualification === 'string' && body.qualification) { body.qualification = await this.resolveMediaValue(body.qualification, client, record); } // 字符串数组图片字段 for (const key of [ 'qualification_other', 'account_supplemental', 'auth_ident_material' ]) { if (Array.isArray(body[key])) { for (let i = 0; i < body[key].length; i++) { if (typeof body[key][i] === 'string' && body[key][i]) { body[key][i] = await this.resolveMediaValue(body[key][i], client, record); } } } } } /** * 单个图片字段解析:http/https 开头(COS URL)→ 下载 → uploadauthmaterial 换 mediaid; * 其他值视为已传 mediaid 原样返回。 * * @param {string} value 字段值。 * @param {WechatOpenClient} client 微信客户端。 * @param {object} record wms_wechat_app 记录。 * @return {Promise} mediaid。 */ async resolveMediaValue(value, client, record) { const trimmed = String(value).trim(); if (!/^https?:\/\//i.test(trimmed)) { return value; } const buffer = await this.downloadFromUrl(trimmed); // 新版 uploadauthmaterial 限制:图片 ≤2M if (buffer.length > 2 * 1024 * 1024) { throw new Error(`上传认证材料失败(${trimmed}): 图片超过 2M 限制`); } 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}): 微信未返回 mediaid`); } 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); * 并附 agreement_version_id(协议版本id,loginByCode 自动回写,可供 getAgreementVersion 拉取协议内容)。 * * @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', 'agreement_version_id', '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), agreement_version_id: row.agreement_version_id === null || row.agreement_version_id === undefined ? null : Number(row.agreement_version_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;