request.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. import uni from '@/utils/uniHooks';
  2. import { getUTMSource } from '@/utils/utils';
  3. import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
  4. import { md } from '@/utils/common'
  5. // import { Message } from 'element-ui';
  6. // import { jumpLogin } from '@/utils';
  7. // import { Loading } from 'element-ui';
  8. // import { ElLoadingComponent } from 'element-ui/types/loading';
  9. // import vm from "@/main";
  10. import { Toast, Dialog, Switch } from 'vant';
  11. // import vue from 'vue';
  12. import store from '@/store';
  13. import { backLbsHome, getsTheCurrentTopic, toLogin } from "@/utils";
  14. import kipTheme from '@/kui/theme/theme'
  15. // import { v4 as uuidv4 } from 'uuid';
  16. // import { wxToLoginCallback } from '@/utils/index.js'
  17. let loadingInstance = null;
  18. let requestNum = 0;
  19. const CONTENT_TYPE_ARRAY = {
  20. json: 'application/json',
  21. form: 'application/x-www-form-urlencoded',
  22. };
  23. function getHeaders(config = {}) {
  24. const { contentType = 'json' } = config;
  25. const ct = CONTENT_TYPE_ARRAY[contentType];
  26. let header = {
  27. // appId: uni.getStorageSync('appid'),
  28. // appId: 'wx92c3e55fbef6b2af',
  29. // 'Content-Type': ct,
  30. };
  31. const token = getToken();
  32. if (token) {
  33. header['Authorization'] = `Bearer ${token}`;
  34. }
  35. const groupId = uni.getStorageSync('groupId');
  36. const mallId = uni.getStorageSync('mallid');
  37. // if (groupId) {
  38. // header['brandId'] = groupId;
  39. // }
  40. // if (mallId) {
  41. // header['lbsId'] = mallId;
  42. // }
  43. const sourceObj = getUTMSource();
  44. return Object.assign(header, sourceObj);
  45. }
  46. function handleConfig(config = {}) {
  47. const header = getHeaders(config);
  48. const noToken = config.noToken;
  49. if (noToken) {
  50. delete header.Authorization;
  51. }
  52. return { header, ...config };
  53. }
  54. function getToken() {
  55. const token = uni.getStorageSync('kipAccessToken');
  56. // if (!token || token?.trim() == '' || token == 'null' || token == 'undefined') {
  57. if (!token || token == 'null' || token == 'undefined') {
  58. return false;
  59. }
  60. return token;
  61. }
  62. const addLoading = () => {
  63. // 增加loading 如果pending请求数量等于1,弹出loading, 防止重复弹出
  64. requestNum++;
  65. if (requestNum === 1) {
  66. // 展示加载中的状态
  67. loadingInstance = Toast.loading({
  68. message: '正在努力加载中....',
  69. });
  70. }
  71. };
  72. const cancelLoading = () => {
  73. // 取消loading 如果pending请求数量等于0,关闭loading
  74. requestNum--;
  75. if (requestNum === 0) loadingInstance?.clear();
  76. };
  77. function XUser(config) {
  78. let params = {
  79. userId: store.state?.kipUserId || '', // K+用户ID
  80. // userId: '2c9d85868652dee50186532bdbbb0001', // K+用户ID
  81. // sourceType: 'WECHAT',
  82. sourceType: isAlipayClient ? 'ALIPAY' : 'WECHAT',
  83. // phoneNumber: '18521563898',
  84. phoneNumber: store.state?.mobile || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  85. // projectId: store.state.projectId || '4028e3817c2b3f79017c2b48c54c0000', // 楼盘id
  86. projectId: store.state.projectId || '', // 楼盘id
  87. brandId: store.state.groupId,
  88. // cid: '8aaa809d835ba76d018378bc57180006',
  89. cid: store.state?.openid || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  90. // vipCode: 'KERRY100213505',
  91. vipCode: store.state?.member?.vipcode || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  92. // vipCode: 'KERRY100213853', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  93. // lbsId: '8aaa82ea804d07cd0180516ff03b0008',
  94. lbsId: store.state?.lbsId || '',
  95. // https://kerryprops.atlassian.net/browse/KIP-10831
  96. sourceId: store.state?.sourceId || '', // 微信:unionId; 支付宝:userId
  97. // isLogin: store.state?.member?.vipcode ? true : false
  98. isLogin: store.state?.isLogin === 'haveLoggedIn'
  99. };
  100. if (!params.isLogin) {
  101. delete params.vipCode
  102. delete params.userId
  103. delete params.phoneNumber
  104. }
  105. if (params.isLogin && (!params.vipCode || !params.userId) && config.url.indexOf('/parking-lots/') < -1) {
  106. throw {
  107. response: {
  108. data: {
  109. code: 'BAD_USER_INFO'
  110. }
  111. }
  112. };
  113. }
  114. // 如果 token 存在, 但是没有 vipCode 或者 userId
  115. const kipAccessToken =uni.getStorageSync('kipAccessToken')
  116. if (kipAccessToken && (!params.vipCode || !params.userId) && config.url.indexOf('/parking-lots/') < -1) {
  117. throw {
  118. response: {
  119. data: {
  120. message: '当前登录失效,请重新登录',
  121. code: 'BAD_USER_INFO_2'
  122. }
  123. }
  124. };
  125. }
  126. // params = {"userId": "8aaa809d835ba76d018378bc57180006","sourceType": "WECHAT","phoneNumber": "18521563898","projectId": "paroject1","buildingId": "QHKC-P1","brandId":"8a84853b7c91ac5b017c962dab55030e","cid": "oIUfO5XAVleJ88z13i1_08DCKIhQ","vipCode":"KERRY100200040","lbsId":"8aaa81cb7c836c6b017c83e46b110001"}
  127. if (/orders-and-prepay|calculate-discount|unlicensed-car-check-in|unlicensed-car-checkout|paper-coupon/g.test(config.url)) {
  128. params.buildingId = window.localStorage.getItem('buildingId');
  129. }
  130. const newParams = {}
  131. Object.keys(params).forEach(key => {
  132. const value = params[key]
  133. // 对特殊字段,不做过滤处理
  134. if (value || key === 'isLogin') {
  135. newParams[key] = value
  136. }
  137. })
  138. return JSON.stringify(newParams);
  139. }
  140. function getSign(config) {
  141. let params = {}
  142. if (config.method === 'get' && config?.params) {
  143. params = config.params
  144. }
  145. if (config.method === 'post' && config?.data) {
  146. params = config.data
  147. }
  148. const newHeader = md(params, true)
  149. return newHeader
  150. }
  151. export const createAxiosByinterceptors = (config) => {
  152. const instance = axios.create({
  153. timeout: 1000000, //超时配置
  154. baseURL: `${window.profileApi}/temporary-parking-service`,
  155. // baseURL: `https://dev-kip-service-internal.kerryonvip.com/temporary-parking-service`,
  156. withCredentials: false, //跨域携带cookie
  157. xhrFields: {
  158. withCredentials: false // 允许跨域携带cookie信息
  159. },
  160. ...config, // 自定义配置覆盖基本配置
  161. });
  162. // 添加请求拦截器
  163. instance.interceptors.request.use(
  164. function (config) {
  165. // 在发送请求之前做些什么
  166. const { loading = true } = config;
  167. if (loading) addLoading();
  168. // 设置 headers
  169. config.headers = {
  170. ...config.headers,
  171. ...handleConfig().header,
  172. // ...getSign(config),
  173. // 'x-conversation-id': uuidv4(),
  174. 'Parking-User': XUser(config),
  175. 'withCredentials': 'false'
  176. };
  177. return config;
  178. },
  179. function (error) {
  180. // 对请求错误做些什么
  181. return Promise.reject(error);
  182. }
  183. );
  184. // 添加响应拦截器
  185. instance.interceptors.response.use(
  186. function (response) {
  187. // 对响应数据做点什么
  188. // console.log('response:', response);
  189. const { loading = true } = response.config;
  190. if (loading) cancelLoading();
  191. const { code, data, message = '', langMessage = '' } = response.data;
  192. // console.log('success response', response);
  193. const codeList = ['010902', '300000', '500001', '500000']
  194. if (codeList.indexOf(code) > -1) {
  195. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  196. // console.log('193193193193193193', '193');
  197. setTimeout(() => {
  198. switch (code) {
  199. case '300000':
  200. toLogin()
  201. break
  202. case '500001':
  203. toLogin()
  204. break
  205. case '500000':
  206. toLogin()
  207. break
  208. }
  209. }, 1500)
  210. console.log('206206206206206206206', '206');
  211. }
  212. // TODO: 临时注释
  213. // Promise.reject(response.data)
  214. return response.data;
  215. },
  216. function (error) {
  217. console.log('error', error);
  218. // 断网
  219. if (error.code === 'ERR_NETWORK') {
  220. uni.showToast({ title: '网络连接失败,请重试', duration: 3000, icon: 'fail' });
  221. return Promise.reject(error.code);
  222. }
  223. // 对响应错误做点什么
  224. console.log('error-response:', error.response);
  225. console.log('error-config:', error.config);
  226. console.log('error-request:', error.request);
  227. const { loading = true } = error.config || {};
  228. if (loading) cancelLoading();
  229. if (error.response) {
  230. if (error.response.status === 401) {
  231. // 跳转到登陆
  232. // jumpLogin();
  233. }
  234. }
  235. // 错误信息提示
  236. const { code, langMessage = '', message = '', status } = error.response.data;
  237. const codeList = ['INTERNAL_SERVER_ERROR', 'VALIDATION_FAILED', 'CAR_HAS_PLATE', "NOT_FOUND", "LOCAL_PARK_ERROR", "LOCK_OCCUPIED", "REMOTE_CALL_FAIL", 'PLEASE_SCAN_QRCODE', 'SUBIN_CAR_IN_DEVICE_EXCEPTION', 'COUPON_UNAVAILABLE', 'COUPON_SELECTION_FAILED', 'NEED_REFRESHING_PARKING_FEE', 'LOCK_OCCUPIED']; // 默认处理的错误code
  238. if (codeList.indexOf(code) > -1) {
  239. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  240. }
  241. // 如果必填参数校验失败的话
  242. if (['BAD_USER_INFO'].indexOf(code) > -1) {
  243. backLbsHome()
  244. }
  245. // 如果必填参数校验失败的话
  246. if (['BAD_USER_INFO_2'].indexOf(code) > -1) {
  247. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  248. setTimeout(() => {
  249. toLogin()
  250. }, 1500)
  251. }
  252. if (status === 500) {
  253. uni.showToast({ title: error.response.data.error, duration: 3000, icon: 'fail' });
  254. }
  255. // Message.error(error?.response?.data?.message || '服务端异常');
  256. return Promise.reject(error.response.data);
  257. }
  258. );
  259. return instance;
  260. };