feat(wechat): 用户协议版本管理(getUserAgreement/setUserAgreement/getAgreementVersion 与清理定时任务)、工牌绑微信 bindByEmployee,wxaauth/uploadauthmaterial 接口路径迁移,wms_user_oauth 关联协议版本
This commit is contained in:
parent
24ffb5896e
commit
05b2d08014
@ -301,20 +301,21 @@ class WechatOpenClient {
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起小程序认证(wxa/sec/wxaapi/wxaauth,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
* 发起小程序认证(POST wxa/sec/wxaauth,使用 authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* 材料图片由前端上传换取 media_id 后一步提交;请求体字段白名单由业务层透传。
|
||||
* ⚠ 微信已下线旧接口 /wxa/sec/wxaapi/wxaauth(调用返回 40066 invalid url);
|
||||
* 现行接口路径为 /wxa/sec/wxaauth,请求体为 { auth_data: {...} }(由业务层组装)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {object} body 认证请求体(contact_type/contact_name/各 media_id 材料等)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/taskid/auth_url/apply_status)。
|
||||
* @param {object} body 认证请求体({ auth_data: {...} },字段见业务层白名单)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/taskid/auth_url)。
|
||||
*/
|
||||
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`
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/sec/wxaauth`
|
||||
+ `?access_token=${encodeURIComponent(authorizerAccessToken)}`;
|
||||
const response = await this.ctx.curl(url, {
|
||||
method: 'POST',
|
||||
@ -330,7 +331,7 @@ class WechatOpenClient {
|
||||
// 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 缓存重试`);
|
||||
this.ctx.logger.warn(`[wechatOpen] wxa/sec/wxaauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
@ -339,17 +340,18 @@ class WechatOpenClient {
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传认证材料图片到微信换取 media_id(wxa/sec/wxaapi/uploadmedia,
|
||||
* 上传认证材料图片到微信换取 mediaid(POST wxa/sec/uploadauthmaterial,
|
||||
* authorizer_access_token 代商家调用,权限集 18)。
|
||||
*
|
||||
* 采用 multipart/form-data:media=图片文件(写入临时文件后按路径上传,保证文件名带扩展名)、
|
||||
* media_type=image;成功后返回 media_id(3 天内有效,供 wxaauth 提交)。
|
||||
* ⚠ 微信已下线旧接口 /wxa/sec/wxaapi/uploadmedia;现行接口为 /wxa/sec/uploadauthmaterial,
|
||||
* 仅 media 一个 multipart 字段(图片 ≤2M,PNG/JPEG/JPG/GIF),成功返回 mediaid
|
||||
* (本方法归一化为 media_id 供上层使用)。
|
||||
*
|
||||
* @param {string} appid 小程序 AppID。
|
||||
* @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。
|
||||
* @param {Buffer} buffer 图片内容。
|
||||
* @param {string} filename 文件名(含扩展名,如 idcard.jpg)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/media_id/media_md5)。
|
||||
* @return {Promise<object>} 微信原始响应(errcode/errmsg/media_id/mediaid)。
|
||||
*/
|
||||
async uploadAuthMedia(appid, refreshToken, buffer, filename) {
|
||||
const fs = require('node:fs');
|
||||
@ -365,13 +367,12 @@ class WechatOpenClient {
|
||||
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`
|
||||
const url = `${base.replace(/\/$/, '')}/wxa/sec/uploadauthmaterial`
|
||||
+ `?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;
|
||||
@ -382,11 +383,15 @@ class WechatOpenClient {
|
||||
// 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 缓存重试`);
|
||||
this.ctx.logger.warn(`[wechatOpen] wxa/sec/uploadauthmaterial token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`);
|
||||
}
|
||||
await this.cacheDel(`App:${appid}:AuthorizerAccessToken`);
|
||||
result = await request();
|
||||
}
|
||||
// 现行接口成功返回字段为 mediaid,归一化为 media_id 供上层使用
|
||||
if (result && Number(result.errcode) === 0 && !result.media_id && result.mediaid) {
|
||||
result = { ...result, media_id: result.mediaid };
|
||||
}
|
||||
return result;
|
||||
} finally {
|
||||
await fs.promises.unlink(tmpFile).catch(() => {});
|
||||
|
||||
@ -118,6 +118,12 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '登录码({uuid,id_6} JSON 的 base64,一次性消费)',
|
||||
},
|
||||
agreement_version_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '协议版本ID(关联 wms_wechat_agreement_version.id,loginByCode 时自动更新到最新)',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
|
||||
57
app/model/wechat_agreement_version.js
Normal file
57
app/model/wechat_agreement_version.js
Normal file
@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 微信用户须知版本表模型(副表)。
|
||||
* 提交一次自动新增版本:version 为数字、同一 appid 内自动 +1;拉取只取最新版本。
|
||||
* @param {import('egg').Application} app Egg 应用实例。
|
||||
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TEXT, DATE } = app.Sequelize;
|
||||
|
||||
const WechatAgreementVersion = app.model.define('wechatAgreementVersion', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
appid: {
|
||||
type: STRING(64),
|
||||
allowNull: false,
|
||||
comment: '小程序AppID(关联 wms_wechat_app.appid)',
|
||||
},
|
||||
content: {
|
||||
type: TEXT('long'),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '用户须知富文本内容',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_wechat_agreement_version',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: false,
|
||||
comment: '微信用户须知版本表(副表,提交一次新增一个版本)',
|
||||
indexes: [
|
||||
{
|
||||
fields: [ 'appid' ],
|
||||
name: 'idx_appid',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return WechatAgreementVersion;
|
||||
};
|
||||
71
app/schedule/wechat_agreement_cleanup.js
Normal file
71
app/schedule/wechat_agreement_cleanup.js
Normal file
@ -0,0 +1,71 @@
|
||||
// app/schedule/wechat_agreement_cleanup.js
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 微信用户须知版本清理定时任务。
|
||||
*
|
||||
* 默认每 1 小时整点(cron:秒 分 时 日 月 周 = 0 0 * * * *)在单 worker 中执行一次,
|
||||
* 真实删除 wms_wechat_agreement_version 中「未被使用且不是对应 appid 最终版」的历史版本,
|
||||
* 释放 MySQL 磁盘空间。保留规则:各 appid 最终版(version 最大)+ 被
|
||||
* wms_user_oauth.agreement_version_id 引用的版本。
|
||||
* cron 从 config.wechatAgreementCleanup.cron 读取(config.default.js 提供默认值),
|
||||
* 本地环境可在 config.local.js 覆盖为短间隔以便快速验证;enable=false 时不注册本任务;
|
||||
* 实际清理逻辑收敛在 service.systems.wechat.cleanupUnusedAgreementVersions。
|
||||
*
|
||||
* @param {Object} app Egg 应用实例。
|
||||
* @return {Object} 定时任务定义(含 schedule 与 task)。
|
||||
*/
|
||||
module.exports = app => {
|
||||
const cleanupConfig = (app.config && app.config.wechatAgreementCleanup) || {};
|
||||
const cleanupCron = typeof cleanupConfig.cron === 'string' && cleanupConfig.cron
|
||||
? cleanupConfig.cron
|
||||
: '0 0 * * * *';
|
||||
|
||||
return {
|
||||
schedule: {
|
||||
cron: cleanupCron,
|
||||
type: 'worker',
|
||||
immediate: false,
|
||||
disable: cleanupConfig.enable === false,
|
||||
},
|
||||
|
||||
/**
|
||||
* 执行用户须知历史版本清理。
|
||||
*
|
||||
* 采用单 worker 防重入:上一轮未结束时跳过本轮;
|
||||
* 任务失败只记录错误日志,不向上抛出,避免导致 schedule 崩溃。
|
||||
*
|
||||
* @param {Object} ctx Egg 上下文。
|
||||
* @return {Promise<void>} 无返回值。
|
||||
*/
|
||||
async task(ctx) {
|
||||
const scheduleName = 'wechat_agreement_cleanup';
|
||||
|
||||
if (ctx.app._wechatAgreementCleanupRunning) {
|
||||
ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`);
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.app._wechatAgreementCleanupRunning = true;
|
||||
const startedAt = Date.now();
|
||||
try {
|
||||
const config = ctx.app.config.wechatAgreementCleanup || {};
|
||||
const batchSize = Number(config.batchSize) > 0
|
||||
? Math.floor(Number(config.batchSize))
|
||||
: 500;
|
||||
|
||||
const summary = await ctx.service.systems.wechat.cleanupUnusedAgreementVersions(batchSize);
|
||||
|
||||
ctx.logger.info(
|
||||
`[${scheduleName}] 本轮完成 deleted=${summary.deleted} kept_latest=${summary.kept_latest}`
|
||||
+ ` kept_in_use=${summary.kept_in_use} total=${summary.total}`
|
||||
+ ` duration=${Date.now() - startedAt}ms`
|
||||
);
|
||||
} catch (error) {
|
||||
ctx.logger.error(`[${scheduleName}] 执行失败: ${error.message}`);
|
||||
} finally {
|
||||
ctx.app._wechatAgreementCleanupRunning = false;
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
@ -8,10 +8,10 @@ const MainService = require('../main');
|
||||
class WechatService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
// getAuthUrl:需登录、免权限、不记系统日志;loginByCode:免登录、免权限、免鉴权;
|
||||
// pushLoginCode/queryauth/registerMiniprogram/getTemplateList/commit/getTrialQRCode/submitAudit/userList:需登录、免权限(PC 已登录用户操作);
|
||||
// getAuthUrl:需登录、免权限、不记系统日志;loginByCode/getUserAgreementText:免登录、免权限、免鉴权;
|
||||
// pushLoginCode/queryauth/wxaauth/registerMiniprogram/getTemplateList/commit/getTrialQRCode/submitAudit/userList/getUserAgreement/setUserAgreement/getAgreementVersion:需登录、免权限(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');
|
||||
this.systemInit('loginByCode,getUserAgreementText', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', '*', 'getAuthUrl,pushLoginCode,queryauth,wxaauth,registerMiniprogram,getTemplateList,commit,getTrialQRCode,submitAudit,userList,getAuthorizerInfo,getUserAgreement,setUserAgreement,getAgreementVersion', 'bindUser,updateInfo,uploadHeadimg,getMyLoginCode');
|
||||
}
|
||||
|
||||
/**
|
||||
@ -76,6 +76,97 @@ class WechatService extends MainService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按工号绑定微信(需登录需权限,PC 管理员操作):传工号 id 与微信绑定记录 id,
|
||||
* 查工号的账号 id 写入 wms_user_oauth.user_id。
|
||||
*
|
||||
* @param {Object} data 请求参数(id 工号id、oauth_id 微信绑定记录id)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async bindByEmployee(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.bindByEmployee(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '绑定成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('绑定失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取小程序用户须知富文本(免登录):传入 appId,24h 缓存。
|
||||
*
|
||||
* @param {Object} data 请求参数(appId)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getUserAgreementText(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.getUserAgreementText(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 请求参数(无)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getUserAgreement(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.getUserAgreement(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 请求参数(text 富文本)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async setUserAgreement(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.setUserAgreement(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '设置成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('设置用户须知失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定协议版本内容(需登录免权限):传版本记录 id,校验仓库后返回协议内容。
|
||||
*
|
||||
* @param {Object} data 请求参数(id 协议版本记录id)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async getAgreementVersion(data) {
|
||||
try {
|
||||
const result = await this.service.systems.wechat.getAgreementVersion(data || {});
|
||||
if (result.code) {
|
||||
return this.success(result.message || '获取成功', result);
|
||||
}
|
||||
return this.fail(result.message, result);
|
||||
} catch (e) {
|
||||
return this.fail('获取协议版本失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认登录码(需登录,PC 已登录用户确认小程序登录)。
|
||||
*
|
||||
@ -113,9 +204,10 @@ class WechatService extends MainService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起小程序认证(需登录):前端上传材料换取 media_id 后一步提交。
|
||||
* 发起小程序认证(需登录):后端分步——图片字段传 COS 文件 URL,后端下载 →
|
||||
* wxa/sec/uploadauthmaterial 换 mediaid → { auth_data } 包裹提交 wxa/sec/wxaauth。
|
||||
*
|
||||
* @param {Object} data 请求参数(contact_type/contact_name 必填,其余白名单字段透传)。
|
||||
* @param {Object} data 请求参数(新版 auth_data 字段白名单透传,详见 methods/system.json)。
|
||||
* @return {Promise<Object>} 统一响应结果。
|
||||
*/
|
||||
async wxaauth(data) {
|
||||
|
||||
@ -146,6 +146,16 @@ class WechatSystemsService extends Service {
|
||||
|
||||
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({
|
||||
@ -153,6 +163,7 @@ class WechatSystemsService extends Service {
|
||||
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({
|
||||
@ -165,6 +176,7 @@ class WechatSystemsService extends Service {
|
||||
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) });
|
||||
@ -336,6 +348,404 @@ class WechatSystemsService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按工号绑定微信(需登录需权限,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<object|null>} 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<object|null>} 版本行(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 生成的码。
|
||||
*
|
||||
@ -511,17 +921,18 @@ class WechatSystemsService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起小程序认证(需登录,wxa/sec/wxaapi/wxaauth,代商家调用需权限集 18)。
|
||||
* 发起小程序认证(需登录,wxa/sec/wxaauth 新版接口,代商家调用需权限集 18)。
|
||||
*
|
||||
* 后端分步:图片字段传 COS 文件 URL(http/https),后端下载文件 → wxa/sec/wxaapi/uploadmedia
|
||||
* 换 media_id → 替换请求体 → 调 wxaauth 一步提交。
|
||||
* 后端分步:图片字段传 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 请求体字段白名单:
|
||||
* 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;其余字段透传)。
|
||||
* @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 = {}) {
|
||||
@ -553,39 +964,52 @@ class WechatSystemsService extends Service {
|
||||
return { success: false, data: null, code: 0, message: '小程序未授权代码管理权限(权限集 18),请重新授权' };
|
||||
}
|
||||
|
||||
// 白名单透传微信请求体字段
|
||||
// 新版 auth_data 字段白名单透传(2024 版小程序认证接口)
|
||||
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',
|
||||
'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 body = {};
|
||||
const authData = {};
|
||||
for (const key of ALLOWED_KEYS) {
|
||||
if (Object.prototype.hasOwnProperty.call(data, key)) {
|
||||
body[key] = data[key];
|
||||
authData[key] = data[key];
|
||||
}
|
||||
}
|
||||
if (body.contact_type === undefined || body.contact_name === undefined) {
|
||||
return { success: false, data: null, code: 0, message: 'contact_type/contact_name 为必填' };
|
||||
|
||||
// 必填校验
|
||||
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 时,后端下载并上传微信换 media_id
|
||||
// 分步①:图片字段传 COS URL 时,后端下载并上传微信换 mediaid
|
||||
try {
|
||||
await this.resolveBodyMedia(body, client, record);
|
||||
await this.resolveBodyMedia(authData, 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);
|
||||
// 分步②:发起认证(请求体为 { 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}` };
|
||||
@ -607,67 +1031,43 @@ class WechatSystemsService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 将请求体中的图片字段从 COS URL 替换为微信 media_id(http/https 开头的值视为 COS URL,
|
||||
* 其余值视为已是 media_id 原样保留)。
|
||||
* 将请求体中的图片字段从 COS URL 替换为微信 mediaid(http/https 开头的值视为 COS URL,
|
||||
* 其余值视为已是 mediaid 原样保留)。
|
||||
*
|
||||
* @param {object} body wxaauth 请求体(就地修改)。
|
||||
* 新版字段: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<void>}
|
||||
*/
|
||||
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);
|
||||
}
|
||||
// 单张字符串图片字段
|
||||
if (typeof body.qualification === 'string' && body.qualification) {
|
||||
body.qualification = await this.resolveMediaValue(body.qualification, 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 字符串数组图片字段
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 原样返回。
|
||||
* 单个图片字段解析:http/https 开头(COS URL)→ 下载 → uploadauthmaterial 换 mediaid;
|
||||
* 其他值视为已传 mediaid 原样返回。
|
||||
*
|
||||
* @param {string} value 字段值。
|
||||
* @param {WechatOpenClient} client 微信客户端。
|
||||
* @param {object} record wms_wechat_app 记录。
|
||||
* @return {Promise<string>} media_id。
|
||||
* @return {Promise<string>} mediaid。
|
||||
*/
|
||||
async resolveMediaValue(value, client, record) {
|
||||
const trimmed = String(value).trim();
|
||||
@ -676,6 +1076,10 @@ class WechatSystemsService extends Service {
|
||||
}
|
||||
|
||||
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) {
|
||||
@ -683,7 +1087,7 @@ class WechatSystemsService extends Service {
|
||||
throw new Error(`上传认证材料失败(${filename}): ${errmsg}`);
|
||||
}
|
||||
if (!result.media_id) {
|
||||
throw new Error(`上传认证材料失败(${filename}): 微信未返回 media_id`);
|
||||
throw new Error(`上传认证材料失败(${filename}): 微信未返回 mediaid`);
|
||||
}
|
||||
return result.media_id;
|
||||
}
|
||||
@ -1323,7 +1727,8 @@ class WechatSystemsService extends Service {
|
||||
* 可选 app_id 指定单个应用(须属于当前仓库且启用,否则报错)。
|
||||
* 支持 where(operator 结构,由 method 层 prepareWhereContext 解析)、
|
||||
* pagination(page/pageSize)、sort(sortField/sortOrder 白名单)。
|
||||
* 响应排除 session_key/access_token/refresh_token 等敏感字段,并附 is_bound(user_id>0)。
|
||||
* 响应排除 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(可选)。
|
||||
@ -1399,6 +1804,7 @@ class WechatSystemsService extends Service {
|
||||
'sex',
|
||||
'login_time',
|
||||
'login_count',
|
||||
'agreement_version_id',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
];
|
||||
@ -1424,6 +1830,9 @@ class WechatSystemsService extends Service {
|
||||
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,
|
||||
}));
|
||||
|
||||
|
||||
@ -258,6 +258,15 @@ module.exports = appInfo => {
|
||||
// 单轮批处理大小(按 id 升序分批)
|
||||
batchSize: 50,
|
||||
};
|
||||
// 微信用户须知版本清理定时任务配置(每 1 小时执行,真实删除未使用且非最终版的历史版本释放磁盘空间)
|
||||
config.wechatAgreementCleanup = {
|
||||
// 开关:false 时不注册本定时任务
|
||||
enable: true,
|
||||
// 触发 cron(秒 分 时 日 月 周):默认每 1 小时整点;本地环境可在 config.local.js 覆盖为短间隔
|
||||
cron: '0 0 * * * *',
|
||||
// 单批硬删除行数(按 id 分批,走主键索引)
|
||||
batchSize: 500,
|
||||
};
|
||||
// 系统日志超期清理定时任务配置(每日凌晨 03:00 执行,硬删除 wms_system_log 超期数据释放磁盘空间)
|
||||
config.systemLogCleanup = {
|
||||
enable: true,
|
||||
|
||||
@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* wms_wechat_app 增加用户须知富文本字段(只做加字段):
|
||||
* - user_agreement:用户须知(富文本 longText),供 wechat.getUserAgreementText/
|
||||
* wechat.getUserAgreement/wechat.setUserAgreement 读写。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_wechat_app';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'user_agreement', {
|
||||
type: Sequelize.TEXT('long'),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '用户须知(富文本 longText)',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'user_agreement');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,84 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 用户须知改为副表版本管理(2026-09-23):
|
||||
* 1. 移除 wms_wechat_app.user_agreement 字段(富文本改为副表存储);
|
||||
* 2. 新增副表 wms_wechat_agreement_version:appid + 数字版本号 + 富文本,
|
||||
* 提交一次自动新增版本,拉取只取最新版本;
|
||||
* 3. wms_user_oauth 增加 agreement_version_id(协议版本id),loginByCode 时自动更新到最新。
|
||||
*/
|
||||
|
||||
const APP_TABLE = 'wms_wechat_app';
|
||||
const VERSION_TABLE = 'wms_wechat_agreement_version';
|
||||
const OAUTH_TABLE = 'wms_user_oauth';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn(APP_TABLE, 'user_agreement');
|
||||
|
||||
await queryInterface.createTable(VERSION_TABLE, {
|
||||
id: {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键',
|
||||
},
|
||||
appid: {
|
||||
type: Sequelize.STRING(64),
|
||||
allowNull: false,
|
||||
comment: '小程序AppID(关联 wms_wechat_app.appid)',
|
||||
},
|
||||
version: {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: false,
|
||||
comment: '协议版本号(数字,同一 appid 内自动+1)',
|
||||
},
|
||||
content: {
|
||||
type: Sequelize.TEXT('long'),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '用户须知富文本内容',
|
||||
},
|
||||
created_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
comment: '微信用户须知版本表(副表,提交一次新增一个版本)',
|
||||
});
|
||||
await queryInterface.addIndex(VERSION_TABLE, [ 'appid', 'version' ], {
|
||||
unique: true,
|
||||
name: 'uk_appid_version',
|
||||
});
|
||||
await queryInterface.addIndex(VERSION_TABLE, [ 'appid' ], {
|
||||
name: 'idx_appid',
|
||||
});
|
||||
|
||||
await queryInterface.addColumn(OAUTH_TABLE, 'agreement_version_id', {
|
||||
type: Sequelize.BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '协议版本ID(关联 wms_wechat_agreement_version.id,loginByCode 时自动更新到最新)',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn(OAUTH_TABLE, 'agreement_version_id');
|
||||
await queryInterface.dropTable(VERSION_TABLE);
|
||||
await queryInterface.addColumn(APP_TABLE, 'user_agreement', {
|
||||
type: Sequelize.TEXT('long'),
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '用户须知(富文本 longText)',
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 用户须知版本表去掉 version 数字版本号,直接用 id 自增(2026-09-23):
|
||||
* - 删除唯一索引 uk_appid_version(appid,version);
|
||||
* - 删除 version 列;最新版本判定改为 ORDER BY id DESC。
|
||||
*/
|
||||
|
||||
const TABLE_NAME = 'wms_wechat_agreement_version';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface) {
|
||||
await queryInterface.removeIndex(TABLE_NAME, 'uk_appid_version');
|
||||
await queryInterface.removeColumn(TABLE_NAME, 'version');
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn(TABLE_NAME, 'version', {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '协议版本号(数字,同一 appid 内自动+1)',
|
||||
});
|
||||
await queryInterface.addIndex(TABLE_NAME, [ 'appid', 'version' ], {
|
||||
unique: true,
|
||||
name: 'uk_appid_version',
|
||||
});
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user