| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183 |
- import md5 from 'md5';
- import { formatDate, formatPattern } from '@/utils/formatDate';
- export const API_BASE_URL = 'https://ssxz.akaisi.cn/client-api';
- const API_SECRET = 'isXEg8A6WsucUvlswOgcTHUlKYu2DrPJ';
- /**
- * 对象按ASCII码进行排序
- */
- const asciiSort = (data: any, join = false) => {
- let keys: any[] = [];
- if (!data) {
- return false;
- }
- Object.keys(data).forEach((item) => keys.push(item));
- keys = keys.sort();
- if (join) {
- let str = '';
- for (let i in keys) {
- let key = keys[i];
- if (key != 'sign') {
- str += data[key];
- }
- }
- return str;
- } else {
- let sortData: any = {};
- for (let i in keys) {
- let key = keys[i];
- if (key != 'sign') {
- sortData[key] = data[key];
- }
- }
- return sortData;
- }
- };
- /**
- * 取得签名数据
- */
- export const getSignature = (data: any, datetime: number | string) => {
- let signData = Object.assign({}, data, {
- _t: datetime
- });
- let dataStr = asciiSort(signData, true);
- dataStr += API_SECRET;
- let val = md5(dataStr);
- return val.toLocaleUpperCase();
- };
- class ApiRequest {
- private baseUrl: string;
- private headers: { [key: string]: string };
- constructor(baseUrl: string, headers: { [key: string]: string } = {}) {
- this.baseUrl = baseUrl;
- this.headers = headers;
- }
- // 请求拦截器
- private requestInterceptor(config: UniApp.RequestOptions | UniApp.UploadFileOption) {
- let hTimestamp = formatDate(formatPattern.h_timestamp);
- config.header = {
- ...this.headers,
- ...config.header,
- timeout: 20000,
- 'h-timestamp': hTimestamp,
- 'h-sign': getSignature(config.data, hTimestamp)
- };
- return config;
- }
- // 响应拦截器
- private responseInterceptor(response: UniApp.RequestSuccessCallbackResult | UniApp.UploadFileSuccessCallbackResult) {
- let { statusCode, data } = response;
- if (typeof data == 'string') {
- data = JSON.parse(data);
- }
- data = data as object;
- if (statusCode >= 200 && statusCode < 300) {
- if (data.code == 200) return data.data;
- uni.showToast({
- title: data.message,
- icon: 'none'
- });
- } else {
- throw new Error(`请求失败,状态码: ${statusCode}`);
- }
- }
- // 错误处理
- private errorHandler(error: any) {
- console.error('请求发生错误:', error);
- return Promise.reject(error);
- }
- // 封装请求方法
- public request(config: UniApp.RequestOptions) {
- const newConfig = this.requestInterceptor({
- ...config,
- url: this.baseUrl + config.url
- });
- return new Promise((resolve, reject) => {
- uni.request({
- ...newConfig,
- success: (res) => {
- try {
- const result = this.responseInterceptor(res);
- resolve(result);
- } catch (error) {
- this.errorHandler(error).then(() => reject(error));
- }
- },
- fail: (err) => {
- if (err.errMsg == 'request:fail timeout') {
- uni.showToast({
- title: '网络请求超时,请稍后再试...',
- icon: 'none'
- });
- }
- this.errorHandler(err).then(() => reject(err));
- }
- });
- });
- }
- public requestUpload(filePath: string, data?: any, config?: UniApp.UploadFileOption) {
- const newConfig = this.requestInterceptor({
- ...config,
- url: this.baseUrl + config.url,
- name: 'file',
- filePath: filePath,
- formData: data
- });
- return new Promise((resolve, reject) => {
- uni.uploadFile({
- ...newConfig,
- success: (res) => {
- try {
- const result = this.responseInterceptor(res);
- resolve(result);
- } catch (error) {
- this.errorHandler(error).then(() => reject(error));
- }
- },
- fail: (err) => {
- this.errorHandler(err).then(() => reject(err));
- }
- });
- });
- }
- // 封装 get 请求
- public get(url: string, data?: any, config: UniApp.RequestOptions = { url: '' }) {
- return this.request({
- ...config,
- url,
- method: 'GET',
- data
- });
- }
- // 封装 post 请求
- public post(url: string, data?: any, config: UniApp.RequestOptions = { url: '' }) {
- return this.request({
- ...config,
- url,
- method: 'POST',
- data
- });
- }
- public upload(url: string, filePath: string, data?: any, config: UniApp.UploadFileOption = { url: '' }) {
- return this.requestUpload(filePath, data, {
- ...config,
- url
- });
- }
- }
- export const http = new ApiRequest(API_BASE_URL, {
- 'Content-Type': 'application/json;charset=utf-8'
- });
|