request.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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 } from 'vant';
  11. // import vue from 'vue';
  12. import store from '@/store';
  13. import {backLbsHome, getsTheCurrentTopic} 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. // phoneNumber: '18521563898',
  83. phoneNumber: store.state?.mobile || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  84. // projectId: store.state.projectId || '4028e3817c2b3f79017c2b48c54c0000', // 楼盘id
  85. projectId: store.state.projectId || '', // 楼盘id
  86. brandId: store.state.groupId,
  87. // cid: '8aaa809d835ba76d018378bc57180006',
  88. cid: store.state?.openid || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  89. // vipCode: 'KERRY100213505',
  90. vipCode: store.state?.member?.vipcode || '', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  91. // vipCode: 'KERRY100213853', // 终端用户ID, 微信端传openId, 支付宝小程序传阿里userId, APP传KIP的userId
  92. // lbsId: '8aaa82ea804d07cd0180516ff03b0008',
  93. lbsId: store.state?.lbsId || '',
  94. // https://kerryprops.atlassian.net/browse/KIP-10831
  95. sourceId: store.state?.sourceId || '', // 微信:unionId; 支付宝:userId
  96. // isLogin: store.state?.member?.vipcode ? true : false
  97. isLogin: store.state?.isLogin === 'haveLoggedIn'
  98. };
  99. if(!params.isLogin) {
  100. delete params.vipCode
  101. delete params.userId
  102. delete params.phoneNumber
  103. }
  104. if(params.isLogin && (!params.vipCode || !params.userId) && config.url.indexOf('/parking-lots/') < -1) {
  105. throw {
  106. response: {
  107. data: {
  108. code:'BAD_USER_INFO'
  109. }
  110. }
  111. };
  112. }
  113. // params = {"userId": "8aaa809d835ba76d018378bc57180006","sourceType": "WECHAT","phoneNumber": "18521563898","projectId": "paroject1","buildingId": "QHKC-P1","brandId":"8a84853b7c91ac5b017c962dab55030e","cid": "oIUfO5XAVleJ88z13i1_08DCKIhQ","vipCode":"KERRY100200040","lbsId":"8aaa81cb7c836c6b017c83e46b110001"}
  114. if (/orders-and-prepay|calculate-discount|unlicensed-car-check-in|unlicensed-car-checkout|paper-coupon/g.test(config.url)) {
  115. params.buildingId = window.localStorage.getItem('buildingId');
  116. }
  117. const newParams = {}
  118. Object.keys(params).forEach(key => {
  119. const value = params[key]
  120. // 对特殊字段,不做过滤处理
  121. if ( value || key === 'isLogin') {
  122. newParams[key] = value
  123. }
  124. })
  125. return JSON.stringify(newParams);
  126. }
  127. function getSign(config) {
  128. let params = {}
  129. if(config.method === 'get' && config?.params) {
  130. params = config.params
  131. }
  132. if(config.method === 'post' && config?.data) {
  133. params = config.data
  134. }
  135. const newHeader = md(params, true)
  136. return newHeader
  137. }
  138. export const createAxiosByinterceptors = (config) => {
  139. const instance = axios.create({
  140. timeout: 1000000, //超时配置
  141. baseURL: `${window.profileApi}/temporary-parking-service`,
  142. // baseURL: `https://dev-kip-service-internal.kerryonvip.com/temporary-parking-service`,
  143. withCredentials: false, //跨域携带cookie
  144. xhrFields: {
  145. withCredentials: false // 允许跨域携带cookie信息
  146. },
  147. ...config, // 自定义配置覆盖基本配置
  148. });
  149. // 添加请求拦截器
  150. instance.interceptors.request.use(
  151. function (config) {
  152. // 在发送请求之前做些什么
  153. const { loading = true } = config;
  154. if (loading) addLoading();
  155. // 设置 headers
  156. config.headers = {
  157. ...config.headers,
  158. ...handleConfig().header,
  159. // ...getSign(config),
  160. // 'x-conversation-id': uuidv4(),
  161. 'Parking-User': XUser(config),
  162. 'withCredentials': 'false'
  163. };
  164. return config;
  165. },
  166. function (error) {
  167. // 对请求错误做些什么
  168. return Promise.reject(error);
  169. }
  170. );
  171. // 添加响应拦截器
  172. instance.interceptors.response.use(
  173. function (response) {
  174. // 对响应数据做点什么
  175. console.log('response:', response);
  176. const { loading = true } = response.config;
  177. if (loading) cancelLoading();
  178. const { code, data, message, langMessage } = response.data;
  179. console.log('success response', response);
  180. const codeList = ['010902']
  181. if (codeList.indexOf(code) > -1) {
  182. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  183. }
  184. // TODO: 临时注释
  185. // Promise.reject(response.data)
  186. return response.data;
  187. },
  188. function (error) {
  189. console.log('error', error);
  190. // 断网
  191. if (error.code === 'ERR_NETWORK') {
  192. uni.showToast({ title: '网络连接失败,请重试', duration: 3000, icon: 'fail' });
  193. return Promise.reject(error.code);
  194. }
  195. // 对响应错误做点什么
  196. console.log('error-response:', error.response);
  197. console.log('error-config:', error.config);
  198. console.log('error-request:', error.request);
  199. const { loading = true } = error.config || {};
  200. if (loading) cancelLoading();
  201. if (error.response) {
  202. if (error.response.status === 401) {
  203. // 跳转到登陆
  204. // jumpLogin();
  205. }
  206. }
  207. // 错误信息提示
  208. const { code, langMessage, message,status } = error.response.data;
  209. 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' ]; // 默认处理的错误code
  210. if (codeList.indexOf(code) > -1) {
  211. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  212. }
  213. // 如果必填参数校验失败的话
  214. if (['BAD_USER_INFO'].indexOf(code) > -1) {
  215. backLbsHome()
  216. }
  217. if ( status === 500 ) {
  218. uni.showToast({ title: error.response.data.error, duration: 3000, icon: 'fail' });
  219. }
  220. // Message.error(error?.response?.data?.message || '服务端异常');
  221. return Promise.reject(error.response.data);
  222. }
  223. );
  224. return instance;
  225. };