request-kip.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import { APPID, SOURCE_KEY } from '@/constants.js';
  2. import CacheTool from '@/utils/cache-tool.js';
  3. import log from './log.js';
  4. import { getUTMSource } from '@/utils/utils.js';
  5. import uni from './uniHooks';
  6. const CONTENT_TYPE_ARRAY = {
  7. json: 'application/json',
  8. form: 'application/x-www-form-urlencoded',
  9. };
  10. function getHeaders(config = {}) {
  11. const { contentType = 'json' } = config;
  12. const ct = CONTENT_TYPE_ARRAY[contentType];
  13. let header = {
  14. appId: uni.getStorageSync('appid'),
  15. 'Content-Type': ct,
  16. };
  17. const token = getToken();
  18. if (token) {
  19. header['Authorization'] = `Bearer ${token}`;
  20. }
  21. const groupId = uni.getStorageSync('groupId');
  22. const mallId = uni.getStorageSync('mallid');
  23. if (groupId) {
  24. header['brandId'] = groupId;
  25. }
  26. if (mallId) {
  27. header['lbsId'] = mallId;
  28. }
  29. const sourceObj = getUTMSource();
  30. return Object.assign(header, sourceObj);
  31. }
  32. function handleConfig(config = {}) {
  33. const header = getHeaders(config);
  34. const noToken = config.noToken;
  35. if (noToken) {
  36. delete header.Authorization;
  37. }
  38. return { header, ...config };
  39. }
  40. function getToken() {
  41. const token = uni.getStorageSync('kipAccessToken');
  42. // if (!token || token?.trim() == '' || token == 'null' || token == 'undefined') {
  43. if (!token || token == 'null' || token == 'undefined') {
  44. return false;
  45. }
  46. return token;
  47. }
  48. function getUrl(path) {
  49. console.log(555555555, path);
  50. // 如果是dev、qa、prod环境
  51. if (window.ininjectConfig) {
  52. if (path.indexOf(`/${window.profileApi}`) > -1) {
  53. // return `${window.ininjectConfig.profileApi}${path}`
  54. return `${window.profileApi}${path}`;
  55. }
  56. if (/weixinApi/g.test(path)) {
  57. return path;
  58. }
  59. if (/\/qaPayment/g.test(path)) {
  60. return `${window.ininjectConfig.qaPayment}${path.replace(
  61. /\/qaPayment/g,
  62. ''
  63. )}`;
  64. }
  65. }
  66. // 本地开发环境
  67. // path.indexOf('http') > -1 &&
  68. if (path.indexOf(`/${window.profileApi}`) > -1 || path) {
  69. return path;
  70. } else if (/\/qaPayment/g.test(path)) {
  71. // 支付
  72. return `https://qa-payment.kerryonvip.com${path}`;
  73. } else {
  74. return CacheTool.getCurEnvConst('KIP_API') + path;
  75. }
  76. }
  77. function cleanCacheAndGoLogin() {
  78. // 删除token以及会员数据
  79. uni.removeStorageSync('kipAccessToken');
  80. uni.removeStorageSync('isNewUser');
  81. uni.removeStorageSync('kipRefreshToken');
  82. // 直接跳转到登录页面
  83. uni.removeStorageSync('member');
  84. uni.removeStorageSync('wxMember');
  85. uni.removeStorageSync('openId');
  86. uni.removeStorageSync('userInfo');
  87. uni.reLaunch({
  88. url: '/pages/automatic/automaticMy.vue',
  89. });
  90. }
  91. function handleKipResponse(resp, request) {
  92. if (resp && resp.data) {
  93. const { status } = resp;
  94. console.log(`kip request resp => errMsg ${status}`);
  95. const { path } = request.detail;
  96. let isLogout = false;
  97. if (path.indexOf('/logout') > -1) {
  98. isLogout = true;
  99. }
  100. if (!resp || !resp.data) {
  101. return resp;
  102. }
  103. const result = resp.data;
  104. if (result) {
  105. const { message, code } = result || {};
  106. console.log(`kip api resul => message: ${message} code: ${code}`);
  107. if (result.code == '300000' && !isLogout) {
  108. console.warn('===> kip的access_token已过期');
  109. log.info(`kip的access_token已过期`, result);
  110. }
  111. }
  112. }
  113. return resp.data;
  114. }
  115. export default {
  116. detail: null,
  117. base(method, path, param = {}, config) {
  118. const _this = this;
  119. _this.detail = {
  120. method,
  121. path,
  122. param,
  123. config,
  124. };
  125. return new Promise((resolve, reject) => {
  126. const url = getUrl(
  127. /|http/g.test(path) ? path : `${window.profileApi}${path}`
  128. );
  129. // console.log(130, url);
  130. const { header } = handleConfig(config);
  131. log.info(`===>request-kip url: ${url}`);
  132. log.info(`===>request-kip header: ${JSON.stringify(header)}`);
  133. uni
  134. .request({
  135. header: header,
  136. method: method,
  137. url: url,
  138. data: param,
  139. })
  140. .then((res) => {
  141. log.info(`===>request-kip response: ${JSON.stringify(res.data)}`);
  142. resolve(handleKipResponse(res, _this));
  143. if (res.status == 581) {
  144. uni.navigateTo({
  145. url: '/pages/errorPage/errorLimit?msg=当前访问太火爆了,稍后试试吧~',
  146. });
  147. }
  148. })
  149. .catch((response) => {
  150. log.error(`===>request-kip error: ${JSON.stringify(response)}`);
  151. reject(response);
  152. });
  153. });
  154. },
  155. get(path, param = {}, config) {
  156. return this.base('GET', path, param, config);
  157. },
  158. post(path, param = {}, config) {
  159. return this.base('POST', path, param, config);
  160. },
  161. put(path, param = {}, config) {
  162. return this.base('PUT', path, param, config);
  163. },
  164. delete(path, param = {}, config) {
  165. return this.base('DELETE', path, param, config);
  166. },
  167. uploadFile(path, param = {}, config) {
  168. const _this = this;
  169. _this.detail = {
  170. method: 'POST',
  171. path,
  172. param,
  173. config,
  174. };
  175. return new Promise((resolve, reject) => {
  176. const url = getUrl(path);
  177. const { fileType, file, formData } = param;
  178. let header = getHeaders(config);
  179. header['Content-Type'] = 'multipart/form-data';
  180. uni
  181. .uploadFile({
  182. header: header,
  183. method: 'POST',
  184. url: url,
  185. name: 'file',
  186. fileType: fileType,
  187. filePath: file.path,
  188. file: file,
  189. formData: formData,
  190. })
  191. .then((res) => {
  192. resolve(handleKipResponse(res[1], _this));
  193. })
  194. .catch((response) => {
  195. reject(response);
  196. });
  197. });
  198. },
  199. refreshToken(path) {
  200. return new Promise((resolve, reject) => {
  201. const url = getUrl(path);
  202. const header = getHeaders();
  203. delete header.Authorization;
  204. uni
  205. .request({
  206. header: header,
  207. method: 'POST',
  208. url: url,
  209. })
  210. .then((res) => {
  211. resolve(res[1]);
  212. })
  213. .catch((response) => {
  214. reject(response);
  215. });
  216. });
  217. },
  218. };