import { loadStripe } from '@stripe/stripe-js'; // Initialize Stripe on the client export const getStripe = () => { const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!); return stripePromise; }; // Helper function to create a payment intent (server-side only) export async function createPaymentIntent(amount: number, currency: string = 'usd') { try { console.log('Creating Stripe payment intent with:', { amount, currency }); // This function should only be called from server-side code const { default: Stripe } = await import('stripe'); const stripeSecretKey = process.env.STRIPE_SECRET_KEY; if (!stripeSecretKey) { throw new Error('STRIPE_SECRET_KEY is not configured'); } const stripe = new Stripe(stripeSecretKey, { apiVersion: '2025-05-28.basil', typescript: true, }); console.log('Stripe instance created, creating payment intent...'); const paymentIntent = await stripe.paymentIntents.create({ amount: Math.round(amount * 100), // Convert to cents currency, automatic_payment_methods: { enabled: true, }, }); console.log('Payment intent created:', { id: paymentIntent.id, amount: paymentIntent.amount, currency: paymentIntent.currency, status: paymentIntent.status }); return { clientSecret: paymentIntent.client_secret, paymentIntentId: paymentIntent.id, }; } catch (error) { console.error('Error creating payment intent:', error); throw error; } } // Helper function to create a checkout session (server-side only) export async function createCheckoutSession( boxId: string, boxName: string, amount: number, currency: string = 'usd' ) { try { // This function should only be called from server-side code const { default: Stripe } = await import('stripe'); const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { apiVersion: '2025-05-28.basil', typescript: true, }); const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], line_items: [ { price_data: { currency, product_data: { name: boxName, description: `Mystery Box Purchase - ${boxName}`, }, unit_amount: Math.round(amount * 100), // Convert to cents }, quantity: 1, }, ], mode: 'payment', success_url: `${process.env.NEXT_PUBLIC_BASE_URL}/boxes/success?box_id=${boxId}&session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${process.env.NEXT_PUBLIC_BASE_URL}/boxes?canceled=true`, metadata: { boxId, }, }); return session; } catch (error) { console.error('Error creating checkout session:', error); throw error; } }