import { headers } from 'next/headers'; // 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', request?: Request ) { 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, }); // Determine the base URL dynamically let baseUrl = process.env.NEXT_PUBLIC_BASE_URL; if (!baseUrl && request) { // Fallback: extract from request headers const headersList = await headers(); const host = headersList.get('host'); const protocol = headersList.get('x-forwarded-proto') || 'http'; if (host) { baseUrl = `${protocol}://${host}`; } } // Final fallback for development if (!baseUrl) { baseUrl = 'http://localhost:3000'; } console.log('Using base URL for Stripe checkout:', baseUrl); 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: `${baseUrl}/boxes/success?box_id=${boxId}&session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${baseUrl}/boxes?canceled=true`, metadata: { boxId, }, }); return session; } catch (error) { console.error('Error creating checkout session:', error); throw error; } }