const { API_DOMAIN, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING, ENV_VERSION } = require('./config') const auth = require('./auth') const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto') const HEADER_TIMESTAMP = 'X-Timestamp' const HEADER_NONCE = 'X-Nonce' const HEADER_SIGNATURE = 'X-Signature' const HEADER_SIGNATURE_VERSION = 'X-Sign-Version' /** * 服务端协议同意拦截返回的业务码:登录用户未同意最新版协议时返回 4510。 */ const AGREEMENT_VERSION_REQUIRED_CODE = 4510 /** 挂起请求被放弃时的自定义错误码,调用方据此区分“未完成协议同意”与普通业务失败。 */ const AGREEMENT_NOT_ACCEPTED_CODE = 'AGREEMENT_NOT_ACCEPTED' const AGREEMENT_NOT_ACCEPTED_MESSAGE = '未完成协议同意' /** 面向用户的友好文案:内部错误码与文案保持技术语义,展示层统一经 resolveUserMessage 转换。 */ const AGREEMENT_NOT_ACCEPTED_USER_MESSAGE = '协议未确认,请稍后重试' /** * 挂起请求最长等待时间(3 分钟),只作为“避免页面 loading 永久卡死”的兜底。 * 用户阅读两份协议可能耗时较久,不能因为超时提前判定操作失败; * 超时结算后不再自动重放该请求,但用户稍后再同意协议仍会正常记录同意, * 只是原请求需要用户重新发起。 */ const AGREEMENT_PENDING_TIMEOUT_MS = 180000 const AGREEMENT_PAGE_URL = '/pages/legal/index?mode=accept' /** * 一屏多个请求同时命中 4510 时只允许弹一次弹窗; * 首个被拦下的请求挂起等待用户在协议页同意后重放,新的 4510 会先结算旧的挂起请求。 */ let agreementPromptVisible = false let agreementBlockedRequest = null function buildUrl(url, params) { const sourceParams = params || {} const baseUrl = sourceParams.__baseUrl ? sourceParams.__baseUrl : API_DOMAIN const query = Object.keys(sourceParams) .filter(key => key !== '__baseUrl') .filter(key => sourceParams[key] !== undefined && sourceParams[key] !== null && sourceParams[key] !== '') .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(sourceParams[key])}`) .join('&') const target = `${baseUrl}${url}` return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target } function normalizeError(message, raw) { const error = new Error(message || '请求失败') error.raw = raw return error } function resolveResponseMessage(response, fallbackMessage) { const data = response && response.data ? response.data : {} return data.message || fallbackMessage } function clearRuntimeSession() { const app = getApp() if (app && typeof app.clearSession === 'function') { app.clearSession() return } auth.clearSession() } function redirectToLoginAfterExpired(message) { if (!auth.beginSessionExpiredHandling()) { return } // 真正的登录失效才清会话;同时丢弃协议重试目标,避免把旧会话的请求带到新会话。 agreementBlockedRequest = null agreementPromptVisible = false clearRuntimeSession() wx.showToast({ title: message, icon: 'none', duration: 1200 }) setTimeout(() => { wx.reLaunch({ url: '/pages/login/index' }) }, 700) } function handleUnauthorized(response, url) { const message = resolveResponseMessage(response, '登录已过期,请重新登录') if (isAuthFreePath(url)) { return normalizeError(message, response) } redirectToLoginAfterExpired(message) return normalizeError(message, response) } function cloneRequestOptions(options) { return { url: options.url, method: options.method, data: options.data, params: options.params, header: options.header, timeout: options.timeout } } function createAgreementNotAcceptedError(raw) { const error = normalizeError(AGREEMENT_NOT_ACCEPTED_MESSAGE, raw) error.code = AGREEMENT_NOT_ACCEPTED_CODE return error } /** * 集中把内部错误文案映射成可直接展示给用户的文案,避免各页面自行硬编码。 * AGREEMENT_NOT_ACCEPTED 的内部语义保持“未完成协议同意”,展示为“协议未确认,请稍后重试”。 */ function resolveUserMessage(error, fallbackMessage) { if (error && error.code === AGREEMENT_NOT_ACCEPTED_CODE) { return AGREEMENT_NOT_ACCEPTED_USER_MESSAGE } return (error && error.message) || fallbackMessage } /** * 创建挂起请求容器:保证 resolve/reject 各只生效一次,并携带 3 分钟兜底定时器。 * 结算或开始重放时统一清理引用与定时器,避免内存泄漏和后续误重放。 */ function createBlockedAgreementRequest(options, resolve, reject) { const entry = { options: cloneRequestOptions(options), settled: false, retrying: false, timer: null, startedAt: null, remainingMs: AGREEMENT_PENDING_TIMEOUT_MS } const cleanup = () => { if (entry.timer) { clearTimeout(entry.timer) entry.timer = null } entry.startedAt = null if (agreementBlockedRequest === entry) { agreementBlockedRequest = null } } /** * 启动(或恢复)超时兜底计时;已结算、已开始重放或计时已在运行时为 no-op, * 保证同一请求不会被重复计时或二次结算。 */ entry.startTimer = delay => { if (entry.settled || entry.retrying || entry.timer) { return } entry.remainingMs = delay entry.startedAt = Date.now() entry.timer = setTimeout(() => { entry.timer = null entry.startedAt = null entry.rejectNotAccepted() }, delay) } /** * 切后台时暂停计时:清除定时器并记下剩余可见时长,后台期间不会触发结算。 */ entry.pauseTimer = () => { if (!entry.timer) { return } const elapsed = Date.now() - entry.startedAt entry.remainingMs = Math.max(0, entry.remainingMs - elapsed) clearTimeout(entry.timer) entry.timer = null entry.startedAt = null } /** * 回到前台按剩余时间恢复计时;挂起请求已被结算/已取走重放时为 no-op。 */ entry.resumeTimer = () => { if (entry.settled || entry.retrying || entry.timer) { return } entry.startTimer(entry.remainingMs) } entry.resolveOnce = value => { if (entry.settled) { return } entry.settled = true cleanup() resolve(value) } entry.rejectNotAccepted = raw => { if (entry.settled) { return } entry.settled = true cleanup() reject(createAgreementNotAcceptedError(raw)) } entry.rejectOriginal = error => { if (entry.settled) { return } entry.settled = true cleanup() reject(error) } entry.takeForRetry = () => { if (entry.settled || entry.retrying) { return null } entry.retrying = true cleanup() return Object.assign(cloneRequestOptions(entry.options), { _agreementRetry: 1 }) } entry.startTimer(AGREEMENT_PENDING_TIMEOUT_MS) return entry } /** * 处理 4510:不清会话,弹窗引导用户去协议页同意。 * 新 4510 到来时先按“未完成协议同意”结算旧的挂起请求,避免堆积多个 pending。 */ function handleAgreementVersionRequired(response, options, resolve, reject) { const message = resolveResponseMessage(response, '用户协议与隐私政策已更新,请阅读并同意后继续使用') if (isAuthFreePath(options.url) || Number(options._agreementRetry) > 0) { reject(normalizeError(message, response)) return } if (agreementBlockedRequest) { agreementBlockedRequest.rejectNotAccepted(response) } agreementBlockedRequest = createBlockedAgreementRequest(options, resolve, reject) if (agreementPromptVisible) { return } agreementPromptVisible = true wx.showModal({ title: '协议版本已更新', content: message, confirmText: '查看并同意', cancelText: '稍后', success(result) { agreementPromptVisible = false if (result && result.confirm) { wx.navigateTo({ url: AGREEMENT_PAGE_URL, fail: () => wx.redirectTo({ url: AGREEMENT_PAGE_URL }) }) return } // 稍后:停留当前页,只给轻提示,不清会话;挂起请求走同一条“未同意”出口。 wx.showToast({ title: '请先同意最新协议后再操作', icon: 'none' }) discardPendingAgreement() }, fail() { agreementPromptVisible = false discardPendingAgreement() } }) } /** * 放弃当前挂起请求:用于“稍后”以及真正离开协议页(返回触发页面卸载), * 统一按“未完成协议同意”结算;切后台(onHide)不触发结算。 */ function discardPendingAgreement() { const blocked = agreementBlockedRequest if (!blocked) { return } blocked.rejectNotAccepted() } /** * 协议页切后台时调用:暂停挂起请求的超时计时,后台期间不会触发结算。 * 挂起请求已不存在(已结算/已取走重放)时为 no-op。 */ function pausePendingAgreementTimeout() { const blocked = agreementBlockedRequest if (!blocked) { return } blocked.pauseTimer() } /** * 协议页回到前台时调用:按剩余可见时长恢复计时。 * 挂起请求已不存在(例如后台期间已在别处完成同意、或被新的 4510 结算)时为 no-op, * 不会重复计时或二次结算。 */ function resumePendingAgreementTimeout() { const blocked = agreementBlockedRequest if (!blocked) { return } blocked.resumeTimer() } /** * 用户在协议页同意成功后调用:重放首个被 4510 拦下的原请求一次。 * 取走待重放请求时即清理定时器与挂起引用,后续返回/超时不会打断已开始的成功重放; * 重放会重新生成签名头(nonce/签名),不复用旧请求的一次性头; * 若重放仍失败(包括再次 4510),直接把结果交回原调用方,不再弹窗、不再重试。 */ function retryPendingAfterAgreement() { const blocked = agreementBlockedRequest if (!blocked) { return } const options = blocked.takeForRetry() if (!options) { return } request(options).then(blocked.resolveOnce, blocked.rejectOriginal) } function extractPath(value) { const target = String(value || '') if (!target) { return '' } if (/^[a-z][a-z\d+\-.]*:\/\//i.test(target)) { const match = target.match(/^[a-z][a-z\d+\-.]*:\/\/[^/]*(\/[^?#]*)?/i) return match ? (match[1] || '/') : '/' } return target.split('?')[0] || '' } function toBackendRequestPath(url) { const path = extractPath(url).replace(/\/+$/, '') || '/' if (path === '/api') { return '/' } if (path.startsWith('/api/')) { return `/${path.slice('/api/'.length)}` } return path } function isAuthFreePath(url) { return [ '/auth/login', '/auth/register', '/user/login', '/user/workbench/register/', '/user/workbench/shops/available', '/user/check/login-shops/', '/user/send-verification-code', '/user/phone-login', '/user/wechat-mini/', '/legal-agreement/current' ].some(path => String(url || '').includes(path)) } function buildSignatureHeaders(options) { const headers = {} const method = String(options.method || 'GET').toUpperCase() const accessToken = auth.getAccessToken() if (accessToken && !isAuthFreePath(options.url)) { headers.Authorization = `Bearer ${accessToken}` } if (!ENABLE_REQUEST_SIGNING || !accessToken || isAuthFreePath(options.url) || ['GET', 'HEAD', 'OPTIONS'].includes(method)) { return headers } const contentType = String((options.header && options.header['Content-Type']) || 'application/json').toLowerCase() const payload = contentType.includes('application/json') ? buildJsonPayload(options.data) : buildCanonicalParams(options.data || options.params) const timestamp = String(Date.now()) const nonce = randomNonce() const canonical = [ method, toBackendRequestPath(options.requestUrl), timestamp, nonce, sha256Hex(payload) ].join('\n') headers[HEADER_TIMESTAMP] = timestamp headers[HEADER_NONCE] = nonce headers[HEADER_SIGNATURE] = hmacSha256Hex(accessToken, canonical) headers[HEADER_SIGNATURE_VERSION] = 'v1' return headers } function request(options) { const method = String(options.method || 'GET').toUpperCase() const requestUrl = buildUrl(options.url, options.params) const signatureHeaders = buildSignatureHeaders({ url: options.url, requestUrl, method, data: options.data, params: options.params, header: options.header }) return new Promise((resolve, reject) => { wx.request({ url: requestUrl, method, timeout: options.timeout || REQUEST_TIMEOUT, data: method === 'GET' ? undefined : options.data, header: { 'Content-Type': 'application/json', ...signatureHeaders, ...(options.header || {}), 'X-Mini-Program-Env-Version': ENV_VERSION }, success(response) { if (response.statusCode === 401) { reject(handleUnauthorized(response, options.url)) return } if (response.statusCode >= 400) { reject(normalizeError((response.data && response.data.message) || '网络请求失败', response)) return } const payload = response.data if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) { if (payload.code === 200) { resolve(payload.data) return } if (Number(payload.code) === AGREEMENT_VERSION_REQUIRED_CODE) { handleAgreementVersionRequired({ data: payload }, options, resolve, reject) return } if (Number(payload.code) === 401) { reject(handleUnauthorized({ data: payload }, options.url)) return } reject(normalizeError(payload.message || '请求失败', payload)) return } resolve(payload) }, fail(error) { reject(normalizeError(`请求超时或网络异常:${method} ${requestUrl},原因:${error.errMsg || '未知错误'}`, error)) } }) }) } request.buildSignatureHeaders = buildSignatureHeaders request.toBackendRequestPath = toBackendRequestPath request.handleUnauthorized = handleUnauthorized request.retryPendingAfterAgreement = retryPendingAfterAgreement request.discardPendingAgreement = discardPendingAgreement request.pausePendingAgreementTimeout = pausePendingAgreementTimeout request.resumePendingAgreementTimeout = resumePendingAgreementTimeout request.resolveUserMessage = resolveUserMessage request.AGREEMENT_NOT_ACCEPTED_CODE = AGREEMENT_NOT_ACCEPTED_CODE module.exports = request