http.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import md5 from 'md5';
  2. import { formatDate, formatPattern } from '@/utils/formatDate';
  3. export const API_BASE_URL = 'https://ssxz.akaisi.cn/client-api';
  4. const API_SECRET = 'isXEg8A6WsucUvlswOgcTHUlKYu2DrPJ';
  5. /**
  6. * 对象按ASCII码进行排序
  7. */
  8. const asciiSort = (data: any, join = false) => {
  9. let keys: any[] = [];
  10. if (!data) {
  11. return false;
  12. }
  13. Object.keys(data).forEach((item) => keys.push(item));
  14. keys = keys.sort();
  15. if (join) {
  16. let str = '';
  17. for (let i in keys) {
  18. let key = keys[i];
  19. if (key != 'sign') {
  20. str += data[key];
  21. }
  22. }
  23. return str;
  24. } else {
  25. let sortData: any = {};
  26. for (let i in keys) {
  27. let key = keys[i];
  28. if (key != 'sign') {
  29. sortData[key] = data[key];
  30. }
  31. }
  32. return sortData;
  33. }
  34. };
  35. /**
  36. * 取得签名数据
  37. */
  38. export const getSignature = (data: any, datetime: number | string) => {
  39. let signData = Object.assign({}, data, {
  40. _t: datetime
  41. });
  42. let dataStr = asciiSort(signData, true);
  43. dataStr += API_SECRET;
  44. let val = md5(dataStr);
  45. return val.toLocaleUpperCase();
  46. };
  47. class ApiRequest {
  48. private baseUrl: string;
  49. private headers: { [key: string]: string };
  50. constructor(baseUrl: string, headers: { [key: string]: string } = {}) {
  51. this.baseUrl = baseUrl;
  52. this.headers = headers;
  53. }
  54. // 请求拦截器
  55. private requestInterceptor(config: UniApp.RequestOptions | UniApp.UploadFileOption) {
  56. let hTimestamp = formatDate(formatPattern.h_timestamp);
  57. config.header = {
  58. ...this.headers,
  59. ...config.header,
  60. timeout: 20000,
  61. 'h-timestamp': hTimestamp,
  62. 'h-sign': getSignature(config.data, hTimestamp)
  63. };
  64. return config;
  65. }
  66. // 响应拦截器
  67. private responseInterceptor(response: UniApp.RequestSuccessCallbackResult | UniApp.UploadFileSuccessCallbackResult) {
  68. let { statusCode, data } = response;
  69. if (typeof data == 'string') {
  70. data = JSON.parse(data);
  71. }
  72. data = data as object;
  73. if (statusCode >= 200 && statusCode < 300) {
  74. if (data.code == 200) return data.data;
  75. uni.showToast({
  76. title: data.message,
  77. icon: 'none'
  78. });
  79. } else {
  80. throw new Error(`请求失败,状态码: ${statusCode}`);
  81. }
  82. }
  83. // 错误处理
  84. private errorHandler(error: any) {
  85. console.error('请求发生错误:', error);
  86. return Promise.reject(error);
  87. }
  88. // 封装请求方法
  89. public request(config: UniApp.RequestOptions) {
  90. const newConfig = this.requestInterceptor({
  91. ...config,
  92. url: this.baseUrl + config.url
  93. });
  94. return new Promise((resolve, reject) => {
  95. uni.request({
  96. ...newConfig,
  97. success: (res) => {
  98. try {
  99. const result = this.responseInterceptor(res);
  100. resolve(result);
  101. } catch (error) {
  102. this.errorHandler(error).then(() => reject(error));
  103. }
  104. },
  105. fail: (err) => {
  106. if (err.errMsg == 'request:fail timeout') {
  107. uni.showToast({
  108. title: '网络请求超时,请稍后再试...',
  109. icon: 'none'
  110. });
  111. }
  112. this.errorHandler(err).then(() => reject(err));
  113. }
  114. });
  115. });
  116. }
  117. public requestUpload(filePath: string, data?: any, config?: UniApp.UploadFileOption) {
  118. const newConfig = this.requestInterceptor({
  119. ...config,
  120. url: this.baseUrl + config.url,
  121. name: 'file',
  122. filePath: filePath,
  123. formData: data
  124. });
  125. return new Promise((resolve, reject) => {
  126. uni.uploadFile({
  127. ...newConfig,
  128. success: (res) => {
  129. try {
  130. const result = this.responseInterceptor(res);
  131. resolve(result);
  132. } catch (error) {
  133. this.errorHandler(error).then(() => reject(error));
  134. }
  135. },
  136. fail: (err) => {
  137. this.errorHandler(err).then(() => reject(err));
  138. }
  139. });
  140. });
  141. }
  142. // 封装 get 请求
  143. public get(url: string, data?: any, config: UniApp.RequestOptions = { url: '' }) {
  144. return this.request({
  145. ...config,
  146. url,
  147. method: 'GET',
  148. data
  149. });
  150. }
  151. // 封装 post 请求
  152. public post(url: string, data?: any, config: UniApp.RequestOptions = { url: '' }) {
  153. return this.request({
  154. ...config,
  155. url,
  156. method: 'POST',
  157. data
  158. });
  159. }
  160. public upload(url: string, filePath: string, data?: any, config: UniApp.UploadFileOption = { url: '' }) {
  161. return this.requestUpload(filePath, data, {
  162. ...config,
  163. url
  164. });
  165. }
  166. }
  167. export const http = new ApiRequest(API_BASE_URL, {
  168. 'Content-Type': 'application/json;charset=utf-8'
  169. });