From 5c3ad6ad753c4d662013cb18c36ccbc85799fe2d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 23 Sep 2026 02:22:44 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=BE=AE=E4=BF=A1=E5=B0=8F=E7=A8=8B?= =?UTF-8?q?=E5=BA=8F):=20=E8=AE=A4=E8=AF=81=E7=8A=B6=E6=80=81=E5=AF=B9?= =?UTF-8?q?=E6=8E=A5=20queryauth=20=E6=96=B0=E5=A5=91=E7=BA=A6=EF=BC=8C?= =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=8F=91=E8=B5=B7=E8=AE=A4=E8=AF=81=E4=B8=8E?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E5=BE=AE=E4=BF=A1=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - wechat.ts:wechat.queryauth 契约更新(is_verified / verify_type_id / taskid / apply_status 等); 新增 wechat.wxaauth(发起认证,图片字段支持 COS URL,超时 180s)与 wechat.getAuthorizerInfo - MiniProgramConfigForm.vue:认证状态面板按新契约重写,新增「发起微信认证」弹窗与「同步微信信息」入口 --- src/api/wechat/wechat.ts | 156 +++- .../newview/pages/MiniProgramConfigForm.vue | 743 +++++++++++++++--- 2 files changed, 774 insertions(+), 125 deletions(-) diff --git a/src/api/wechat/wechat.ts b/src/api/wechat/wechat.ts index 5d8cf693..dd90c11e 100644 --- a/src/api/wechat/wechat.ts +++ b/src/api/wechat/wechat.ts @@ -39,15 +39,43 @@ export function wechatGetAuthUrl( } /** - * 查询当前仓库小程序的微信认证状态(wechat.queryauth)—— 无需入参,仓库由登录态上下文(ctx.user.store_id)决定。 + * 查询当前仓库小程序的微信认证状态(wechat.queryauth)—— 入参可选 `taskid`,仓库由登录态上下文(ctx.user.store_id)决定。 + * + * 三种返回形态(均为 code 200 / success:true,需看 `is_verified` 与 `taskid`): + * 1) 已认证:`{is_verified:true, appid, verify_type_id, verify_type_text, principal_name, signature, + * service_type_id, account_status}`,message「小程序已认证」; + * 2) 未认证但有认证任务:微信 `wxa/sec/queryauth` 结果 + `{appid, is_verified, task_status_text, apply_status_text}`; + * 3) 未认证且无认证任务:`{is_verified:false, appid, taskid:null, task_status:null, apply_status:null}`, + * message「尚未认证,且无认证任务」。 */ export type WeChatQueryAuthData = { /** 小程序 AppID */ - appid: string - /** 认证状态:0 未认证、1 认证中、2 认证通过、3 认证失败 */ - auth_state: number - /** 认证状态中文文案 */ - auth_state_text: string + appid?: string + /** 是否已认证(verify_type_id >= 0 或 apply_status=4) */ + is_verified?: boolean + /** 认证类型 ID:0 微信认证、1 新浪微博认证、3 资质通过未名称认证、4 资质通过+微博认证(-1 未认证) */ + verify_type_id?: number | null + /** 认证类型中文文案 */ + verify_type_text?: string + /** 认证主体名称 */ + principal_name?: string + /** 帐号简介 */ + signature?: string + /** 主体类型 ID(微信原值) */ + service_type_id?: number | null + /** 帐号状态(微信原值) */ + account_status?: number | null + /** 认证任务 ID(为空=后端没有认证任务) */ + taskid?: string | null + /** 认证任务状态(微信 task_status,0/1/2/3…15) */ + task_status?: number | null + /** 认证任务状态中文文案 */ + task_status_text?: string + /** 认证审核单状态:0 审核单不存在、1 待支付、2 审核中、3 打回重填、4 认证通过、5 认证最终失败 */ + apply_status?: number | null + /** 审核单状态中文文案 */ + apply_status_text?: string + [key: string]: unknown } export function wechatQueryAuth(): Promise< @@ -66,6 +94,94 @@ export function wechatQueryAuth(): Promise< } as any) } +/** + * 发起小程序认证(wechat.wxaauth)—— 后端分步: + * 图片字段传 COS 文件 URL(http/https)→ 后端下载并调微信 `wxa/sec/wxaapi/uploadmedia` 换 media_id + * → 替换请求体 → 调微信 `wxa/sec/wxaapi/wxaauth`(权限集 18)一步提交。 + * 成功后后端回写 `wms_wechat_app.auth_task_id`/`auth_apply_status`,返回 `taskid` 与 `auth_url`; + * 小程序已认证(verify_type_id >= 0)时会拒绝重复发起。 + */ +export type WeChatWxaauthParams = { + /** 联系人类型:1 法人、2 管理员 */ + contact_type: number + /** 联系人姓名 */ + contact_name: string + /** + * 其余白名单字段(后端透传微信 wxaauth 请求体): + * 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。 + * 图片字段(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;传非 URL 时视为已传 media_id 原样透传。 + */ + [key: string]: unknown +} + +export type WeChatWxaauthData = { + /** 小程序 AppID */ + appid?: string + /** 认证任务 ID(已回写 auth_task_id,供 wechat.queryauth 查进度) */ + taskid?: string + /** 小程序管理员认证链接(可选,打开后继续完成认证) */ + auth_url?: string + /** 审核单状态:0 不存在、1 待支付、2 审核中 */ + apply_status?: number + [key: string]: unknown +} + +export function wechatWxaauth(data: WeChatWxaauthParams): Promise< + { code?: number; message?: string; data?: WeChatWxaauthData } & Record +> { + return request({ + url: '/system', + method: 'post', + params: { + method: 'wechat.wxaauth', + v, + timestamp: new Date().getTime() + }, + data, + isSystemApi: true, + // 材料图片需后端下载 + 上传微信换 media_id,耗时较长 + timeout: 180000 + } as any) +} + +/** + * 获取并同步当前仓库小程序基础信息(wechat.getAuthorizerInfo)—— + * 后端调微信 `api_get_authorizer_info` 拉取授权账号详情,将昵称/头像/原始ID/主体名称/签名/ + * 认证类型/账号状态/权限集等落库 `wms_wechat_app` 后返回完整数据;认证进度请用 wechat.queryauth。 + */ +export type WeChatAuthorizerInfoData = { + /** 当前仓库小程序 AppID */ + appid?: string + /** 授权账号基本信息(nick_name/head_img/user_name/principal_name/signature/verify_type_info 等) */ + authorizer_info?: Record + /** 授权信息(authorizer_appid/func_info/authorizer_refresh_token) */ + authorization_info?: Record + [key: string]: unknown +} + +export function wechatGetAuthorizerInfo(): Promise< + { code?: number; message?: string; data?: WeChatAuthorizerInfoData } & Record +> { + return request({ + url: '/system', + method: 'post', + params: { + method: 'wechat.getAuthorizerInfo', + v, + timestamp: new Date().getTime() + }, + data: {}, + isSystemApi: true + } as any) +} + /** * 快速注册企业小程序(wechat.registerMiniprogram)—— * 调微信 fastregisterweapp?action=create(component_access_token)提交企业信息创建注册任务, @@ -155,18 +271,15 @@ export function wechatGetTemplateList(): Promise< /** * 上传代码并生成体验版(wechat.commit)—— - * 后端取当前仓库启用小程序,校验授权权限集 18(代码管理)与模板存在性后调微信 wxa/commit 上传代码, - * 成功后回写 wms_wechat_app.template_id。 + * 入参**只有 template_id**(正整数):后端取当前仓库启用小程序 → 校验授权权限集 18(代码管理) + * → 从模板库取该模板、直接用它自己的 `user_version`/`user_desc` 作为版本号与代码描述 + * (模板缺版本号/描述会直接失败,前端不再传) + * → `ext_json` 由后端固定生成 `{extEnable:true, extAppid:当前小程序appid}` + * → 调微信 wxa/commit → 成功后回写 `wms_wechat_app.template_id` 与 `user_version`。 */ export type WeChatCommitParams = { - /** 代码库中的代码模板 ID(由 wechat.getTemplateList 获取) */ + /** 代码库中的代码模板 ID(由 wechat.getTemplateList 获取,必须为正整数) */ template_id: number - /** ext.json 配置内容(JSON 字符串,控制 extAppid / 自定义字段等) */ - ext_json: string - /** 代码版本号(≤64 字符) */ - user_version: string - /** 代码描述 */ - user_desc: string } export type WeChatCommitData = { @@ -174,6 +287,17 @@ export type WeChatCommitData = { appid: string /** 已上传的模板 ID(同时回写 wms_wechat_app.template_id) */ template_id: number + /** 版本号(取自模板,由后端回传,非前端传入) */ + user_version?: string + /** 代码描述(取自模板) */ + user_desc?: string + /** 后端生成的 ext_json 字符串 */ + ext_json?: string + /** 微信返回的 errcode(0=成功) */ + errcode?: number + /** 微信返回的 errmsg */ + errmsg?: string + [key: string]: unknown } export function wechatCommit( @@ -285,6 +409,8 @@ export function wechatSubmitAudit( export const wechat = { getAuthUrl: wechatGetAuthUrl, queryAuth: wechatQueryAuth, + wxaauth: wechatWxaauth, + getAuthorizerInfo: wechatGetAuthorizerInfo, registerMiniprogram: wechatRegisterMiniprogram, getTemplateList: wechatGetTemplateList, commit: wechatCommit, diff --git a/src/views/system/setting/basicManagement/newview/pages/MiniProgramConfigForm.vue b/src/views/system/setting/basicManagement/newview/pages/MiniProgramConfigForm.vue index e7abace6..052538ae 100644 --- a/src/views/system/setting/basicManagement/newview/pages/MiniProgramConfigForm.vue +++ b/src/views/system/setting/basicManagement/newview/pages/MiniProgramConfigForm.vue @@ -4,11 +4,20 @@ - setting.warehouse.getweChatApp(settingWarehouseGetWeChatApp):拉取当前仓库已授权的微信小程序配置 - wechat.getAuthUrl(wechatGetAuthUrl):未配置时点击「去授权」获取授权链接,并在新小窗口中打开 - wechat.queryauth(wechatQueryAuth):查询当前仓库小程序的微信认证进度(左菜单「认证状态」) + (返回 `{is_verified, appid, verify_type_id/verify_type_text, principal_name, signature, taskid, + task_status/task_status_text, apply_status/apply_status_text}`) + - wechat.wxaauth(wechatWxaauth):发起小程序认证(「认证状态」未认证时的「发起微信认证」弹窗): + 材料图片传 COS URL(后端自动下载并换 media_id)→ 微信 wxa/sec/wxaapi/wxaauth 一步提交, + 返回 taskid / auth_url;已认证时后端拒绝重复发起 + - wechat.getAuthorizerInfo(wechatGetAuthorizerInfo):同步微信侧小程序基础信息 + (昵称/主体/认证类型/账号状态/权限集 → 落库后刷新本页;头部「同步微信信息」按钮) - wechat.registerMiniprogram(wechatRegisterMiniprogram):提交企业信息创建企业小程序注册任务 (「代注册小程序」弹窗;后端调微信 fastregisterweapp,法人微信收模板消息做人脸核身, 接口返回 errcode/errmsg、**不返回链接**,故不再开小窗) - wechat.getTemplateList(wechatGetTemplateList):拉普通代码模板库列表(左菜单「发布」,后端缓存 24h) - wechat.commit(wechatCommit):选定模板上传代码、生成体验版(需授权权限集 18) + (**入参只有 template_id**:版本号/代码描述由后端从模板库的模板取用,ext_json 由后端固定生成 + `{extEnable:true, extAppid:小程序appid}`;故页面不再展示这三项) - wechat.getTrialQRCode(wechatGetTrialQRCode):获取体验版二维码(后端转存 COS 后返回 URL) - wechat.submitAudit(wechatSubmitAudit):提交代码审核(后端仅在 audit_status!=1 时允许;回写 audit_id) ⚠️ 无审核状态查询接口,页面只能回显「已提交 + 审核单 ID」 @@ -23,6 +32,9 @@ 5) 认证状态:切到「认证状态」菜单时按需查询一次,可手动刷新 6) 发布:切到「发布」菜单时按需拉模板列表;上传代码成功后自动刷新配置并重取体验版二维码; 提交审核后可回显审核单 ID + 7) 失败响应识别:本套接口失败时返回 `{flag:'failure', code:0, success:false, message, data:null}`, + 而 axios 拦截器把 code=0 也当作成功码 → 必须用 `okCode(res)` 显式判 flag/success, + 授权类失败(如「小程序未授权相关权限(权限集 18/86),请重新授权」)即使是静默刷新也要提示 使用方: 1) basicManagement/newview 的 viewType='form' 标签页「微信小程序」 @@ -41,6 +53,18 @@
刷新 + + + + + 同步微信信息 + + + 代注册小程序 @@ -248,17 +272,52 @@ + + + + + + + 联系人 + + + + + + + + + + + + + + + + + + + + + 认证名称与主体 + + + + + + + + + + + + + + + + + + 法人信息 + + + + + + + + + + + + + + 材料照片(选填) + + +
+ + + 上传 + + + + 清除 + +
+
+ + 高级字段(选填) + + + +

+ 用于上方未覆盖的白名单字段(图片字段同样可填 COS URL);与上方字段同名时以此处为准 +

+
+
+ + +
@@ -610,23 +807,59 @@ import { } from '@/api/setting.warehouse/settingwarehouse' import { wechatCommit, + wechatGetAuthorizerInfo, wechatGetAuthUrl, wechatGetTemplateList, wechatGetTrialQRCode, wechatQueryAuth, wechatRegisterMiniprogram, wechatSubmitAudit, + wechatWxaauth, type WeChatAuditItem, + type WeChatCommitData, type WeChatQueryAuthData, type WeChatRegisterMiniprogramParams, type WeChatSubmitAuditData, type WeChatTemplateItem, - type WeChatTemplateListData + type WeChatTemplateListData, + type WeChatWxaauthData, + type WeChatWxaauthParams } from '@/api/wechat/wechat' import { isMainDomainHost, normalizeFrontHost } from '@/stores/modules/frontBrand' +import { uploadImageToCos } from '@/utils/cosImageUpload' defineOptions({ name: 'MiniProgramConfigForm' }) -const okCode = (code: unknown) => code === 1 || code === 200 || code === 0 +/** 本套接口响应中与成功/失败判定相关的字段 */ +type ApiFlagFields = { code?: unknown; flag?: unknown; success?: unknown; message?: unknown } + +/** + * 判定接口是否成功。 + * ⚠️ 本套接口失败时返回 `{ flag:'failure', code:0, success:false, message, data:null }`, + * 而 `code=0` 也被 axios 拦截器(SUCCESS_CODES)视为成功,因此**必须显式识别 flag/success**; + * 否则「小程序未授权相关权限(权限集 18/86),请重新授权」这类失败会被当成成功(data 为 null 只显示空值)。 + */ +const okCode = (res: unknown) => { + if (!res || typeof res !== 'object') return false + const raw = res as ApiFlagFields + if (raw.flag === 'failure' || raw.flag === 'fail' || raw.success === false) return false + return raw.code === 1 || raw.code === 200 || raw.code === 0 +} + +/** 授权类失败(缺少授权权限集)→ 在提示里补上「重新授权」指引 */ +const AUTH_FAILURE_RE = /权限集|重新授权|未授权/ + +/** + * 统一错误提示。 + * silent 仅抑制「非授权类」失败提示:授权类失败(权限集缺失)即使静默刷新也要提示,否则问题会被完全吞掉。 + */ +function showApiError(res: unknown, fallback: string, silent = false) { + const message = String((res as ApiFlagFields | null | undefined)?.message ?? '').trim() || fallback + const authIssue = AUTH_FAILURE_RE.test(message) + if (silent && !authIssue) return + ElMessage.error( + authIssue ? `${message}(请在「基础信息」中点击「重新授权」,确认授予全部权限后重试)` : message + ) +} // ============================================================ // 常量 @@ -724,11 +957,11 @@ const MENU_LIST: MiniProgramMenuItem[] = [ key: 'cert', label: '认证状态', icon: Medal, - desc: '小程序微信认证状态(接口已接入:wechat.queryauth)', + desc: '小程序微信认证状态与进度(已接入:wechat.queryauth 查询 / wechat.wxaauth 发起)', blocks: [ - { title: '认证信息(待后端补充)', desc: '认证类型 / 认证主体名称 / 认证主体证件号 / 认证有效期' }, - { title: '认证材料与支付(待后端补充)', desc: '认证订单与支付记录 / 认证结果通知 / 年审提醒' }, - { title: '状态与记录(待后端补充)', desc: '认证历史记录 / 失败原因与重试' } + { title: '认证材料(待后端补充)', desc: '认证主体证件号 / 认证有效期 / 认证订单与支付记录' }, + { title: '认证结果通知(待后端补充)', desc: '认证结果回调记录 / 失败原因与重试' }, + { title: '认证历史(待后端补充)', desc: '认证历史记录 / 年审提醒' } ] }, { @@ -842,17 +1075,14 @@ const templateLoaded = ref(false) const templateList = ref([]) const templateFromCache = ref(false) const commitSubmitting = ref(false) -const commitForm = reactive<{ - template_id?: number - user_version: string - user_desc: string - ext_json: string -}>({ - template_id: undefined, - user_version: '', - user_desc: '', - ext_json: '{}' -}) +/** 入参只有 template_id:版本号/代码描述取自模板,ext_json 由后端生成 */ +const commitForm = reactive<{ template_id?: number }>({ template_id: undefined }) + +/** 当前选中的模板(其 user_version / user_desc 会被后端直接当上传参数用,仅用于提交前校验) */ +const selectedTemplate = computed(() => + templateList.value.find((tpl) => Number(tpl.template_id) === Number(commitForm.template_id)) +) + const trialQRCodeLoading = ref(false) const trialQRCodePath = ref('') const trialQRCodeUrl = ref('') @@ -1050,8 +1280,8 @@ async function loadConfig(options: { silent?: boolean } = {}) { if (!options.silent) pageLoading.value = true try { const res: any = await settingWarehouseGetWeChatApp() - if (!res || !okCode(res.code)) { - if (!options.silent) ElMessage.error(res?.message || '获取微信小程序配置失败') + if (!okCode(res)) { + showApiError(res, '获取微信小程序配置失败', options.silent) return } // 未授权时后端返回 data:null(不能用整包 res 兜底,否则 flag/timestamp 会被误判为已配置) @@ -1074,20 +1304,110 @@ async function loadConfig(options: { silent?: boolean } = {}) { // ============================================================ // 认证状态(wechat.queryauth) // ============================================================ -/** 认证状态码 → 标签文案与颜色(后端同时返回 auth_state_text,展示时优先用后端文案) */ -const CERT_STATE_META: Record = { - 0: { text: '未认证', type: 'info' }, - 1: { text: '认证中', type: 'warning' }, - 2: { text: '认证通过', type: 'success' }, - 3: { text: '认证失败', type: 'danger' } +/** 已认证时的认证类型(后端返回 verify_type_text,缺省按 verify_type_id 兜底) */ +const VERIFY_TYPE_TEXT: Record = { + 0: '微信认证', + 1: '新浪微博认证', + 3: '资质通过未名称认证', + 4: '资质通过+微博认证' } +/** 审核单状态(apply_status)→ 文案与颜色 */ +const APPLY_STATUS_META: Record< + number, + { text: string; type: 'info' | 'warning' | 'success' | 'danger' } +> = { + 0: { text: '审核单不存在', type: 'info' }, + 1: { text: '待支付', type: 'warning' }, + 2: { text: '审核中', type: 'warning' }, + 3: { text: '打回重填', type: 'warning' }, + 4: { text: '认证通过', type: 'success' }, + 5: { text: '认证最终失败', type: 'danger' } +} + +/** 认证任务状态(task_status)→ 标签颜色(文案优先用后端 task_status_text) */ +const TASK_STATUS_TYPE: Record = { + 0: 'info', + 1: 'danger', + 2: 'danger', + 3: 'warning', + 4: 'warning', + 5: 'danger', + 6: 'warning', + 7: 'warning', + 8: 'danger', + 9: 'warning', + 11: 'danger', + 12: 'warning', + 14: 'danger', + 15: 'warning' +} + +/** 认证主状态:已认证 → 审核单状态 → 认证任务状态 → 尚未认证 */ const certStateMeta = computed<{ text: string; type: 'info' | 'warning' | 'success' | 'danger' }>(() => { - const meta = CERT_STATE_META[Number(certInfo.value?.auth_state)] - return { - text: certInfo.value?.auth_state_text || meta?.text || '未知状态', - type: meta?.type ?? 'info' + const info = certInfo.value + if (!info) return { text: '未知状态', type: 'info' } + if (info.is_verified) { + const typeId = info.verify_type_id === null || info.verify_type_id === undefined ? null : Number(info.verify_type_id) + return { + text: info.verify_type_text || (typeId !== null ? VERIFY_TYPE_TEXT[typeId] : '') || '已认证', + type: 'success' + } } + if (info.apply_status !== null && info.apply_status !== undefined) { + const status = Number(info.apply_status) + const meta = APPLY_STATUS_META[status] + return { + text: info.apply_status_text || meta?.text || `未知状态(${status})`, + type: meta?.type ?? 'info' + } + } + if (info.task_status !== null && info.task_status !== undefined) { + const status = Number(info.task_status) + return { + text: info.task_status_text || `认证任务进行中(${status})`, + type: TASK_STATUS_TYPE[status] ?? 'warning' + } + } + return { text: '尚未认证', type: 'info' } +}) + +/** 是否存在认证任务(taskid / task_status);无任务即后端还没发起过认证 */ +const certHasTask = computed(() => { + const info = certInfo.value + if (!info) return false + const hasTaskId = info.taskid !== null && info.taskid !== undefined && String(info.taskid).trim() !== '' + const hasTaskStatus = info.task_status !== null && info.task_status !== undefined + return hasTaskId || hasTaskStatus +}) + +/** 认证明细(只展示能明确命名的字段,空值不占位) */ +const certRows = computed<{ label: string; value: string }[]>(() => { + const info = certInfo.value + if (!info) return [] + const rows: { label: string; value: string }[] = [] + const push = (label: string, value: unknown) => { + if (value === null || value === undefined) return + const text = String(value).trim() + if (!text) return + rows.push({ label, value: text }) + } + + push('小程序 AppID', info.appid) + if (info.is_verified) { + const typeId = + info.verify_type_id === null || info.verify_type_id === undefined ? null : Number(info.verify_type_id) + push( + '认证类型', + info.verify_type_text || (typeId !== null ? VERIFY_TYPE_TEXT[typeId] : '') || (typeId !== null ? `认证类型 ${typeId}` : '') + ) + push('主体名称', info.principal_name) + push('帐号简介', info.signature) + } + push('认证任务 ID', info.taskid) + push('任务状态', info.task_status_text) + push('审核单状态', info.apply_status_text) + return rows }) /** 查询认证状态(切到「认证状态」菜单时按需拉取,也可手动刷新) */ @@ -1095,8 +1415,8 @@ async function loadAuthStatus(options: { silent?: boolean } = {}) { if (!options.silent) certLoading.value = true try { const res: any = await wechatQueryAuth() - if (!res || !okCode(res.code)) { - if (!options.silent) ElMessage.error(res?.message || '查询小程序认证状态失败') + if (!okCode(res)) { + showApiError(res, '查询小程序认证状态失败', options.silent) return null } const payload = res.data @@ -1141,8 +1461,8 @@ async function loadTemplateList(force = false) { templateLoading.value = true try { const res: any = await wechatGetTemplateList() - if (!res || !okCode(res.code)) { - ElMessage.error(res?.message || '获取代码模板列表失败') + if (!okCode(res)) { + showApiError(res, '获取代码模板列表失败') return null } const payload = (res.data ?? {}) as Partial @@ -1158,51 +1478,35 @@ async function loadTemplateList(force = false) { } } -/** 上传代码并生成体验版(wechat.commit) */ +/** 上传代码并生成体验版(wechat.commit;入参只有 template_id,版本号/描述由后端从模板取) */ async function submitCommit() { const templateId = commitForm.template_id if (templateId === undefined || templateId === null) { ElMessage.warning('请先选择代码模板') return } - const version = commitForm.user_version.trim() - if (!version) { - ElMessage.warning('请填写版本号') + const tpl = selectedTemplate.value + if (!tpl) { + ElMessage.warning('所选模板不在当前模板列表中,请先刷新模板') return } - if (version.length > 64) { - ElMessage.warning('版本号不能超过 64 个字符') - return - } - const desc = commitForm.user_desc.trim() - if (!desc) { - ElMessage.warning('请填写代码描述') - return - } - const extJson = commitForm.ext_json.trim() || '{}' - try { - JSON.parse(extJson) - } catch { - ElMessage.error('ext_json 不是合法的 JSON 字符串') + // 后端直接取模板的 user_version / user_desc 上传,模板缺这两项必然失败 → 前端提前拦 + if (!String(tpl.user_version ?? '').trim() || !String(tpl.user_desc ?? '').trim()) { + ElMessage.warning('所选模板缺少版本号或代码描述,请先在微信模板库补充后再上传') return } commitSubmitting.value = true try { - const res: any = await wechatCommit({ - template_id: templateId, - ext_json: extJson, - user_version: version, - user_desc: desc - }) - if (!res || !okCode(res.code)) { - ElMessage.error(res?.message || '上传代码失败') + const res: any = await wechatCommit({ template_id: Number(templateId) }) + if (!okCode(res)) { + showApiError(res, '上传代码失败') return } - const payload = (res.data ?? {}) as { appid?: string; template_id?: number } + const payload = (res.data ?? {}) as WeChatCommitData ElMessage.success( - payload.template_id != null - ? `代码已上传,体验版已生成(模板 #${payload.template_id})` + payload.user_version + ? `代码已上传,体验版已生成(版本 ${payload.user_version})` : '代码已上传,体验版已生成' ) // 后端会回写 wms_wechat_app.template_id,刷新基础信息保持一致 @@ -1223,8 +1527,8 @@ async function loadTrialQRCode(options: { silent?: boolean } = {}) { try { const path = trialQRCodePath.value.trim() const res: any = await wechatGetTrialQRCode(path ? { path } : {}) - if (!res || !okCode(res.code)) { - if (!options.silent) ElMessage.error(res?.message || '获取体验版二维码失败') + if (!okCode(res)) { + showApiError(res, '获取体验版二维码失败', options.silent) return null } const payload = (res.data ?? {}) as { url?: string } @@ -1269,8 +1573,8 @@ async function submitAudit() { privacy_api_not_use: auditForm.privacy_api_not_use || undefined, ...(itemList ? { item_list: itemList } : {}) }) - if (!res || !okCode(res.code)) { - ElMessage.error(res?.message || '提交审核失败') + if (!okCode(res)) { + showApiError(res, '提交审核失败') return } const payload = (res.data ?? {}) as WeChatSubmitAuditData @@ -1306,21 +1610,30 @@ function pickUrl(raw: Record): string { return '' } -/** 在新小窗口中打开链接(授权) */ -function openSmallWindow(url: string, windowName: string, tipText: string) { +/** + * 在新小窗口中打开链接(授权 / 代注册共用)。 + * @param url 目标地址。 + * @param windowName 窗口名(同名窗口会被复用)。 + * @param tipText 打开后的提示文案。 + * @param shouldWatch 是否启动「授权小窗」配置轮询(发起认证改为手动刷新认证状态,传 false)。 + */ +function openSmallWindow(url: string, windowName: string, tipText: string, shouldWatch = true) { const width = 760 const height = 780 const left = Math.max(0, Math.round((window.screen.width - width) / 2)) const top = Math.max(0, Math.round((window.screen.height - height) / 2)) const features = `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes` - authWindow = window.open(url, windowName, features) - if (!authWindow) { + const opened = window.open(url, windowName, features) + if (!opened) { ElMessage.warning('窗口被浏览器拦截:请允许本站弹出窗口后重试') return } ElMessage.info(tipText) - startWatch() + if (shouldWatch) { + authWindow = opened + startWatch() + } } /** 点击「去授权」:获取授权链接 → 打开小窗(仅主域名可用) */ @@ -1332,8 +1645,8 @@ async function handleAuthorize() { authUrlLoading.value = true try { const res: any = await wechatGetAuthUrl() - if (!res || !okCode(res.code)) { - ElMessage.error(res?.message || '获取微信授权链接失败') + if (!okCode(res)) { + showApiError(res, '获取微信授权链接失败') return } const url = pickUrl({ ...unwrapSettingWarehousePayload(res) }) @@ -1385,7 +1698,9 @@ async function submitRegister() { const nested = (raw.data && typeof raw.data === 'object' ? raw.data : {}) as Record const errcode = Number(nested.errcode ?? raw.errcode) const errmsg = String(nested.errmsg ?? raw.errmsg ?? raw.message ?? '') - if (!(okCode(raw.code) || errcode === 0)) { + // flag/success 显式失败时,不能被 errcode===0 的兜底救回来 + const flagFailure = raw.flag === 'failure' || raw.flag === 'fail' || raw.success === false + if (flagFailure || !(okCode(raw) || errcode === 0)) { ElMessage.error(errmsg || '提交代注册失败') return } @@ -1401,6 +1716,182 @@ async function submitRegister() { } } +// ============================================================ +// 同步微信基础信息(wechat.getAuthorizerInfo) +// ============================================================ +const authorizerInfoLoading = ref(false) + +/** 调微信 api_get_authorizer_info 同步主体/认证类型/账号状态/权限集,落库后刷新本页 */ +async function handleSyncAuthorizerInfo() { + if (!authorized.value) { + ElMessage.warning('请先完成小程序授权') + return + } + authorizerInfoLoading.value = true + try { + const res = await wechatGetAuthorizerInfo() + if (!okCode(res)) { + showApiError(res, '同步微信信息失败') + return + } + ElMessage.success('已同步微信侧小程序基础信息') + await loadConfig({ silent: true }) + // 认证类型 / 账号状态可能变化 → 认证状态重新查询 + certLoaded.value = false + if (activeMenu.value === 'cert') await loadAuthStatus() + } catch (e: unknown) { + ElMessage.error(e instanceof Error ? e.message : '同步微信信息失败') + } finally { + authorizerInfoLoading.value = false + } +} + +// ============================================================ +// 发起微信认证(wechat.wxaauth) +// ============================================================ +const authApplyDialogVisible = ref(false) +const authApplySubmitting = ref(false) +const authApplyFormRef = ref() +/** 正在上传的材料字段 key(用于按钮 loading) */ +const authMediaUploading = ref('') +/** 高级字段 JSON:白名单字段原样透传,与上方表单同名时以此为准 */ +const authApplyExtraJson = ref('') + +/** 发起认证表单:contact_type/contact_name 必填,其余选填(空值不提交) */ +const authApplyForm = reactive>({ + contact_type: 1, + contact_name: '', + contact_mobile: '', + contact_idcard_number: '', + nickname: '', + business_license_number: '', + business_license_address: '', + business_license_expiration_date: '', + legal_persona_name: '', + legal_persona_idcard_number: '', + legal_persona_idcard_expiration_date: '', + business_license_copy: '', + legal_persona_idcard_copy: '', + contact_cert_photo: '' +}) + +const authApplyRules: FormRules = { + contact_type: [{ required: true, message: '请选择联系人类型', trigger: 'change' }], + contact_name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }] +} + +/** 选填字段:提交时非空才带上(图片字段允许填 COS URL,后端自动换 media_id) */ +const AUTH_APPLY_OPTIONAL_KEYS = [ + 'contact_mobile', + 'contact_idcard_number', + 'nickname', + 'business_license_number', + 'business_license_address', + 'business_license_expiration_date', + 'legal_persona_name', + 'legal_persona_idcard_number', + 'legal_persona_idcard_expiration_date', + 'business_license_copy', + 'legal_persona_idcard_copy', + 'contact_cert_photo' +] as const + +/** 材料图片字段:可上传图片(换 COS URL)或直接填 URL */ +const AUTH_APPLY_MEDIA_FIELDS = [ + { key: 'business_license_copy', label: '营业执照照片' }, + { key: 'legal_persona_idcard_copy', label: '法人身份证照片' }, + { key: 'contact_cert_photo', label: '联系人证件照片' } +] as const + +/** 打开「发起微信认证」弹窗(保留已填内容,仅清校验态) */ +function openAuthApplyDialog() { + authApplyFormRef.value?.clearValidate() + authApplyDialogVisible.value = true +} + +/** 材料图片上传:复用 COS 直传,后端提交前会自动换 media_id */ +function authMediaRequest(key: string) { + return async (options: { file: File }) => { + const file = options?.file + if (!file) return + authMediaUploading.value = key + try { + const uploaded = await uploadImageToCos(file) + authApplyForm[key] = uploaded.fileUrl + ElMessage.success('图片已上传') + } catch (e: unknown) { + ElMessage.error(e instanceof Error ? e.message : '图片上传失败') + } finally { + authMediaUploading.value = '' + } + } +} + +/** 提交发起认证:成功刷新认证状态,必要时打开微信认证链接 */ +async function submitAuthApply() { + const form = authApplyFormRef.value + if (!form) return + const valid = await form.validate().catch(() => false) + if (!valid) return + + // 高级字段:必须是 JSON 对象 + let extra: Record = {} + const rawExtra = authApplyExtraJson.value.trim() + if (rawExtra) { + try { + const parsed: unknown = JSON.parse(rawExtra) + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + ElMessage.error('高级字段必须是 JSON 对象') + return + } + extra = parsed as Record + } catch { + ElMessage.error('高级字段不是合法的 JSON') + return + } + } + + const payload: WeChatWxaauthParams = { + contact_type: Number(authApplyForm.contact_type) || 1, + contact_name: String(authApplyForm.contact_name ?? '').trim() + } + for (const key of AUTH_APPLY_OPTIONAL_KEYS) { + const value = String(authApplyForm[key] ?? '').trim() + if (value) payload[key] = value + } + Object.assign(payload, extra) + + authApplySubmitting.value = true + try { + const res = await wechatWxaauth(payload) + if (!okCode(res)) { + showApiError(res, '发起认证失败') + return + } + const data = (res.data ?? {}) as WeChatWxaauthData + authApplyDialogVisible.value = false + ElMessage.success( + data.taskid + ? `认证已发起(任务 ${data.taskid}),请前往微信完成认证` + : '认证已发起,请前往微信完成认证' + ) + const url = data.auth_url ? String(data.auth_url) : '' + if (url) { + openSmallWindow( + url, + 'wx-miniprogram-auth-apply', + '请在新窗口中完成微信认证(法人核身 / 支付审核费),完成后点「刷新认证状态」', + false + ) + } + await loadAuthStatus() + } catch (e: unknown) { + ElMessage.error(e instanceof Error ? e.message : '发起认证失败') + } finally { + authApplySubmitting.value = false + } +} + /** 小窗打开期间轮询配置:流程完成即自动刷新 */ function startWatch() { stopAuthWatch() @@ -1618,6 +2109,38 @@ onBeforeUnmount(() => { margin-top: 12px; } +/* 未认证时的认证流程说明(发起认证接口待后端提供) */ +.mp-cert__flow { + margin: 12px 0 0; + padding-left: 20px; + color: #606266; + font-size: 13px; + line-height: 1.9; +} + +.mp-cert__flow code { + padding: 0 4px; + border-radius: 3px; + background: #f4f6f9; + font-size: 12px; +} + +/* 发起微信认证弹窗:材料图片行 */ +.mp-media-row { + display: flex; + align-items: center; + gap: 8px; + width: 100%; +} + +.mp-media-preview { + flex: none; + width: 40px; + height: 40px; + border: 1px solid #e8eef7; + border-radius: 4px; +} + /* ===== 发布 / 代码包管理(wechat.getTemplateList / wechat.commit / wechat.getTrialQRCode) ===== */ .mp-publish-form { max-width: 640px;