test preview
This commit is contained in:
98
src/lib/stripe.ts
Normal file
98
src/lib/stripe.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { loadStripe } from '@stripe/stripe-js';
|
||||
|
||||
// Stripe Configuration
|
||||
export const STRIPE_CONFIG = {
|
||||
publishableKey: import.meta.env.VITE_STRIPE_PUBLISHABLE_KEY || '',
|
||||
apiUrl: import.meta.env.VITE_API_URL || 'http://localhost:3001',
|
||||
};
|
||||
|
||||
// Stripe instance (lazy loaded)
|
||||
let stripePromise: ReturnType<typeof loadStripe> | null = null;
|
||||
|
||||
export function getStripe() {
|
||||
if (!stripePromise && STRIPE_CONFIG.publishableKey) {
|
||||
stripePromise = loadStripe(STRIPE_CONFIG.publishableKey);
|
||||
}
|
||||
return stripePromise;
|
||||
}
|
||||
|
||||
// Types
|
||||
export interface OrderData {
|
||||
websiteType: string;
|
||||
style: string;
|
||||
theme: string;
|
||||
colors: {
|
||||
primary: string;
|
||||
secondary: string;
|
||||
accent: string;
|
||||
};
|
||||
customInput?: {
|
||||
referenceUrl: string;
|
||||
description: string;
|
||||
};
|
||||
contact: {
|
||||
name: string;
|
||||
email: string;
|
||||
company?: string;
|
||||
phone?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CheckoutResponse {
|
||||
sessionId: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface SessionData {
|
||||
id: string;
|
||||
status: string;
|
||||
customerEmail: string;
|
||||
amountTotal: number;
|
||||
metadata: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Stripe Checkout Session via backend API
|
||||
*/
|
||||
export async function createCheckoutSession(orderData: OrderData): Promise<CheckoutResponse> {
|
||||
const response = await fetch(`${STRIPE_CONFIG.apiUrl}/api/checkout`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ orderData }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.details || error.error || 'Failed to create checkout session');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect to Stripe Checkout
|
||||
*/
|
||||
export async function redirectToCheckout(orderData: OrderData): Promise<void> {
|
||||
const { url } = await createCheckoutSession(orderData);
|
||||
|
||||
if (url) {
|
||||
window.location.href = url;
|
||||
} else {
|
||||
throw new Error('No checkout URL returned');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a checkout session (for success page)
|
||||
*/
|
||||
export async function verifySession(sessionId: string): Promise<SessionData> {
|
||||
const response = await fetch(`${STRIPE_CONFIG.apiUrl}/api/session/${sessionId}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Session not found');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
Reference in New Issue
Block a user