bookwiz.io / lib / hooks / useStripeCheckout.ts
useStripeCheckout.ts
Raw
import { useState } from 'react';
import { getStripe } from '@/lib/stripe';
import { supabase } from '@/lib/supabase';

export function useStripeCheckout() {
  const [loading, setLoading] = useState(false);

  const handleCheckout = async (priceId: string) => {
    try {
      setLoading(true);

      // Get the current session to access the access token
      const { data: { session } } = await supabase.auth.getSession();
      
      if (!session?.access_token) {
        throw new Error('Not authenticated');
      }

      // Create a checkout session
      const response = await fetch('/api/create-checkout-session', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${session.access_token}`,
        },
        body: JSON.stringify({ priceId }),
      });

      const { sessionId, error } = await response.json();

      if (error) {
        throw new Error(error);
      }

      // Redirect to Stripe checkout
      const stripe = await getStripe();
      const { error: stripeError } = await stripe!.redirectToCheckout({
        sessionId,
      });

      if (stripeError) {
        throw new Error(stripeError.message);
      }
    } catch (error) {
      console.error('Error:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return {
    handleCheckout,
    loading,
  };
}