bookwiz.io / app / api / create-checkout-session / route.ts
route.ts
Raw
import { NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import { createClient } from '@supabase/supabase-js';

export async function POST(req: Request) {
  try {
    const { priceId } = await req.json();
    
    // Get the Authorization header
    const authHeader = req.headers.get('authorization');
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        { error: 'Not authenticated' },
        { status: 401 }
      );
    }

    const token = authHeader.replace('Bearer ', '');

    // Create Supabase client with the access token
    const supabase = createClient(
      process.env.NEXT_PUBLIC_SUPABASE_URL!,
      process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
      {
        global: {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      }
    );

    // Get the user from the token
    const { data: { user }, error: userError } = await supabase.auth.getUser();
    
    if (userError || !user) {
      return NextResponse.json(
        { error: 'Not authenticated' },
        { status: 401 }
      );
    }

    // Get the base URL with fallback
    const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000';
    console.log('Base URL from env:', process.env.NEXT_PUBLIC_BASE_URL);
    console.log('Using base URL:', baseUrl);

    // Validate the base URL
    try {
      new URL(baseUrl);
    } catch (urlError) {
      console.error('Invalid base URL:', baseUrl);
      return NextResponse.json(
        { error: 'Invalid base URL configuration' },
        { status: 500 }
      );
    }

    const successUrl = `${baseUrl}/billing?success=true`;
    const cancelUrl = `${baseUrl}/pricing`;

    console.log('Success URL:', successUrl);
    console.log('Cancel URL:', cancelUrl);

    // Create or update customer with metadata
    let customer;
    try {
      // Try to find existing customer by email
      const customers = await stripe!.customers.list({
        email: user.email,
        limit: 1,
      });

      if (customers.data.length > 0) {
        // Update existing customer with metadata
        customer = await stripe!.customers.update(customers.data[0].id, {
          metadata: {
            userId: user.id,
          },
        });
      } else {
        // Create new customer with metadata
        customer = await stripe!.customers.create({
          email: user.email,
          metadata: {
            userId: user.id,
          },
        });
      }
    } catch (error) {
      console.error('Error handling customer:', error);
      return NextResponse.json(
        { error: 'Error setting up customer' },
        { status: 500 }
      );
    }

    // Create a checkout session
    const checkoutSession = await stripe!.checkout.sessions.create({
      mode: 'subscription',
      payment_method_types: ['card'],
      line_items: [
        {
          price: priceId,
          quantity: 1,
        },
      ],
      success_url: successUrl,
      cancel_url: cancelUrl,
      customer: customer.id,
      metadata: {
        userId: user.id,
      },
      subscription_data: {
        metadata: {
          userId: user.id,
        },
      },
    });

    return NextResponse.json({ sessionId: checkoutSession.id });
  } catch (error) {
    console.error('Error creating checkout session:', error);
    return NextResponse.json(
      { error: 'Error creating checkout session' },
      { status: 500 }
    );
  }
}