Ver Fonte

perf: 优化axios接口请求写法

kuns há 1 mês atrás
pai
commit
a1ae8f4480
6 ficheiros alterados com 392 adições e 421 exclusões
  1. 2 12
      context/AuthProvider.tsx
  2. 61 167
      service/authService.tsx
  3. 62 170
      service/chargeStationService.tsx
  4. 55 0
      service/conf.ts
  5. 190 0
      service/requets.ts
  6. 22 72
      service/walletService.tsx

+ 2 - 12
context/AuthProvider.tsx

@@ -2,11 +2,10 @@ import { ReactNode, createContext, useEffect, useState } from 'react';
 import { useContext } from 'react';
 import { router, useSegments } from 'expo-router';
 import * as SecureStore from 'expo-secure-store';
-
-import axios from 'axios';
 import { User } from '../types/user';
 
 import { authenticationService } from '../service/authService';
+import {apiClient} from '../service/requets'
 
 type AuthProvider = {
     user: User | null;
@@ -98,17 +97,8 @@ export default function AuthProvider({ children }: { children: ReactNode }) {
     };
 
     const getUserFromAccessToken = async () => {
-        SecureStore.getItemAsync('accessToken').then((aa) => {
-            console.log('sssssss:', aa);
-        });
-
-        const token = await SecureStore.getItemAsync('accessToken');
         try {
-            const res = await axios.get(`${process.env.EXPO_PUBLIC_API_URL}/clients/customer`, {
-                headers: {
-                    Authorization: `Bearer ${token}`
-                }
-            });
+            const res = await apiClient.instance.get(`/clients/customer`);
 
             const items = {
                 address: res.data.address,

+ 61 - 167
service/authService.tsx

@@ -1,44 +1,29 @@
-import axios from 'axios';
+import axios, {isAxiosError} from 'axios';
 import { Alert } from 'react-native';
 import * as SecureStore from 'expo-secure-store';
 import { forgetPasswordFormData } from '../types/signup';
 import { CustomerData } from '../types/signUpFormData';
 import * as FileSystem from 'expo-file-system';
-
+import {apiClient} from './requets'
 class AuthenticationService {
-    private apiUrl: string;
-
-    constructor() {
-        this.apiUrl = process.env.EXPO_PUBLIC_API_URL;
-        if (!this.apiUrl) {
-            throw new Error('API URL is not defined in environment variables');
-        }
-    }
 
     async emailLogin(username: string, password: string, isBinding?: boolean) {
         try {
-            console.log('username in emailLogin auth service', username);
-            console.log('password in emailLogin auth service', password);
-            console.log('isBinding in emailLogin auth service', isBinding);
-            const response = await axios.post(
-                `${this.apiUrl}/public/client/customer/sign-in`,
+            const response = await apiClient.instance.post('/public/client/customer/sign-in',
                 {
                     email: username,
                     password: password,
-                    isBinding: isBinding
+                    isBinding: isBinding,
+                    
                 },
                 {
-                    headers: {
-                        'Content-Type': 'application/json',
-                        Accept: 'application/json'
-                    }
-                }
+                    customConfig: {needAuth: true}
+                },
             );
             if (response.status === 201) {
                 const token = response.data.accessToken;
                 await SecureStore.setItemAsync('accessToken', token);
                 console.log('AccessToken', token);
-                console.log('Login successful!');
                 return true;
             } else {
                 console.error('Login failed:', response.status);
@@ -46,7 +31,7 @@ class AuthenticationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Login error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -58,20 +43,17 @@ class AuthenticationService {
 
     async phoneLogin(username: string | null | undefined, password: string, isBinding?: boolean) {
         try {
-            const response = await axios.post(
-                // `${this.apiUrl}/public/client/customer/sign-in`,
-                // `${this.apiUrl}/public/client/customer/sign-in`,
-                `${this.apiUrl}/public/client/customer/phone/sign-in`,
+            const response = await apiClient.instance.post(
+                `/public/client/customer/phone/sign-in`,
                 {
                     phone: username,
                     password: password,
-                    isBinding: isBinding
+                    isBinding: isBinding,
+                    
                 },
                 {
-                    headers: {
-                        'Content-Type': 'application/json',
-                        Accept: '*/*'
-                    }
+                
+                    customConfig: {needAuth: true}
                 }
             );
             if (response.status === 201) {
@@ -97,19 +79,11 @@ class AuthenticationService {
         console.log('log out successfully, accessToken deleted');
     }
 
-    //BELOW CODES RELATE TO "SIGN UP"
-    //BELOW CODES RELATE TO "SIGN UP"
     async sendOtpToSignUpEmail(email: string) {
         try {
-            const response = await axios.post(
-                `${this.apiUrl}/public/client/customer/otp`,
+            const response = await apiClient.instance.post(
+                `/public/client/customer/otp`,
                 { email: email },
-                {
-                    headers: {
-                        'Content-Type': 'application/json',
-                        Accept: 'application/json'
-                    }
-                }
             );
             if (response.status === 200 || response.status === 201) {
                 return true;
@@ -118,7 +92,7 @@ class AuthenticationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error sending OTP:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred while sending OTP:', error);
@@ -133,11 +107,11 @@ class AuthenticationService {
             if (!fileInfo.exists) {
                 throw new Error('File does not exist');
             }
-
-            const fileExtension = imageUri.split('.').pop().toLowerCase();
+            const fileExtension = imageUri ? imageUri.split('.').pop()?.toLowerCase() : undefined;
+            
             const allowedExtensions = ['jpg', 'jpeg', 'png'];
 
-            if (!allowedExtensions.includes(fileExtension)) {
+            if (fileExtension && !allowedExtensions.includes(fileExtension)) {
                 throw new Error('只接受jpg,jpeg,png格式的圖片');
             }
 
@@ -151,12 +125,10 @@ class AuthenticationService {
                 type: `image/${fileExtension}`
             } as any);
 
-            const accessToken = await SecureStore.getItemAsync('accessToken');
-            const response = await axios.post(`${this.apiUrl}/clients/customer/image?type=uber`, formData, {
+            const response = await apiClient.instance.post(`/clients/customer/image?type=uber`, formData, {
                 headers: {
                     accept: '*/*',
                     'Content-Type': 'multipart/form-data',
-                    Authorization: `Bearer ${accessToken}`
                 }
             });
             console.log('Upload response:', response.data);
@@ -174,15 +146,9 @@ class AuthenticationService {
         setError: React.Dispatch<React.SetStateAction<string>>
     ) {
         try {
-            const response = await axios.put(
-                `${this.apiUrl}/public/client/customer/otp`,
+            const response = await apiClient.instance.put(
+                `/public/client/customer/otp`,
                 { email, code },
-                {
-                    headers: {
-                        'Content-Type': 'application/json',
-                        Accept: 'application/json'
-                    }
-                }
             );
 
             if (response.status === 200) {
@@ -195,7 +161,7 @@ class AuthenticationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error verifying OTP:', error.response?.data?.message || error.message);
                 setError('發生意外錯誤,請確保您輸入的電子郵件正確,並再次確認您的OTP驗證碼是否正確。');
             } else {
@@ -208,12 +174,7 @@ class AuthenticationService {
 
     async signUp(data: CustomerData) {
         try {
-            const response = await axios.post(`${this.apiUrl}/public/client/customer`, data, {
-                headers: {
-                    'Content-Type': 'application/json',
-                    Accept: 'application/json'
-                }
-            });
+            const response = await apiClient.instance.post(`/public/client/customer`, data);
             if (response.status === 200 || response.status === 201) {
                 return true;
             } else {
@@ -221,7 +182,7 @@ class AuthenticationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error signing up:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred while signing up:', error);
@@ -230,19 +191,11 @@ class AuthenticationService {
         }
     }
 
-    //BELOW CODES RELATE TO "FORGET PASSWORD"
-    //BELOW CODES RELATE TO "FORGET PASSWORD"
     async sendForgetPasswordOtp(email: string) {
         try {
-            const response = await axios.post(
-                `${this.apiUrl}/public/client/customer/pw/otp`,
+            const response = await apiClient.instance.post(
+                `/public/client/customer/pw/otp`,
                 { email },
-                {
-                    headers: {
-                        'Content-Type': 'application/json',
-                        Accept: 'application/json'
-                    }
-                }
             );
 
             if (response.status === 200 || response.status === 201) {
@@ -253,7 +206,7 @@ class AuthenticationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error sending forget password OTP:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred while sending forget password OTP:', error);
@@ -264,7 +217,7 @@ class AuthenticationService {
 
     async getVersion() {
         try {
-            const response = await axios.get(`${this.apiUrl}/public/client/app/version`);
+            const response = await apiClient.instance.get(`/public/client/app/version`);
             return response.data.data;
         } catch (error) {
             console.error('Error getting version:', error);
@@ -279,7 +232,7 @@ class AuthenticationService {
         setData: React.Dispatch<React.SetStateAction<string>>
     ) {
         try {
-            const res = await axios.put(`${this.apiUrl}/public/client/customer/pw/otp`, {
+            const res = await apiClient.instance.put(`/public/client/customer/pw/otp`, {
                 email: email,
                 code: otp
             });
@@ -299,18 +252,13 @@ class AuthenticationService {
 
     async changePassword(confirmedNewPassword: string, data: string) {
         try {
-            const res = await axios.put(
-                `${this.apiUrl}/clients/customer/pw/forget`,
+            const res = await apiClient.instance.put(
+                `/clients/customer/pw/forget`,
                 { newPassword: confirmedNewPassword },
-                {
-                    headers: {
-                        Authorization: `Bearer ${data}`
-                    }
-                }
             );
             return true;
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error changing password:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -320,19 +268,14 @@ class AuthenticationService {
 
     async changeEmail(email: string | null, token: string | null): Promise<boolean> {
         try {
-            const res = await axios.put(
-                `${this.apiUrl}/clients/customer`,
+            const res = await apiClient.instance.put(
+                `/clients/customer`,
                 { email: email },
-                {
-                    headers: {
-                        Authorization: `Bearer ${token}`
-                    }
-                }
             );
             console.log('Change Name Successfully!');
             return true;
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error changing name:', error.response?.data?.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -343,19 +286,14 @@ class AuthenticationService {
     //BELOW CODES RELATE TO "changing account info (such as gender, name)"
     async changeName(name: string | null, token: string | null): Promise<boolean> {
         try {
-            const res = await axios.put(
-                `${this.apiUrl}/clients/customer`,
+            const res = await apiClient.instance.put(
+                `/clients/customer`,
                 { nickname: name },
-                {
-                    headers: {
-                        Authorization: `Bearer ${token}`
-                    }
-                }
             );
             console.log('Change Name Successfully!');
             return true;
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error changing name:', error.response?.data?.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -365,14 +303,9 @@ class AuthenticationService {
     }
     async changeNotifySessionID(notifySessionID: string | null): Promise<boolean> {
         try {
-            const res = await axios.put(
-                `${this.apiUrl}/clients/customer`,
-                { notify_session_id: notifySessionID },
-                {
-                    headers: {
-                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                    }
-                }
+            const res = await apiClient.instance.put(
+                `/clients/customer`,
+                { notify_session_id: notifySessionID }
             );
             if (res.data.status == 200) {
                 console.log('Change notifySessionID Successfully!');
@@ -382,7 +315,7 @@ class AuthenticationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error changing name:', error.response?.data?.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -394,18 +327,13 @@ class AuthenticationService {
     async changePhone(phone: string | null, token: string | null): Promise<boolean> {
         try {
             const convertPhoneStringToNumber = Number(phone);
-            const res = await axios.put(
-                `${this.apiUrl}/clients/customer`,
+            const res = await apiClient.instance.put(
+                `/clients/customer`,
                 { phone: convertPhoneStringToNumber },
-                {
-                    headers: {
-                        Authorization: `Bearer ${token}`
-                    }
-                }
             );
             return true;
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error changing phone:', error.response?.data?.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -416,19 +344,14 @@ class AuthenticationService {
 
     async changeGender(gender: string | null, token: string | null): Promise<boolean> {
         try {
-            const res = await axios.put(
-                `${this.apiUrl}/clients/customer`,
+            const res = await apiClient.instance.put(
+                `/clients/customer`,
                 { gender: gender },
-                {
-                    headers: {
-                        Authorization: `Bearer ${token}`
-                    }
-                }
             );
             console.log('Change gender Successfully!');
             return true;
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error changing gender:', error.response?.data?.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -438,11 +361,7 @@ class AuthenticationService {
     }
     async getUserInfo() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/customer`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/customer`);
             if (response.status === 200 || response.status === 201) {
                 return response;
             } else {
@@ -454,12 +373,7 @@ class AuthenticationService {
     }
     async deleteAccount(): Promise<boolean> {
         try {
-            const accessToken = await SecureStore.getItemAsync('accessToken');
-            const response = await axios.delete(`${this.apiUrl}/clients/customer`, {
-                headers: {
-                    Authorization: `Bearer ${accessToken}`
-                }
-            });
+            const response = await apiClient.instance.delete(`/clients/customer`);
 
             if (response.status === 200 || response.status === 201) {
                 console.log('Account deleted successfully');
@@ -470,7 +384,7 @@ class AuthenticationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error deleting account:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred while deleting account:', error);
@@ -482,16 +396,11 @@ class AuthenticationService {
     async checkPhoneSame(phoneNumber: string) {
         try {
             console.log('being checkPhoneSame');
-            const response = await axios.post(
-                `${this.apiUrl}/clients/customer/binding/sms`,
+            const response = await apiClient.instance.post(
+                `/clients/customer/binding/sms`,
                 {
                     phone: phoneNumber,
                     type: 3
-                },
-                {
-                    headers: {
-                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                    }
                 }
             );
             const token = await SecureStore.getItemAsync('accessToken');
@@ -505,20 +414,14 @@ class AuthenticationService {
 
     async confirmBindingPhone(phoneNumber: string, otp: string, notify_session_id: string) {
         try {
-            const response = await axios.put(
-                `${this.apiUrl}/public/client/customer/phone/otp`,
+            const response = await apiClient.instance.put(
+                `/public/client/customer/phone/otp`,
                 {
                     phone: phoneNumber,
                     code: otp,
                     notify_session_id: notify_session_id,
                     type: 3
                 },
-                {
-                    headers: {
-                        'Content-Type': 'application/json',
-                        Accept: 'application/json'
-                    }
-                }
             );
             console.log('confirmBindingPhone response', response.data);
             return response.data;
@@ -529,24 +432,17 @@ class AuthenticationService {
 
     async verifyPhoneOtp(phoneNumber: string, otp: string, notify_session_id: string) {
         try {
-            const response = await axios.put(
-                `${this.apiUrl}/public/client/customer/phone/otp`,
+            const response = await apiClient.instance.put(
+                `/public/client/customer/phone/otp`,
                 {
                     phone: phoneNumber,
                     code: otp,
                     notify_session_id: notify_session_id
                 },
-                {
-                    headers: {
-                        'Content-Type': 'application/json',
-                        Accept: '*/*'
-                    }
-                }
             );
-            console.log('verifyPhoneOtp response:', response.data);
             return response.data;
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Error verifying phone OTP:', error.response?.data || error.message);
                 throw error;
             } else {
@@ -557,15 +453,13 @@ class AuthenticationService {
     }
     async sendOtpToSignUpPhone(phone: string) {
         try {
-            const response = await axios.post(`${this.apiUrl}/public/client/customer/phone/sms`, {
+            const response = await apiClient.instance.post(`/public/client/customer/phone/sms`, {
                 phone: phone,
                 type: 1
             });
             if (response.status === 200 || response.status === 201) {
-                console.log('OTP sent successfully -- from api sendOtpToSignUpPhone, response:', response);
                 return true;
             } else {
-                console.error('Failed to send OTP -- from api sendOtpToSignUpPhone.. response:', response);
                 return false;
             }
         } catch (error) {

+ 62 - 170
service/chargeStationService.tsx

@@ -1,22 +1,13 @@
-import axios from 'axios';
+import axios, { isAxiosError } from 'axios';
 import { Alert } from 'react-native';
 import * as SecureStore from 'expo-secure-store';
-import { forgetPasswordFormData } from '../types/signup';
-import { CustomerData } from '../types/signUpFormData';
+import {apiClient} from './requets'
 
 class ChargeStationService {
-    private apiUrl: string;
-
-    constructor() {
-        this.apiUrl = process.env.EXPO_PUBLIC_API_URL;
-        if (!this.apiUrl) {
-            throw new Error('API URL is not defined in environment variables');
-        }
-    }
 
     async fetchCarBrand() {
         try {
-            const response = await axios.get(`${this.apiUrl}/public/client/car/brand`);
+            const response = await apiClient.instance.get(`/public/client/car/brand`);
 
             if (response.status === 200 || response.status === 201) {
                 return response.data;
@@ -24,7 +15,7 @@ class ChargeStationService {
                 console.log('invalid response');
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -35,7 +26,7 @@ class ChargeStationService {
 
     async getCarImage(filename: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/public/image?filename=${filename}`);
+            const response: any = await apiClient.instance.get(`/public/image?filename=${filename}`);
             if (response.status === 200 || response.status === 201) {
                 return response.url;
             } else {
@@ -45,11 +36,7 @@ class ChargeStationService {
 
     async getUserCars() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/customer/car/all`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/customer/car/all`);
             if (response.status === 200 || response.status === 201) {
                 return response.data;
             } else {
@@ -59,11 +46,7 @@ class ChargeStationService {
 
     async getUserDefaultCars() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/customer/car/all?queryDefault=true`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/customer/car/all?queryDefault=true`);
             if (response.status === 200 || response.status === 201) {
                 // console.log(response.data.data);
                 return response.data;
@@ -74,8 +57,8 @@ class ChargeStationService {
 
     async getReservationWithSize(size: number) {
         try {
-            const response = await axios.get(
-                `${this.apiUrl}/clients/reservation/connectors/2405311022116801000/${size}`,
+            const response = await apiClient.instance.get(
+                `/clients/reservation/connectors/2405311022116801000/${size}`,
                 {
                     headers: {
                         Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
@@ -91,8 +74,8 @@ class ChargeStationService {
 
     async addCar(licensePlate: string, carBrandFk: string, carTypeFk: string, isDefault: boolean) {
         try {
-            const response = await axios.post(
-                `${this.apiUrl}/clients/customer/car`,
+            const response = await apiClient.instance.post(
+                `/clients/customer/car`,
                 {
                     licensePlate: licensePlate,
                     carBrandFk: carBrandFk,
@@ -111,7 +94,7 @@ class ChargeStationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('error:', error.response?.data?.message || error.message);
                 return false;
             } else {
@@ -121,29 +104,20 @@ class ChargeStationService {
         }
     }
 
-    async deleteCar(carID) {
+    async deleteCar(carID: string) {
         try {
-            const response = await axios.delete(`${this.apiUrl}/clients/customer/car?carId=${carID}`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.delete(`/clients/customer/car?carId=${carID}`);
             if (response.status === 200 || response.status === 201) {
                 return true;
             } else {
             }
         } catch (error) {}
     }
-    async setDefaultCar(carID) {
+    async setDefaultCar(carID: string) {
         try {
-            const response = await axios.put(
-                `${this.apiUrl}/clients/customer/car/default?carId=${carID}`,
+            const response = await apiClient.instance.put(
+                `/clients/customer/car/default?carId=${carID}`,
                 {},
-                {
-                    headers: {
-                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                    }
-                }
             );
             if (response.status === 200 || response.status === 201) {
                 return true;
@@ -154,11 +128,7 @@ class ChargeStationService {
 
     async fetchPriceForCharging() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/info`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/chargestations/resources/info`);
             if (response.status === 200 || response.status === 201) {
                 return response.data;
             }
@@ -167,7 +137,7 @@ class ChargeStationService {
 
     async getCurrentPrice() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/promotion/price?id=2405311022116801000`);
+            const response = await apiClient.instance.get(`/clients/promotion/price?id=2405311022116801000`);
             if (response.status === 200 || response.status === 201) {
                 return response.data.price;
             } else {
@@ -175,7 +145,7 @@ class ChargeStationService {
             }
         } catch (error) {
             console.error('Error getting current price:', error);
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Response data:', error.response?.data);
                 console.error('Response status:', error.response?.status);
             }
@@ -184,7 +154,7 @@ class ChargeStationService {
     }
     async getOriginalPrice() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/promotion/price?id=2405311022116801000`);
+            const response = await apiClient.instance.get(`/clients/promotion/price?id=2405311022116801000`);
             if (response.status === 200 || response.status === 201) {
                 return response.data.originalPrice;
             } else {
@@ -192,7 +162,7 @@ class ChargeStationService {
             }
         } catch (error) {
             console.error('Error getting original price:', error);
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Response data:', error.response?.data);
                 console.error('Response status:', error.response?.status);
             }
@@ -202,11 +172,7 @@ class ChargeStationService {
 
     async NewfetchAvailableConnectors() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/local/info`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/chargestations/resources/local/info`);
             if (response.status === 200 && response.data.code === 200) {
                 return response.data.data.map((station: any) => {
                     // const snapshotData = JSON.parse(station.snapshot);
@@ -238,19 +204,14 @@ class ChargeStationService {
 
     async fetchAvailableConnectors(stationID: string) {
         try {
-            const response = await axios.get(
-                `${this.apiUrl}/clients/chargestations/resources/status?StationIDs=${stationID}`,
-                {
-                    headers: {
-                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                    }
-                }
+            const response = await apiClient.instance.get(
+                `/clients/chargestations/resources/status?StationIDs=${stationID}`,
             );
             if (response.status === 200 || response.status === 201) {
                 const stationStatusInfos = response.data.data.StationStatusInfos;
                 if (stationStatusInfos && stationStatusInfos.length > 0) {
                     const availableConnectors = stationStatusInfos[0].ConnectorStatusInfos.filter(
-                        (connector) => connector.Status === 2
+                        (connector: any) => connector.Status === 2
                     ).length;
                     return availableConnectors;
                 }
@@ -262,14 +223,10 @@ class ChargeStationService {
     }
     async fetchChargeStations() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/info`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/chargestations/resources/info`);
 
             if (response.status === 200 || response.status === 201) {
-                return response.data.data.map((station, index) => {
+                return response.data.data.map((station: any) => {
                     const { Address, StationName, StationID, StationLng, StationLat } = station.snapshot;
                     const image = station.image;
 
@@ -285,7 +242,7 @@ class ChargeStationService {
             } else {
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Login error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -296,11 +253,7 @@ class ChargeStationService {
 
     async fetchChargeStationIdByScannedConnectorId(scannedConnectorId: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/info`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/chargestations/resources/info`);
 
             if (response.status === 200 || response.status === 201) {
                 const station = response.data.data.find((station: any) =>
@@ -314,7 +267,7 @@ class ChargeStationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Login error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -325,11 +278,7 @@ class ChargeStationService {
 
     async noImagefetchChargeStationIdByScannedConnectorId(scannedConnectorId: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/local/simple/info`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/chargestations/resources/local/simple/info`);
 
             if (response.status === 200 || response.status === 201) {
                 const station = response.data.data.find((station: any) =>
@@ -343,7 +292,7 @@ class ChargeStationService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Login error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -354,17 +303,13 @@ class ChargeStationService {
 
     async fetchAllChargeStations() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/chargestations/resources/info`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/chargestations/resources/info`);
             if (response.status === 200 || response.status === 201) {
                 return response.data.data;
             } else {
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Login error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -375,14 +320,14 @@ class ChargeStationService {
 
     async fetchChargeStationPrice(stationID: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/promotion/price?id=${stationID}`);
+            const response = await apiClient.instance.get(`/clients/promotion/price?id=${stationID}`);
             if (response.status === 200 || response.status === 201) {
                 return response.data.price;
             } else {
                 console.log('invalid response');
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Login error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -393,19 +338,15 @@ class ChargeStationService {
 
     async fetchAvailableDates(stationID: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/reservation/connectors/${stationID}`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/reservation/connectors/${stationID}`);
             if (response.status === 200 || response.status === 201) {
-                const dates = response.data.map((i) => i.date);
+                const dates = response.data.map((i: any) => i.date);
                 return dates;
             } else {
                 console.log('invalid response');
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Login error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -416,21 +357,17 @@ class ChargeStationService {
 
     async fetchAvailableTimeSlots(stationID: string, targetDate: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/reservation/connectors/${stationID}`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/reservation/connectors/${stationID}`);
             if (response.status === 200 || response.status === 201) {
-                const times = response.data.find((i) => i.date === targetDate);
+                const times = response.data.find((i: any) => i.date === targetDate);
                 if (times) {
-                    const availableTimeSlots = times.range.map((i) => i.start);
+                    const availableTimeSlots = times.range.map((i: any) => i.start);
                     return availableTimeSlots;
                 }
             } else {
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Login error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -441,11 +378,7 @@ class ChargeStationService {
 
     async fetchSpecificChargeStation(stationID: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/reservation/connectors/${stationID}`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/reservation/connectors/${stationID}`);
             if (response.status === 200 || response.status === 201) {
                 return response.data;
             } else {
@@ -458,13 +391,8 @@ class ChargeStationService {
 
     async fetchOngoingChargingData(format_order_id: string) {
         try {
-            const response = await axios.get(
-                `${this.apiUrl}/clients/chargestations/resources/equip/status?StartChargeSeq=${format_order_id}`,
-                {
-                    headers: {
-                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                    }
-                }
+            const response = await apiClient.instance.get(
+                `/clients/chargestations/resources/equip/status?StartChargeSeq=${format_order_id}`,
             );
             if (response.status === 200 || response.status === 201) {
                 return response.data;
@@ -478,11 +406,7 @@ class ChargeStationService {
 
     async fetchReservationHistories() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/reservation/all`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/reservation/all`);
             if (response.status === 200 || response.status === 201) {
 
                 return response.data;
@@ -501,11 +425,7 @@ class ChargeStationService {
         StartBalance: number;
     }) {
         try {
-            const response = await axios.put(`${this.apiUrl}/clients/chargestations/resources/charge/start`, payload, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.put(`/clients/chargestations/resources/charge/start`, payload);
             if (response.status === 200 || response.status === 201) {
                 return response.data;
             } else {
@@ -519,11 +439,7 @@ class ChargeStationService {
     async stopCharging(payload: { StartChargeSeq: string; ConnectorID: string }) {
         try {
             console.log('stpo charge initialized');
-            const response = await axios.put(`${this.apiUrl}/clients/chargestations/resources/charge/stop`, payload, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.put(`/clients/chargestations/resources/charge/stop`, payload);
             if (response.status === 200 || response.status === 201) {
                 console.log('stopCharging success', response);
                 return response.data;
@@ -537,11 +453,7 @@ class ChargeStationService {
 
     async getTodayReservation() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/reservation/today`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/reservation/today`);
             if (response.status === 200 || response.status === 201) {
                 // console.log('getTodayReservation response.data: ', response.data);
                 return response.data;
@@ -555,15 +467,8 @@ class ChargeStationService {
 
     async getProcessedImageUrl(filename: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/public/image?filename=${filename}`, {
-                // const response = await axios.get(`${this.apiUrl}/public/image?filename=BENZ-EQA.png`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/public/image?filename=${filename}`)
             if (response.status === 200 || response.status === 201) {
-                // console.log('i am getProcessedImageUrl s resposne', response.data.url);
-
                 return response.data.url;
             }
         } catch (error) {
@@ -574,11 +479,7 @@ class ChargeStationService {
 
     async getProcessedCarImageUrl(filename: string) {
         try {
-            const response = await axios.get(`http://ftp.hkmgt.com/cdn/public/file/crazycharge/${filename}`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`http://ftp.hkmgt.com/cdn/public/file/crazycharge/${filename}`);
             if (response.status === 200 || response.status === 201) {
                 return response.data.detail;
             }
@@ -590,11 +491,7 @@ class ChargeStationService {
 
     async payPenalty(penaltyData: any) {
         try {
-            const response = await axios.post(`${this.apiUrl}/clients/pay/penalty`, penaltyData, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.post(`/clients/pay/penalty`, penaltyData);
             if (response.status === 200 || response.status === 201) {
                 return response.data;
             } else {
@@ -602,7 +499,7 @@ class ChargeStationService {
                 return null;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Penalty payment error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred during penalty payment:', error);
@@ -613,7 +510,7 @@ class ChargeStationService {
 
     async getAdvertise() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/advertise/advertise`);
+            const response = await apiClient.instance.get(`/clients/advertise/advertise`);
             if (response.status === 200 || response.status === 201) {
                 return response.data;
             } else {
@@ -626,7 +523,7 @@ class ChargeStationService {
 
     async getCurrentPriceInPay(stationID: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/promotion/price?id=${stationID}`);
+            const response = await apiClient.instance.get(`/clients/promotion/price?id=${stationID}`);
             if (response.status === 200 || response.status === 201) {
                 return response.data.price;
             } else {
@@ -634,7 +531,7 @@ class ChargeStationService {
             }
         } catch (error) {
             console.error('Error getting current price:', error);
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Response data:', error.response?.data);
                 console.error('Response status:', error.response?.status);
             }
@@ -643,7 +540,7 @@ class ChargeStationService {
     }
     async getOriginalPriceInPay(stationID: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/promotion/price?id=${stationID}`);
+            const response = await apiClient.instance.get(`/clients/promotion/price?id=${stationID}`);
             if (response.status === 200 || response.status === 201) {
                 return response.data.originalPrice;
                 // throw new Error(`Unexpected response status: ${response.status}`);
@@ -652,7 +549,7 @@ class ChargeStationService {
             }
         } catch (error) {
             console.error('Error getting original price:', error);
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('Response data:', error.response?.data);
                 console.error('Response status:', error.response?.status);
             }
@@ -661,17 +558,12 @@ class ChargeStationService {
     }
     async validateCoupon(couponRecords: string[], orderAmount: number) {
         try {
-            const response = await axios.post(
-                `${this.apiUrl}/clients/coupon/valid`,
+            const response = await apiClient.instance.post(
+                `/clients/coupon/valid`,
                 {
                     couponRecords: couponRecords,
                     orderAmount: orderAmount
                 },
-                {
-                    headers: {
-                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                    }
-                }
             );
             if (response.data.is_valid === true) {
                 return true;

+ 55 - 0
service/conf.ts

@@ -0,0 +1,55 @@
+import axios, { 
+  AxiosInstance, 
+  AxiosRequestConfig, 
+  AxiosResponse, 
+  AxiosError,
+  InternalAxiosRequestConfig 
+} from 'axios';
+// API 基础配置
+export const API_CONFIG = {
+  BASE_URL: process.env.EXPO_PUBLIC_API_URL,
+  // 超时时间
+  TIMEOUT: 15000,
+  
+  // 重试配置
+  RETRY: {
+    maxRetries: 3,
+    retryDelay: 1000,
+  },
+  
+  // 错误消息映射
+  ERROR_MESSAGES: {
+    NETWORK_ERROR: '网络连接失败,请检查网络设置',
+    TIMEOUT_ERROR: '请求超时,请重试',
+    SERVER_ERROR: '服务器错误,请稍后重试',
+    UNAUTHORIZED: '登录已过期,请重新登录',
+  } as const,
+} as const;
+
+// 基础响应结构
+export interface BaseResponse<T = any> {
+  code: number;
+  message: string;
+  data: T;
+  success: boolean;
+}
+
+// 错误响应结构
+export interface ErrorResponse {
+  code: number;
+  message: string;
+  timestamp?: string;
+  path?: string;
+}
+
+// 请求配置扩展
+export interface RequestConfig {
+  needAuth?: boolean; // 是否需要认证
+  showError?: boolean; // 是否显示错误提示
+  retryCount?: number; // 重试次数
+}
+
+// 扩展的 Axios 请求配置
+export interface ExtendedRequestConfig extends AxiosRequestConfig {
+  customConfig?: RequestConfig;
+}

+ 190 - 0
service/requets.ts

@@ -0,0 +1,190 @@
+import axios, { 
+  AxiosInstance, 
+  AxiosRequestConfig, 
+  AxiosResponse, 
+  AxiosError,
+  InternalAxiosRequestConfig 
+} from 'axios';
+import {API_CONFIG, BaseResponse, ErrorResponse, ExtendedRequestConfig, RequestConfig } from './conf';
+import * as SecureStore from 'expo-secure-store';
+
+declare module 'axios' {
+  interface AxiosRequestConfig {
+    customConfig?: RequestConfig;
+  }
+}
+
+// 创建 Axios 实例
+class ApiClient {
+  public instance: AxiosInstance;
+  private isRefreshing = false;
+  private failedQueue: Array<{ resolve: (value: any) => void; reject: (error: any) => void }> = [];
+  constructor() {
+    this.instance = axios.create({
+      baseURL: API_CONFIG.BASE_URL,
+      timeout: API_CONFIG.TIMEOUT,
+      headers: {
+        'Content-Type': 'application/json',
+      },
+    });
+
+    this.setupInterceptors();
+  }
+
+  // 设置拦截器
+  private setupInterceptors(): void {
+    // 请求拦截器
+    this.instance.interceptors.request.use(
+      async (config: InternalAxiosRequestConfig) => {
+        const extendedConfig = config as InternalAxiosRequestConfig & { customConfig?: RequestConfig };
+        const { needAuth = true } = extendedConfig.customConfig || {};
+
+        // 添加认证令牌
+        if (needAuth) {
+          const token = await SecureStore.getItemAsync('accessToken')
+          if (token) {
+            config.headers.Authorization = `Bearer ${token}`;
+          }
+        }
+        return config;
+      },
+      (error: AxiosError) => {
+        console.error('❌ 请求错误:', error);
+        return Promise.reject(error);
+      }
+    );
+
+    // 响应拦截器
+    this.instance.interceptors.response.use(
+      (response: AxiosResponse) => {
+        console.log(`✅ ${response.config.method?.toUpperCase()} ${response.config.url} 成功`);
+        return response;
+      },
+      async (error: AxiosError) => {
+        return this.handleError(error);
+      }
+    );
+  }
+
+  // 错误处理
+  private async handleError(error: AxiosError): Promise<never> {
+    const originalRequest = error.config as InternalAxiosRequestConfig & { 
+      _retry?: boolean;
+      customConfig?: RequestConfig;
+    };
+
+    // 网络错误
+    if (!error.response) {
+      const networkError: ErrorResponse = {
+        code: -1,
+        message: API_CONFIG.ERROR_MESSAGES.NETWORK_ERROR,
+      };
+      return Promise.reject(networkError);
+    }
+
+    const { status, data } = error.response;
+    const errorData = data as ErrorResponse;
+
+    // Token 过期,尝试刷新
+    if (status === 401 && !originalRequest._retry) {
+      if (this.isRefreshing) {
+        // 如果正在刷新,将请求加入队列
+        return new Promise((resolve, reject) => {
+          this.failedQueue.push({ resolve, reject });
+        });
+      }
+
+      originalRequest._retry = true;
+      this.isRefreshing = true;
+
+      try {
+        // // 刷新 Token 逻辑
+        // await this.refreshToken();
+        
+        // // 重试原始请求
+        // const retryResponse = await this.instance(originalRequest);
+        // this.isRefreshing = false;
+        // this.processQueue(null);
+        // return retryResponse;
+      } catch (refreshError) {
+        this.isRefreshing = false;
+        this.processQueue(refreshError);
+        
+        // 刷新失败,跳转到登录页
+        // await authManager.clearTokens();
+        // navigation.navigate('Login'); // 根据实际导航库调整
+        
+        return Promise.reject({
+          code: 401,
+          message: API_CONFIG.ERROR_MESSAGES.UNAUTHORIZED,
+        });
+      }
+    }
+
+    // 其他错误处理
+    const customError: ErrorResponse = {
+      code: status,
+      message: errorData?.message || this.getErrorMessageByStatus(status),
+    };
+
+    // 根据配置决定是否显示错误提示
+    const { showError = true } = originalRequest.customConfig || {};
+    if (showError) {
+      this.showErrorToast(customError.message);
+    }
+
+    return Promise.reject(customError);
+  }
+
+  // 处理请求队列
+  private processQueue(error: any): void {
+    this.failedQueue.forEach(promise => {
+      if (error) {
+        promise.reject(error);
+      } else {
+        promise.resolve(this.instance);
+      }
+    });
+    this.failedQueue = [];
+  }
+
+  // 刷新 Token
+  // private async refreshToken(): Promise<void> {
+  //   const refreshToken = await authManager.getRefreshToken();
+  //   if (!refreshToken) {
+  //     throw new Error('No refresh token');
+  //   }
+
+  //   // 调用刷新 Token 接口
+  //   const response = await axios.post(`${API_CONFIG.BASE_URL}/auth/refresh`, {
+  //     refreshToken,
+  //   });
+
+  //   const newTokens = response.data.data;
+  //   await authManager.setTokens(newTokens);
+  // }
+
+  // 根据状态码获取错误消息
+  private getErrorMessageByStatus(status: number): string {
+    const messages: { [key: number]: string } = {
+      400: '请求参数错误',
+      403: '没有权限访问',
+      404: '请求资源不存在',
+      500: API_CONFIG.ERROR_MESSAGES.SERVER_ERROR,
+      502: '网关错误',
+      503: '服务不可用',
+      504: '网关超时',
+    };
+
+    return messages[status] || `请求失败 (${status})`;
+  }
+
+  // 显示错误提示(可根据实际使用的 Toast 库调整)
+  private showErrorToast(message: string): void {
+    // 使用你喜欢的 Toast 库,例如 react-native-toast-message
+    // Toast.show({ type: 'error', text1: message });
+    console.error('Error:', message);
+  }
+
+}
+export const apiClient = new ApiClient();

+ 22 - 72
service/walletService.tsx

@@ -1,23 +1,11 @@
-import axios from 'axios';
+import axios, { isAxiosError } from 'axios';
 import * as SecureStore from 'expo-secure-store';
+import {apiClient} from './requets'
 
 class WalletService {
-    private apiUrl: string;
-
-    constructor() {
-        this.apiUrl = process.env.EXPO_PUBLIC_API_URL;
-        if (!this.apiUrl) {
-            throw new Error('API URL is not defined in environment variables');
-        }
-    }
-
     async getCouponForSpecificUser(userID: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/promotion/coupons/${userID}`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/promotion/coupons/${userID}`);
             if (response.status === 200 || response.status === 201) {
                 return response.data;
             } else {
@@ -31,11 +19,7 @@ class WalletService {
 
     async getCustomerInfo() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/customer`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/customer`);
             if (response.status === 200 || response.status === 201) {
                 const info = response.data;
                 return info;
@@ -44,7 +28,7 @@ class WalletService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('get customer info error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -55,21 +39,16 @@ class WalletService {
 
     async getWalletBalance() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/customer/wallet`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/customer/wallet`);
             if (response.status === 200) {
                 const walletBalance = response.data.data;
-
                 return walletBalance;
             } else {
                 console.error('getWalletBalance failed:', response.status);
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('getWallet error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -80,11 +59,7 @@ class WalletService {
 
     async getOutTradeNo() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/qfpay/out_trade_no`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/qfpay/out_trade_no`);
             if (response.status === 200) {
                 const outTradeNo = response.data.out_trade_no;
 
@@ -94,7 +69,7 @@ class WalletService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('get outTradeNo error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -105,11 +80,7 @@ class WalletService {
 
     async getTransactionRecord() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/wallet/transaction/record`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/wallet/transaction/record`);
             if (response.status === 200) {
                 const walletBalance = response.data;
 
@@ -119,7 +90,7 @@ class WalletService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('getWallet error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -156,11 +127,7 @@ class WalletService {
                 is_ic_call
             };
 
-            const response = await axios.post(`${this.apiUrl}/clients/pay`, payload, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.post(`/clients/pay`, payload);
             if (response.status === 200 || response.status === 201) {
                 return response.data;
             } else {
@@ -200,18 +167,14 @@ class WalletService {
                 is_ic_call
             };
 
-            const response = await axios.post(`${this.apiUrl}/clients/pay`, payload, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.post(`/clients/pay`, payload);
             if (response.data.status === 200 || response.data.status === 201) {
                 return response.data.status;
             } else {
                 return response.data;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 return {
                     error: true,
                     status: error.response?.status,
@@ -228,11 +191,7 @@ class WalletService {
 
     async selectPaymentType() {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/qfpay/type`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/qfpay/type`);
             if (response.status === 200 || response.status === 201) {
                 const info = response.data;
                 return info;
@@ -241,7 +200,7 @@ class WalletService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('get customer info error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -252,24 +211,19 @@ class WalletService {
 
     async submitPaymentAfterSelectingType(amount: number, pay_type: string, return_url?: string) {
         try {
-            const response = await axios.get(
-                `${this.apiUrl}/clients/qfpay/session?amount=${amount}&pay_type=${pay_type}&return_url=${return_url}`,
-                {
-                    headers: {
-                        Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                    }
-                }
+            const response = await apiClient.instance.get(
+                `/clients/qfpay/session?amount=${amount}&pay_type=${pay_type}&return_url=${return_url}`
             );
             // if (response.status === 200 || response.status === 201) {
             if (response) {
                 const info = response.data;
                 return info;
             } else {
-                console.error('get customer info failed:', response.status);
+                console.error('get customer info failed:', response);
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('get customer info error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);
@@ -279,11 +233,7 @@ class WalletService {
     }
     async checkPaymentStatus(out_trade_no: string) {
         try {
-            const response = await axios.get(`${this.apiUrl}/clients/qfpay/check/transaction/${out_trade_no}`, {
-                headers: {
-                    Authorization: `Bearer ${await SecureStore.getItemAsync('accessToken')}`
-                }
-            });
+            const response = await apiClient.instance.get(`/clients/qfpay/check/transaction/${out_trade_no}`);
 
             if (Array.isArray(response.data.data) && response.data.data.length > 0) {
                 // If it's not empty, consider it a success and return the data
@@ -293,7 +243,7 @@ class WalletService {
                 return false;
             }
         } catch (error) {
-            if (axios.isAxiosError(error)) {
+            if (isAxiosError(error)) {
                 console.error('check payment status error:', error.response?.data?.message || error.message);
             } else {
                 console.error('An unexpected error occurred:', error);