request.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. sourceType: isAlipay() ? '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. // params = {"userId": "8aaa809d835ba76d018378bc57180006","sourceType": "WECHAT","phoneNumber": "18521563898","projectId": "paroject1","buildingId": "QHKC-P1","brandId":"8a84853b7c91ac5b017c962dab55030e","cid": "oIUfO5XAVleJ88z13i1_08DCKIhQ","vipCode":"KERRY100200040","lbsId":"8aaa81cb7c836c6b017c83e46b110001"}
  115. if (/orders-and-prepay|calculate-discount|unlicensed-car-check-in|unlicensed-car-checkout|paper-coupon/g.test(config.url)) {
  116. params.buildingId = window.localStorage.getItem('buildingId');
  117. }
  118. const newParams = {}
  119. Object.keys(params).forEach(key => {
  120. const value = params[key]
  121. // 对特殊字段,不做过滤处理
  122. if ( value || key === 'isLogin') {
  123. newParams[key] = value
  124. }
  125. })
  126. return JSON.stringify(newParams);
  127. }
  128. function getSign(config) {
  129. let params = {}
  130. if(config.method === 'get' && config?.params) {
  131. params = config.params
  132. }
  133. if(config.method === 'post' && config?.data) {
  134. params = config.data
  135. }
  136. const newHeader = md(params, true)
  137. return newHeader
  138. }
  139. export const createAxiosByinterceptors = (config) => {
  140. const instance = axios.create({
  141. timeout: 1000000, //超时配置
  142. baseURL: `${window.profileApi}/temporary-parking-service`,
  143. // baseURL: `https://dev-kip-service-internal.kerryonvip.com/temporary-parking-service`,
  144. withCredentials: false, //跨域携带cookie
  145. xhrFields: {
  146. withCredentials: false // 允许跨域携带cookie信息
  147. },
  148. ...config, // 自定义配置覆盖基本配置
  149. });
  150. // 添加请求拦截器
  151. instance.interceptors.request.use(
  152. function (config) {
  153. // 在发送请求之前做些什么
  154. const { loading = true } = config;
  155. if (loading) addLoading();
  156. // 设置 headers
  157. config.headers = {
  158. ...config.headers,
  159. ...handleConfig().header,
  160. // ...getSign(config),
  161. // 'x-conversation-id': uuidv4(),
  162. 'Parking-User': XUser(config),
  163. 'withCredentials': 'false'
  164. };
  165. return config;
  166. },
  167. function (error) {
  168. // 对请求错误做些什么
  169. return Promise.reject(error);
  170. }
  171. );
  172. // 添加响应拦截器
  173. instance.interceptors.response.use(
  174. function (response) {
  175. // 对响应数据做点什么
  176. console.log('response:', response);
  177. const { loading = true } = response.config;
  178. if (loading) cancelLoading();
  179. const { code, data, message, langMessage } = response.data;
  180. console.log('success response', response);
  181. const codeList = ['010902']
  182. if (codeList.indexOf(code) > -1) {
  183. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  184. }
  185. // TODO: 临时注释
  186. // Promise.reject(response.data)
  187. return response.data;
  188. },
  189. function (error) {
  190. console.log('error', error);
  191. // 断网
  192. if (error.code === 'ERR_NETWORK') {
  193. uni.showToast({ title: '网络连接失败,请重试', duration: 3000, icon: 'fail' });
  194. return Promise.reject(error.code);
  195. }
  196. // 对响应错误做点什么
  197. console.log('error-response:', error.response);
  198. console.log('error-config:', error.config);
  199. console.log('error-request:', error.request);
  200. const { loading = true } = error.config || {};
  201. if (loading) cancelLoading();
  202. if (error.response) {
  203. if (error.response.status === 401) {
  204. // 跳转到登陆
  205. // jumpLogin();
  206. }
  207. }
  208. // 错误信息提示
  209. const { code, langMessage, message,status } = error.response.data;
  210. 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
  211. if (codeList.indexOf(code) > -1) {
  212. uni.showToast({ title: langMessage || message, duration: 3000, icon: 'fail' });
  213. }
  214. // 如果必填参数校验失败的话
  215. if (['BAD_USER_INFO'].indexOf(code) > -1) {
  216. backLbsHome()
  217. }
  218. if ( status === 500 ) {
  219. uni.showToast({ title: error.response.data.error, duration: 3000, icon: 'fail' });
  220. }
  221. // Message.error(error?.response?.data?.message || '服务端异常');
  222. return Promise.reject(error.response.data);
  223. }
  224. );
  225. return instance;
  226. };