'use strict'; /** * 微信开放平台第三方平台 API 客户端。 * 封装组件级接口调用与 token 管理(Redis 缓存,Key 与参考实现一致): * - component_access_token:调用授权方接口的组件凭证(约 2 小时)。 * - App:{appid}:authorization_code:授权码(authorized 事件推送后暂存)。 * - App:{appid}:authorizer_refresh_token:授权方刷新令牌(长期)。 * - App:{appid}:AuthorizerAccessToken:授权方接口调用凭证(约 2 小时)。 * * 配置读取 app.config.wechatOpen: * - component_appid / component_secret / token / encoding_aes_key / api_base */ const DEFAULT_API_BASE = 'https://api.weixin.qq.com'; /** 缓存预留提前量(秒):token 在过期前提前失效,避免临界调用失败。 */ const EXPIRE_MARGIN = 300; class WechatOpenClient { /** * @param {object} ctx Egg 上下文。 */ constructor(ctx) { this.ctx = ctx; this.app = ctx.app; this.config = (this.app && this.app.config && this.app.config.wechatOpen) || {}; } /** * 获取 Redis 客户端(cache 库),不可用时返回 null。 * @return {object|null} ioredis 客户端。 */ redis() { return this.app && this.app.redis && typeof this.app.redis.get === 'function' ? this.app.redis.get('cache') : null; } /** * 读取缓存。 * @param {string} key Redis key。 * @return {Promise} 缓存值。 */ async cacheGet(key) { const redis = this.redis(); if (!redis) return null; return redis.get(key); } /** * 写入缓存。 * @param {string} key Redis key。 * @param {string} value 值。 * @param {number} ttl 过期秒数。 * @return {Promise} */ async cacheSet(key, value, ttl) { const redis = this.redis(); if (!redis) return; await redis.set(key, value, 'EX', ttl); } /** * 删除缓存。 * @param {...string} keys Redis keys。 * @return {Promise} */ async cacheDel(...keys) { const redis = this.redis(); if (!redis || keys.length === 0) return; await redis.del(...keys); } /** * 发起微信 API POST 请求(JSON)。 * @param {string} path API 路径(不含 base)。 * @param {object} body 请求体。 * @param {string} [token] component_access_token(作为 URL query 拼接)。 * @return {Promise} 响应 JSON。 */ async apiPost(path, body, token) { const base = this.config.api_base || DEFAULT_API_BASE; let url = base.replace(/\/$/, '') + path; if (token) { url += `${url.includes('?') ? '&' : '?'}component_access_token=${encodeURIComponent(token)}`; } const response = await this.ctx.curl(url, { method: 'POST', dataType: 'json', timeout: 30000, headers: { 'Content-Type': 'application/json' }, data: body, }); return response && response.data !== undefined ? response.data : response; } /** * 携带 component_access_token 发起 POST 请求;遇 40001(invalid credential,token 被别处刷新顶掉) * 时自动清除缓存 token、重取后重试一次。 * * @param {string} path API 路径(不含 base)。 * @param {object} body 请求体。 * @return {Promise} 响应 JSON(必要时重试后)。 */ async apiPostWithComponentToken(path, body) { let result = await this.apiPost(path, body, await this.getComponentAccessToken()); if (result && Number(result.errcode) === 40001) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn(`[wechatOpen] component_access_token 失效(40001),清除缓存重试: ${path}`); } await this.cacheDel('component_access_token'); result = await this.apiPost(path, body, await this.getComponentAccessToken()); } return result; } /** * 保存 ComponentVerifyTicket(component_verify_ticket 事件推送后调用)。 * @param {string} ticket 推送的 Ticket。 * @return {Promise} */ async saveComponentVerifyTicket(ticket) { // 微信每 10 分钟推送一次,ticket 有效期 12 小时。 // 缓存 12 小时:异常未及时收到推送时,继续用上一次可用 ticket 换取 component_access_token(官方建议)。 await this.cacheSet('ComponentVerifyTicket', ticket, 12 * 3600); } /** * 获取组件接口调用凭证 component_access_token(缓存优先)。 * @return {Promise} component_access_token。 */ async getComponentAccessToken() { const cached = await this.cacheGet('component_access_token'); if (cached) return cached; const ticket = await this.cacheGet('ComponentVerifyTicket'); if (!ticket) { throw new Error('ComponentVerifyTicket 不存在,请等待微信推送后重试'); } const result = await this.apiPost('/cgi-bin/component/api_component_token', { component_appid: this.config.component_appid, component_appsecret: this.config.component_secret, component_verify_ticket: ticket, }); if (result && result.component_access_token) { const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN; await this.cacheSet('component_access_token', result.component_access_token, Math.max(ttl, 60)); return result.component_access_token; } throw new Error(`获取 component_access_token 失败: ${JSON.stringify(result)}`); } /** * 保存授权码(authorized/updateauthorized 事件推送后调用)。 * @param {string} authorizerAppid 授权方小程序 AppID。 * @param {string} authorizationCode 授权码。 * @return {Promise} */ async saveAuthorizationCode(authorizerAppid, authorizationCode) { // 授权码有效期 1 小时 await this.cacheSet(`App:${authorizerAppid}:authorization_code`, authorizationCode, 3600); } /** * 使用授权码换取授权方令牌(api_query_auth)。 * @param {string} authorizationCode 授权码。 * @return {Promise} authorization_info(含 authorizer_refresh_token/ * authorizer_access_token/expires_in/func_info 等)。 */ async queryAuth(authorizationCode) { const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_query_auth', { component_appid: this.config.component_appid, authorization_code: authorizationCode, }); if (result && result.authorization_info) { return result.authorization_info; } throw new Error(`获取 authorizer_refresh_token 失败: ${JSON.stringify(result)}`); } /** * 获取/刷新授权方接口调用凭证 authorizer_access_token(缓存优先)。 * @param {string} appid 授权方小程序 AppID。 * @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取)。 * @return {Promise} { authorizerAccessToken, authorizerRefreshToken }。 */ async getAuthorizerAccessToken(appid, refreshToken) { const tokenKey = `App:${appid}:AuthorizerAccessToken`; const cached = await this.cacheGet(tokenKey); if (cached) { return { authorizerAccessToken: cached, authorizerRefreshToken: refreshToken || null }; } let token = refreshToken || (await this.cacheGet(`App:${appid}:authorizer_refresh_token`)); if (!token) { throw new Error(`App:${appid} 的 authorizer_refresh_token 不存在`); } const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_authorizer_token', { component_appid: this.config.component_appid, authorizer_appid: appid, authorizer_refresh_token: token, }); if (result && result.authorizer_access_token) { const ttl = (result.expires_in || 7200) - EXPIRE_MARGIN; await this.cacheSet(tokenKey, result.authorizer_access_token, Math.max(ttl, 60)); if (result.authorizer_refresh_token) { token = result.authorizer_refresh_token; await this.cacheSet(`App:${appid}:authorizer_refresh_token`, token, 30 * 24 * 3600); } return { authorizerAccessToken: result.authorizer_access_token, authorizerRefreshToken: token }; } throw new Error(`获取 authorizer_access_token 失败: ${JSON.stringify(result)}`); } /** * 获取授权方基本信息(api_get_authorizer_info:昵称/头像/原始ID)。 * @param {string} appid 授权方小程序 AppID。 * @return {Promise} authorizer_info。 */ async getAuthorizerInfo(appid) { const detail = await this.getAuthorizerDetail(appid); if (detail && detail.authorizer_info) { return detail.authorizer_info; } throw new Error(`获取授权方信息失败: ${JSON.stringify(detail)}`); } /** * 获取授权账号详情(api_get_authorizer_info 完整返回:authorizer_info + authorization_info)。 * @param {string} appid 授权方小程序 AppID。 * @return {Promise} { authorizer_info, authorization_info }。 */ async getAuthorizerDetail(appid) { const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_get_authorizer_info', { component_appid: this.config.component_appid, authorizer_appid: appid, }); if (result && (result.authorizer_info || result.authorization_info)) { return result; } throw new Error(`获取授权账号详情失败: ${JSON.stringify(result)}`); } /** * 创建预授权码(用于生成授权链接)。 * @return {Promise} pre_auth_code。 */ async createPreAuthCode() { const cached = await this.cacheGet('preauthcode'); if (cached) return cached; const result = await this.apiPostWithComponentToken('/cgi-bin/component/api_create_preauthcode', { component_appid: this.config.component_appid, }); if (result && result.pre_auth_code) { await this.cacheSet('preauthcode', result.pre_auth_code, result.expires_in || 1800); return result.pre_auth_code; } throw new Error(`创建预授权码失败: ${JSON.stringify(result)}`); } /** * 查询小程序认证进度(POST wxa/sec/queryauth,使用 authorizer_access_token 代商家调用,权限集 18)。 * * @param {string} appid 小程序 AppID。 * @param {string} [refreshToken] 授权方刷新令牌(缺省时从缓存读取,Redis 丢失可用 DB 值兜底)。 * @param {string} taskid 认证任务 id(发起认证接口返回)。 * @return {Promise} 微信原始响应(errcode/errmsg/task_status/apply_status/orderid/auth_url 等)。 */ async queryMiniProgramAuth(appid, refreshToken, taskid) { const request = async () => { const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); const base = this.config.api_base || DEFAULT_API_BASE; const url = `${base.replace(/\/$/, '')}/wxa/sec/queryauth` + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; const response = await this.ctx.curl(url, { method: 'POST', dataType: 'json', timeout: 30000, headers: { 'Content-Type': 'application/json' }, data: { taskid }, }); return response && response.data !== undefined ? response.data : response; }; let result = await request(); // authorizer_access_token 失效(40001/40014)时清缓存重试一次 if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn(`[wechatOpen] wxa/sec/queryauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); } await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); result = await request(); } return result; } /** * 发起小程序认证(POST wxa/sec/wxaauth,使用 authorizer_access_token 代商家调用,权限集 18)。 * * ⚠ 微信已下线旧接口 /wxa/sec/wxaapi/wxaauth(调用返回 40066 invalid url); * 现行接口路径为 /wxa/sec/wxaauth,请求体为 { auth_data: {...} }(由业务层组装)。 * * @param {string} appid 小程序 AppID。 * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 * @param {object} body 认证请求体({ auth_data: {...} },字段见业务层白名单)。 * @return {Promise} 微信原始响应(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/wxaauth` + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; const response = await this.ctx.curl(url, { method: 'POST', dataType: 'json', timeout: 60000, headers: { 'Content-Type': 'application/json' }, data: body, }); return response && response.data !== undefined ? response.data : response; }; let result = await request(); // authorizer_access_token 失效(40001/40014)时清缓存重试一次 if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn(`[wechatOpen] wxa/sec/wxaauth token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); } await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); result = await request(); } return result; } /** * 上传认证材料图片到微信换取 mediaid(POST wxa/sec/uploadauthmaterial, * authorizer_access_token 代商家调用,权限集 18)。 * * ⚠ 微信已下线旧接口 /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} 微信原始响应(errcode/errmsg/media_id/mediaid)。 */ async uploadAuthMedia(appid, refreshToken, buffer, filename) { const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const tmpFile = path.join( os.tmpdir(), `wxauth-${Date.now()}-${Math.random().toString(36).slice(2, 10)}-${path.basename(filename || 'image.jpg')}` ); await fs.promises.writeFile(tmpFile, buffer); const request = async () => { const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); const base = this.config.api_base || DEFAULT_API_BASE; const url = `${base.replace(/\/$/, '')}/wxa/sec/uploadauthmaterial` + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; const response = await this.ctx.curl(url, { method: 'POST', dataType: 'json', timeout: 60000, files: { media: tmpFile }, }); return response && response.data !== undefined ? response.data : response; }; try { let result = await request(); // authorizer_access_token 失效(40001/40014)时清缓存重试一次 if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn(`[wechatOpen] wxa/sec/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(() => {}); } } /** * 获取小程序模板列表(wxa/gettemplatelist,仅支持 component_access_token,GET 请求)。 * * @param {number} [templateType] 0=普通模板、1=标准模板,不传返回全部。 * @return {Promise} 微信原始响应(errcode/errmsg/template_list)。 */ async getTemplateList(templateType) { const request = async () => { const componentAccessToken = await this.getComponentAccessToken(); const base = this.config.api_base || DEFAULT_API_BASE; const url = `${base.replace(/\/$/, '')}/wxa/gettemplatelist`; const response = await this.ctx.curl(url, { method: 'GET', dataType: 'json', timeout: 30000, data: { access_token: componentAccessToken, ...(templateType !== undefined && templateType !== null ? { template_type: templateType } : {}), }, }); return response && response.data !== undefined ? response.data : response; }; let result = await request(); if (result && Number(result.errcode) === 40001) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn('[wechatOpen] gettemplatelist 40001 component_access_token 失效,清除缓存重试'); } await this.cacheDel('component_access_token'); result = await request(); } return result; } /** * 提交代码审核(wxa/submit_audit,使用 authorizer_access_token 代商家调用,权限集 18)。 * * @param {string} appid 小程序 AppID。 * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 * @param {object} body 请求体(item_list/version_desc 等,均为可选)。 * @return {Promise} 微信原始响应(errcode/errmsg/auditid)。 */ async submitAudit(appid, refreshToken, body) { const request = async () => { const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); const base = this.config.api_base || DEFAULT_API_BASE; const url = `${base.replace(/\/$/, '')}/wxa/submit_audit` + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; const response = await this.ctx.curl(url, { method: 'POST', dataType: 'json', timeout: 60000, headers: { 'Content-Type': 'application/json' }, data: body, }); return response && response.data !== undefined ? response.data : response; }; let result = await request(); if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn(`[wechatOpen] wxa/submit_audit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); } await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); result = await request(); } return result; } /** * 获取体验版二维码(wxa/get_qrcode,使用 authorizer_access_token 代商家调用,权限集 18/86)。 * * 成功返回图片二进制(contentType=image/jpeg),失败返回微信 JSON(errcode/errmsg)。 * * @param {string} appid 小程序 AppID。 * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 * @param {string} [path] 二维码扫码进入的页面路径(可选,自动 urlencode)。 * @return {Promise} { errcode, errmsg } 或 { errcode: 0, contentType, buffer }。 */ async getTrialQRCode(appid, refreshToken, path) { const request = async () => { const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); const base = this.config.api_base || DEFAULT_API_BASE; let url = `${base.replace(/\/$/, '')}/wxa/get_qrcode` + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; if (path) { url += `&path=${encodeURIComponent(path)}`; } const response = await this.ctx.curl(url, { method: 'GET', timeout: 30000, }); const contentType = String((response.headers && response.headers['content-type']) || ''); if (contentType.includes('image')) { return { errcode: 0, errmsg: 'ok', contentType, buffer: response.data }; } return response && response.data !== undefined ? response.data : response; }; let result = await request(); // authorizer_access_token 失效(40001/40014)时清缓存重试一次 if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn(`[wechatOpen] wxa/get_qrcode token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); } await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); result = await request(); } return result; } /** * 上传代码并生成体验版(wxa/commit,使用 authorizer_access_token 代商家调用,权限集 18)。 * * @param {string} appid 小程序 AppID。 * @param {string} [refreshToken] 授权方刷新令牌(缺省从缓存/DB 读)。 * @param {object} body { template_id, ext_json, user_version, user_desc }。 * @return {Promise} 微信原始响应(errcode/errmsg)。 */ async commitTemplate(appid, refreshToken, body) { const request = async () => { const { authorizerAccessToken } = await this.getAuthorizerAccessToken(appid, refreshToken); const base = this.config.api_base || DEFAULT_API_BASE; const url = `${base.replace(/\/$/, '')}/wxa/commit` + `?access_token=${encodeURIComponent(authorizerAccessToken)}`; const response = await this.ctx.curl(url, { method: 'POST', dataType: 'json', timeout: 60000, headers: { 'Content-Type': 'application/json' }, data: body, }); return response && response.data !== undefined ? response.data : response; }; let result = await request(); // authorizer_access_token 失效(40001/40014)时清缓存重试一次 if (result && [ 40001, 40014 ].includes(Number(result.errcode))) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn(`[wechatOpen] wxa/commit token 失效(errcode=${result.errcode}),清除 authorizer token 缓存重试`); } await this.cacheDel(`App:${appid}:AuthorizerAccessToken`); result = await request(); } return result; } /** * 快速注册企业小程序(fastregisterweapp,仅支持第三方平台 component_access_token)。 * * @param {string} action create=创建小程序 / search=查询创建任务状态。 * @param {object} body 请求体。 * @return {Promise} 微信原始响应(errcode/errmsg)。 */ async fastRegisterWeapp(action, body) { const request = async () => { const componentAccessToken = await this.getComponentAccessToken(); const base = this.config.api_base || DEFAULT_API_BASE; const url = `${base.replace(/\/$/, '')}/cgi-bin/component/fastregisterweapp` + `?action=${encodeURIComponent(action)}` + `&component_access_token=${encodeURIComponent(componentAccessToken)}`; const response = await this.ctx.curl(url, { method: 'POST', dataType: 'json', timeout: 30000, headers: { 'Content-Type': 'application/json' }, data: body, }); return response && response.data !== undefined ? response.data : response; }; let result = await request(); if (result && Number(result.errcode) === 40001) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn('[wechatOpen] fastregisterweapp 40001 component_access_token 失效,清除缓存重试'); } await this.cacheDel('component_access_token'); result = await request(); } return result; } /** * 小程序登录凭证校验(jscode2session):第三方平台代小程序实现登录。 * @param {string} appid 小程序 AppID。 * @param {string} jsCode wx.login 获取的 code。 * @return {Promise} { openid, session_key, unionid }。 */ async jscode2session(appid, jsCode) { const request = async () => { const componentAccessToken = await this.getComponentAccessToken(); const base = this.config.api_base || DEFAULT_API_BASE; const url = `${base.replace(/\/$/, '')}/sns/component/jscode2session` + `?appid=${encodeURIComponent(appid)}` + '&grant_type=authorization_code' + `&component_appid=${encodeURIComponent(this.config.component_appid)}` + `&component_access_token=${encodeURIComponent(componentAccessToken)}` + `&js_code=${encodeURIComponent(jsCode)}`; const response = await this.ctx.curl(url, { method: 'GET', dataType: 'json', timeout: 30000, }); return response && response.data !== undefined ? response.data : response; }; let result = await request(); // 40001:component_access_token 被别处刷新顶掉(not latest),清除缓存重取后重试一次 if (result && Number(result.errcode) === 40001) { if (this.ctx && this.ctx.logger) { this.ctx.logger.warn('[wechatOpen] jscode2session 40001 component_access_token 失效,清除缓存重试'); } await this.cacheDel('component_access_token'); result = await request(); } // 调试:打印微信原始返回报文(仅 openid/session_key/unionid,无昵称头像) if (this.ctx && this.ctx.logger) { this.ctx.logger.info(`[wechatOpen] jscode2session appid=${appid} 返回: ${JSON.stringify(result)}`); } if (result && result.openid) { return result; } throw new Error(`jscode2session 失败: ${JSON.stringify(result)}`); } /** * 清理授权方相关缓存(unauthorized 取消授权事件后调用)。 * @param {string} appid 授权方小程序 AppID。 * @return {Promise} */ async clearAuthorizerCache(appid) { await this.cacheDel( `App:${appid}:authorization_code`, `App:${appid}:authorizer_refresh_token`, `App:${appid}:AuthorizerAccessToken` ); } /** * 保存授权 state(发起授权时缓存仓库信息,回跳时凭 state 取回)。 * @param {string} state 随机 state。 * @param {number|string} warehouseId 仓库ID。 * @param {number} [ttl=600] 过期秒数。 * @return {Promise} */ async saveAuthState(state, warehouseId, ttl = 600) { await this.cacheSet( `wechat_auth_state:${state}`, JSON.stringify({ warehouse_id: warehouseId, created_at: Math.floor(Date.now() / 1000) }), ttl ); } /** * 读取授权 state 对应的仓库信息。 * @param {string} state 随机 state。 * @return {Promise} { warehouse_id, created_at },不存在/过期返回 null。 */ async getAuthState(state) { const cached = await this.cacheGet(`wechat_auth_state:${state}`); if (!cached) return null; try { return JSON.parse(cached); } catch (e) { return null; } } /** * 删除授权 state 缓存(回调消费后调用,保证一次性)。 * @param {string} state 随机 state。 * @return {Promise} */ async clearAuthState(state) { await this.cacheDel(`wechat_auth_state:${state}`); } } module.exports = WechatOpenClient;