const { ADMIN_API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config') const auth = require('./auth') const { getDeviceId } = require('./device') const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto') const DEVICE_ID_HEADER = 'X-Device-Id' const HEADER_TIMESTAMP = 'X-Timestamp' const HEADER_NONCE = 'X-Nonce' const HEADER_SIGNATURE = 'X-Signature' const HEADER_SIGNATURE_VERSION = 'X-Sign-Version' let sessionExpiredHandling = false function buildUrl(url, params) { const sourceParams = params || {} const baseUrl = sourceParams.__baseUrl ? sourceParams.__baseUrl : ADMIN_API_BASE_URL 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 (sessionExpiredHandling) { return } sessionExpiredHandling = true clearRuntimeSession() wx.showToast({ title: message, icon: 'none', duration: 1200 }) setTimeout(() => { wx.reLaunch({ url: '/pages/login/index', complete() { sessionExpiredHandling = false } }) }, 700) } function handleUnauthorized(response) { const message = resolveResponseMessage(response, '登录已过期,请重新登录') redirectToLoginAfterExpired(message) return normalizeError(message, response) } 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/admin') { return '/admin' } if (path.startsWith('/api/admin/')) { return `/admin/${path.slice('/api/admin/'.length)}` } if (path === '/api') { return '/' } if (path.startsWith('/api/')) { return `/${path.slice('/api/'.length)}` } if (path === '/admin/api') { return '/admin' } if (path.startsWith('/admin/api/')) { return `/admin/${path.slice('/admin/api/'.length)}` } if (path === '/admin' || path.startsWith('/admin/')) { return path } return path.startsWith('/') ? `/admin${path}` : `/admin/${path}` } function isAuthFreePath(url) { return [ '/auth/login', '/auth/register', '/user/send-verification-code', '/user/phone-login', '/user/check/login-shops/', '/legal-agreement/current' ].some(path => String(url || '').includes(path)) } function buildSignatureHeaders(options) { const headers = { [DEVICE_ID_HEADER]: getDeviceId() } 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 || {}) }, success(response) { if (response.statusCode === 401) { reject(handleUnauthorized(response)) 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 (payload.code === 401) { reject(handleUnauthorized({ data: payload })) return } reject(normalizeError(payload.message || '请求失败', payload)) return } resolve(payload) }, fail(error) { reject(normalizeError(`请求超时或网络异常:${method} ${requestUrl},原因:${error.errMsg || '未知错误'}`, error)) } }) }) } request.buildSignatureHeaders = buildSignatureHeaders request.toBackendRequestPath = toBackendRequestPath module.exports = request