接口修改

This commit is contained in:
weiwei committed 2025-02-07 13:50:20 +08:00
1 parent 4452435ecf
commit 7ba2bfce2b
5 files changed
+6022 -4833

No files matched your search

+6 -3
View File
@@ -21,7 +21,8 @@ VITE_OAUTH2_APP_CLIENT='mini:mini'
# VITE_IMAGE_BASE_PATH = http://192.168.101.29:9999 # 邓-本地
# VITE_IMAGE_BASE_PATH = http://192.168.101.37:9999 # 邓-本地
# VITE_IMAGE_BASE_PATH = https://123.156.230.15:8089/api # 线上
VITE_IMAGE_BASE_PATH = https://stgl.pj.gov.cn/api # 线上
VITE_IMAGE_BASE_PATH = http://220.191.229.171:8090/api # 线上
# VITE_IMAGE_BASE_PATH = https://stgl.pj.gov.cn/api # 线上
# VITE_IMAGE_BASE_PATH = http://pjcloud.center.takin.cc # 张
# VITE_IMAGE_BASE_PATH = http://59.202.170.152:81/api # 信创线上
@@ -31,14 +32,16 @@ VITE_IMAGE_BASE_PATH = https://stgl.pj.gov.cn/api # 线上
# VITE_APP_DEV_SERVICE = http://192.168.101.29:9999 # 邓-本地
# VITE_APP_DEV_SERVICE = http://192.168.101.37:9999 # 邓-本地
# VITE_APP_DEV_SERVICE = http://127.0.0.1:9999
VITE_APP_DEV_SERVICE = http://123.156.230.15:8089/api/ # 线上
# VITE_APP_DEV_SERVICE = http://123.156.230.15:8089/api/ # 线上
VITE_APP_DEV_SERVICE = http://220.191.229.171:8090/api # 线上
# VITE_APP_DEV_SERVICE = http://localhost:9999
# ******************** end 开发环境 end ********************
# ******************** start 生产环境 start ****************
#VITE_APP_PROD_SERVICE = http://123.156.228.134:48080/app-api
#VITE_APP_PROD_SERVICE = http://59.202.170.152:81/api
VITE_APP_PROD_SERVICE = https://stgl.pj.gov.cn/api
# VITE_APP_PROD_SERVICE = https://stgl.pj.gov.cn/api
VITE_APP_PROD_SERVICE = http://220.191.229.171:8090/api
# ******************** end 生产环境 end ********************
# VITE_DEV_ENV = dev
VITE_DEV_ENV = prod
+5735 -4672
View File
File diff suppressed because it is too large. Load diff
+66 -37
View File
@@ -9,51 +9,80 @@ import { hooks, router, constant } from "@@/index"
import { merchantApi, userApi, walletApi } from "@@/api"
import isDevEnv from "@/sheep/utils/isDevEnv"
const data = {
serviceList: [
{ text: "钱包管理", icon: "/static/icon/service_3.png", router: "/pages/wallet/list" },
{ text: "包厢预定", icon: "/static/icon/service_4.png", router: "/pages/boxes/apply-list" },
{ text: "外来人员就餐", icon: "/static/icon/service_1.png", router: "/pages/apply/foreign-list" },
{ text: "跨单位就餐", icon: "/static/icon/service_1.png", router: "/pages/apply/stride-list" },
{ text: "人脸管理", icon: "/static/icon/service_5.png", router: "/pages/human-face/list" },
],
// 定义类型
interface ServiceItem {
text: string
icon: string
router: string
}
// 服务列表配置
const DEFAULT_SERVICES: ServiceItem[] = [
{ text: "钱包管理", icon: "/static/icon/service_3.png", router: "/pages/wallet/list" },
{ text: "包厢预定", icon: "/static/icon/service_4.png", router: "/pages/boxes/apply-list" },
{ text: "外来人员就餐", icon: "/static/icon/service_1.png", router: "/pages/apply/foreign-list" },
{ text: "跨单位就餐", icon: "/static/icon/service_1.png", router: "/pages/apply/stride-list" },
{ text: "人脸管理", icon: "/static/icon/service_5.png", router: "/pages/human-face/list" },
]
// 状态管理
const state = reactive<any>({
wallet: [],
userInfo: {},
serviceList: [...DEFAULT_SERVICES],
})
// 开发环境可以账号密码登录,生产环境不可
const checkAppInfo = () => {
;(window as any).CP2.getAppInfo().then((res) => {
if (res.code == 1) {
//诗画
console.log("诗画环境")
;(window as any).CP2.getUserInfo().then((res) => {
let accountId = res.data.accountId
let sessionId = res.sessionId
doLogin(1, null, accountId, sessionId)
})
} else {
console.log("浙政钉或者h5环境")
const url = window.location.href
const params = new URL(url).searchParams
const token = params.get("uabaseToken") // 获取 uabaseToken 参数值
// const token =
// "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjJiZGQzODE1LWFlMWYtNDFmZi04MTE2LTU3OWVkMjY3MDI5OCJ9.nuCBrYAkGh5-FG8S_ZTe8mcVVORAuUT7bl0qUIspL9gCNtwtcae2D6DhOO8Q2RtVhuFO5IKtOQ65Xd2Vd7pAUg"
console.log("uabaseToken:", token)
if (null != token) {
//浙政钉
doLogin(2, token, null, null)
}
// 登录相关方法
const loginMethods = {
// 诗画环境登录
async shihuaLogin() {
const appInfo = await (window as any).CP2.getAppInfo()
if (appInfo.code !== 1) return false
const userInfo = await (window as any).CP2.getUserInfo()
const { accountId, sessionId } = userInfo.data
return doLogin(1, null, accountId, sessionId)
},
// 浙政钉登录
zhengdingLogin() {
const params = new URL(window.location.href).searchParams
const token = params.get("uabaseToken")
if (token) {
return doLogin(2, token, null, null)
}
})
return false
},
}
onLoad((options) => {
// 检查应用环境并登录
const checkAppInfo = async () => {
try {
// 先尝试诗画登录
const shihuaResult = await loginMethods.shihuaLogin()
if (shihuaResult) return
// 尝试浙政钉登录
const zhengdingResult = await loginMethods.zhengdingLogin()
if (zhengdingResult) return
// 开发环境下跳转到测试登录页
if (isDevEnv()) {
router.jump("/pages/test/login")
}
} catch (error) {
console.error("登录失败:", error)
uni.showToast({ title: "登录失败", icon: "none" })
}
}
onLoad(() => {
if (isDevEnv()) {
data.serviceList.push({ text: "测试登录", icon: "/static/icon/login.png", router: "/pages/test/login" })
state.serviceList.push({
text: "测试登录",
icon: "/static/icon/login.png",
router: "/pages/test/login",
})
}
checkAppInfo()
})
@@ -125,7 +154,7 @@ const doLogin = async (loginType, token, accountId, sessionId) => {
uni.setStorageSync(userInfoKey, userData)
getUserInfo()
uni.hideLoading()
uni.showToast({ title: "登录成功", icon: "none" })
// uni.showToast({ title: "登录成功", icon: "none" })
} catch (error) {
uni.hideLoading()
uni.showToast({ title: "登录失败", icon: "none" })
@@ -134,7 +163,7 @@ const doLogin = async (loginType, token, accountId, sessionId) => {
}
const toService = async (v: any, i: number) => {
if (i == data.serviceList.length - 1) {
if (i == state.serviceList.length - 1) {
router.jump(v.router)
return
}
@@ -195,7 +224,7 @@ const onTabLogin = () => {
<view class="m-t-40rpx rounded-20rpx shadow-main p-30rpx p-b-40rpx bg-white!">
<view
class="service_item flex-row items-center justify-between"
v-for="(v, i) in data.serviceList"
v-for="(v, i) in state.serviceList"
:key="i"
@tap="toService(v, i)"
>
+29 -10
View File
@@ -1,9 +1,21 @@
import request from "@/sheep/utils/request"
import { encryption } from "@/sheep/utils/encryption"
const basicAuth = "Basic " + window.btoa(import.meta.env.VITE_OAUTH2_APP_CLIENT)
// 将 Basic Auth 字符串提取为常量
const BASIC_AUTH = "Basic " + window.btoa(import.meta.env.VITE_OAUTH2_APP_CLIENT)
// 定义接口类型
interface LoginParams {
username: string
password: string
randomStr: string
code: string
grant_type: string
scope: string
}
export default {
// 获取用户信息
userInfo: () =>
request({
url: "/admin/user/info",
@@ -14,17 +26,19 @@ export default {
},
}),
auth: (str: any) =>
// 浙政钉授权
auth: (token: string) =>
request({
// url: `/sys/auth/zzdsso/${str}`,
url: `/thirdparty/thirdPartyOAth2/zzdsso/${str}`,
url: `/thirdparty/thirdPartyOAth2/zzdsso/${token}`,
method: "GET",
custom: {
showLoading: false,
loadingMsg: "授权中",
},
}),
authsh: (params: any) =>
// 诗画授权
authsh: (params: { accountId: string; sessionId: string }) =>
request({
url: `/sys/auth/shjnsso`,
method: "POST",
@@ -34,7 +48,9 @@ export default {
},
data: params,
}),
refreshToken: (params: any) =>
// 刷新token
refreshToken: (params: { refreshToken: string }) =>
request({
url: `/sys/auth/refresh-token`,
method: "POST",
@@ -43,24 +59,27 @@ export default {
showLoading: false,
},
}),
login: (params: any): any => {
// 登录
login: (params: LoginParams) => {
const { username, password, randomStr, code, grant_type, scope } = params
const encPassword = encryption(password, import.meta.env.VITE_PWD_ENC_KEY)
return request({
url: `/auth/oauth2/token`,
method: "POST",
params: {
username,
password: password,
password,
randomStr,
code,
grant_type,
scope,
},
data: { password: password },
data: { password },
header: {
skipToken: true,
Authorization: basicAuth,
Authorization: BASIC_AUTH,
"content-type": "application/x-www-form-urlencoded",
},
custom: {
+186 -111
View File
@@ -5,8 +5,19 @@ import { userApi } from "@@/api"
import { router, constant } from "@@/index"
import isDevEnv from "./isDevEnv"
const options = {
// 显示操作成功消息 默认不显示
// 定义常量
const TOKEN_KEY = constant.storageConstant.TOKEN
const USER_INFO_KEY = constant.storageConstant.USERINFO
const REFRESH_TOKEN_URL = "/auth/oauth2/token?grant_type=refresh_token"
// 定义类型
interface LoadingInstance {
target: any
count: number
}
// 默认请求配置
const defaultOptions = {
showSuccess: false,
// 成功提醒 默认使用后端返回值
successMsg: "",
@@ -22,16 +33,19 @@ const options = {
auth: false,
}
let LoadingInstance = {
// Loading 管理
const LoadingInstance: LoadingInstance = {
target: null,
count: 0,
}
// 关闭 loading
function closeLoading() {
if (LoadingInstance.count > 0) LoadingInstance.count--
if (LoadingInstance.count === 0) uni.hideLoading()
}
// 创建请求实例
const http = new Request({
baseURL: import.meta.env.VITE_API_URL,
timeout: 8000,
@@ -41,61 +55,122 @@ const http = new Request({
"Content-Type": "application/json;charset=UTF-8",
},
withCredentials: true,
custom: options,
custom: defaultOptions,
})
http.interceptors.request.use(
(config) => {
const tokenKey = constant.storageConstant.TOKEN
const tokenStorage = uni.getStorageSync(tokenKey)
const config_header: any = config?.header
// 添加终端类型
const isToc = import.meta.env.VITE_IS_TOC
if (isToc === "true") {
config_header["CLIENT-TOC"] = "Y"
}
config_header["TENANT-ID"] = "1"
if (
config.url != "/sys/auth/refresh-token" &&
tokenStorage &&
tokenStorage.access_token &&
config_header &&
isDevEnv()
) {
config_header.Authorization = `Bearer ${tokenStorage.access_token}`
}
if (
config.url != "/sys/auth/refresh-token" &&
tokenStorage &&
tokenStorage.accessToken &&
config_header &&
!isDevEnv()
) {
console.log("aaaa", tokenStorage)
// 处理请求头 Authorization
const getAuthHeader = (tokenStorage: any) => {
if (isDevEnv()) {
return tokenStorage?.access_token ? `Bearer ${tokenStorage.access_token}` : null
}
return tokenStorage?.accessToken?.tokenValue ? `Bearer ${tokenStorage.accessToken.tokenValue}` : null
}
config_header.Authorization = `Bearer ${tokenStorage.accessToken.tokenValue}`
// 请求拦截器
http.interceptors.request.use((config) => {
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
const config_header: any = config?.header || {}
// 设置通用请求头
config_header["TENANT-ID"] = "1"
if (import.meta.env.VITE_IS_TOC === "true") {
config_header["CLIENT-TOC"] = "Y"
}
// 设置认证头
if (config.url !== "/sys/auth/refresh-token") {
const authHeader = getAuthHeader(tokenStorage)
if (authHeader) {
config_header.Authorization = authHeader
}
if (config.custom && config.custom.showLoading) {
LoadingInstance.count++
LoadingInstance.count === 1 &&
uni.showLoading({
title: config.custom.loadingMsg,
}
// 处理 loading
if (config.custom?.showLoading) {
LoadingInstance.count++
if (LoadingInstance.count === 1) {
uni.showLoading({
title: config.custom.loadingMsg,
mask: true,
fail: () => uni.hideLoading(),
})
}
}
return config
}, Promise.reject)
// 定义响应处理的辅助函数
const responseHelpers = {
// 处理错误响应
handleErrorResponse(response: any) {
if (!response.config?.custom?.showError) return
switch (response.data.code) {
case 401:
this.handleUnauthorized()
break
default:
uni.showToast({
title: response.data.msg || "服务器开小差啦,请稍后再试~",
icon: "none",
mask: true,
fail: () => {
uni.hideLoading()
},
})
}
return config
},
(error) => {
return Promise.reject(error)
},
)
// 处理未授权情况
handleUnauthorized() {
setTimeout(() => {
uni.removeStorageSync(TOKEN_KEY)
uni.removeStorageSync(USER_INFO_KEY)
router.jump("/pages/tabbar/my", {}, 2)
}, 500)
},
// 处理成功提示
handleSuccessMessage(response: any) {
const { data, config } = response
if (data.code === 200 && data.message && config?.custom?.showSuccess) {
uni.showToast({
title: config.custom.successMsg || data.message,
icon: "none",
})
}
},
// 处理登录过期
handleLoginExpired() {
uni.removeStorageSync(TOKEN_KEY)
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
router.jump("/pages/test/login")
},
// 检查并刷新token
async checkAndRefreshToken(tokenStorage: any) {
const { refresh_token, expiresTime } = tokenStorage
if (!refresh_token || !expiresTime) return
const now = new Date().getTime()
const remain = expiresTime - now
if (remain <= 1000 * 60 * 20) {
const refreshData = await userApi.refreshToken({ refreshToken: refresh_token })
if (!isEmpty(refreshData.data)) {
uni.setStorageSync(TOKEN_KEY, refreshData.data)
}
}
},
}
// 响应拦截器
http.interceptors.response.use(
async (response) => {
response.config && response.config.custom && response.config.custom.showLoading && closeLoading()
// 关闭loading
if (response.config?.custom?.showLoading) {
closeLoading()
}
// OAuth2 token请求特殊处理
if (response.config.url === "/auth/oauth2/token") {
return Promise.resolve({
code: 0,
@@ -103,83 +178,83 @@ http.interceptors.response.use(
msg: null,
})
}
// 错误处理
if (response.data.code !== 0) {
if (response.config && response.config.custom && response.config.custom.showError) {
switch (response.data.code) {
case 401:
setTimeout(() => {
const tokenKey = constant.storageConstant.TOKEN
const userInfoKey = constant.storageConstant.USERINFO
uni.removeStorageSync(tokenKey)
uni.removeStorageSync(userInfoKey)
router.jump("/pages/tabbar/my", {}, 2)
}, 500)
break
default:
uni.showToast({
title: response.data.msg || "服务器开小差啦,请稍后再试~",
icon: "none",
mask: true,
})
break
}
return Promise.resolve(response.data)
}
}
if (
response.data.code === 200 &&
response.data.message !== "" &&
response.config &&
response.config.custom &&
response.config.custom.showSuccess
) {
uni.showToast({
title: response.config.custom.successMsg || response.data.message,
icon: "none",
})
responseHelpers.handleErrorResponse(response)
return Promise.resolve(response.data)
}
// 成功提示
responseHelpers.handleSuccessMessage(response)
// 登录过期处理
if (response.data.code === 1) {
const tokenKey = constant.storageConstant.TOKEN
uni.removeStorageSync(tokenKey)
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
router.jump("/pages/test/login")
responseHelpers.handleLoginExpired()
}
const tokenKey = constant.storageConstant.TOKEN
const tokenStorage = uni.getStorageSync(tokenKey)
if (!isEmpty(tokenStorage) && response.config.url != "/sys/auth/refresh-token") {
const { refresh_token, expiresTime } = tokenStorage
if (!isEmpty(refresh_token) && !isEmpty(expiresTime)) {
const now = new Date().getTime()
const remain = expiresTime - now
if (remain <= 1000 * 60 * 20) {
const _pa = { refreshToken: refresh_token }
const refreshData = await userApi.refreshToken(_pa)
if (!isEmpty(refreshData.data)) {
uni.setStorageSync(tokenKey, refreshData.data)
}
}
}
// Token 刷新检查
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
if (!isEmpty(tokenStorage) && response.config.url !== "/sys/auth/refresh-token") {
await responseHelpers.checkAndRefreshToken(tokenStorage)
}
return Promise.resolve(response.data)
},
(error) => {
if (error.statusCode == 424 && isDevEnv()) {
const tokenKey = constant.storageConstant.TOKEN
const userInfoKey = constant.storageConstant.USERINFO
uni.removeStorageSync(tokenKey)
uni.removeStorageSync(userInfoKey)
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
isDevEnv() ? router.jump("/pages/test/login") : undefined
return false
// 错误拦截器
async (error) => {
// 处理 424 错误(token过期)
if (error.statusCode === 424) {
const tokenStorage = uni.getStorageSync(TOKEN_KEY)
if (isDevEnv()) {
// 开发环境直接清除token并跳转登录
uni.removeStorageSync(TOKEN_KEY)
uni.removeStorageSync(USER_INFO_KEY)
uni.showToast({ title: "登录已过期,请重新登录", icon: "none" })
router.jump("/pages/test/login")
return false
}
// 生产环境尝试刷新token
if (tokenStorage?.refreshToken?.tokenValue) {
try {
const refreshData = await request({
url: REFRESH_TOKEN_URL,
method: "POST",
data: JSON.stringify({
scope: "server",
refresh_token: tokenStorage.refreshToken.tokenValue,
}),
header: {
Authorization: "Basic " + window.btoa(import.meta.env.VITE_OAUTH2_APP_CLIENT),
"content-type": "application/x-www-form-urlencoded",
},
})
if (refreshData.code === 0) {
// 刷新成功,更新token并重试请求
uni.setStorageSync(TOKEN_KEY, refreshData.data)
const config = error.config
config.header!.Authorization = `Bearer ${refreshData.data.accessToken.tokenValue}`
return http.request(config)
}
} catch (refreshError) {
console.error("Token refresh failed:", refreshError)
}
}
}
let errorMessage = error.data.msg
if (error !== undefined) {
// 显示错误信息
if (error?.data?.msg) {
uni.showToast({
title: errorMessage || "",
title: error.data.msg,
icon: "none",
mask: true,
})
}
return false
},
)