Files
JayuCloud/JC-Salon-WeChat/utils/request.js
T
xiaowang fb19fcf05f
自动发布开发环境 Nacos 配置 / publish (push) Successful in 18s
feat(salon): 服务端拦截未同意最新协议的用户并补充端侧 4510 处理
2026-11-05 09:43:01 +08:00

239 lines
7.2 KiB
JavaScript

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
let agreementPrompting = false
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
}
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)
}
/**
* 处理 4510:提示协议已更新并跳转登录页重新阅读同意。
* 登录页已有协议勾选与弹层,重新登录时会带上最新版本同意,避免重复弹窗用 agreementPrompting 去重。
*/
function handleAgreementVersionRequired(response, url) {
const message = resolveResponseMessage(response, '用户协议与隐私政策已更新,请阅读并同意后继续使用')
if (isAuthFreePath(url)) {
return normalizeError(message, response)
}
if (!agreementPrompting) {
agreementPrompting = true
clearRuntimeSession()
wx.showModal({
title: '协议版本已更新',
content: message,
showCancel: false,
confirmText: '去同意',
success() {
agreementPrompting = false
wx.reLaunch({
url: '/pages/login/index'
})
},
fail() {
agreementPrompting = false
}
})
}
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') {
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) {
reject(handleAgreementVersionRequired({ data: payload }, options.url))
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
module.exports = request