102 lines
2.5 KiB
TypeScript
102 lines
2.5 KiB
TypeScript
import { API_BASE_URL } from './config';
|
|
|
|
export interface StripeCredentials {
|
|
publishableKey: string;
|
|
enabled: boolean;
|
|
testMode: boolean;
|
|
}
|
|
|
|
export interface PaymentIntent {
|
|
id: string;
|
|
amount: number;
|
|
currency: string;
|
|
status: string;
|
|
clientSecret: string;
|
|
}
|
|
|
|
class PaymentService {
|
|
private async getAuthToken(): Promise<string | null> {
|
|
return localStorage.getItem('auth_token');
|
|
}
|
|
|
|
async getStripeCredentials(): Promise<StripeCredentials | null> {
|
|
try {
|
|
const token = await this.getAuthToken();
|
|
const response = await fetch(`${API_BASE_URL}/config/payments/stripe/credentials`, {
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to fetch Stripe credentials');
|
|
}
|
|
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error('Error fetching Stripe credentials:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async createPaymentIntent(data: {
|
|
amount: number;
|
|
currency: string;
|
|
description?: string;
|
|
metadata?: Record<string, string>;
|
|
}): Promise<PaymentIntent> {
|
|
const token = await this.getAuthToken();
|
|
|
|
const response = await fetch(`${API_BASE_URL}/payments/create-intent`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(data),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to create payment intent');
|
|
}
|
|
|
|
return await response.json();
|
|
}
|
|
|
|
async confirmPayment(paymentIntentId: string): Promise<boolean> {
|
|
const token = await this.getAuthToken();
|
|
|
|
const response = await fetch(`${API_BASE_URL}/payments/confirm`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({ paymentIntentId }),
|
|
});
|
|
|
|
return response.ok;
|
|
}
|
|
|
|
async getPaymentStatus(paymentIntentId: string): Promise<string> {
|
|
const token = await this.getAuthToken();
|
|
|
|
const response = await fetch(`${API_BASE_URL}/payments/status/${paymentIntentId}`, {
|
|
headers: {
|
|
'Authorization': `Bearer ${token}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error('Failed to get payment status');
|
|
}
|
|
|
|
const data = await response.json();
|
|
return data.status;
|
|
}
|
|
}
|
|
|
|
export const paymentService = new PaymentService();
|