Create Checkout Function
Create Checkout Function
ts";
import { createClient } from "https://esm.sh/@supabase/[email protected]";
import Stripe from "https://esm.sh/[email protected]";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-
type",
};
try {
logStep("Function started");
// Initialize Stripe
const stripe = new Stripe(stripeKey, {
apiVersion: "2023-10-16",
});
logStep("Stripe initialized");
if (!priceId) {
throw new Error("Price ID is required");
}
if (!supabaseUrl || !supabaseAnonKey) {
throw new Error("Supabase environment variables not configured");
}
if (userError) {
logStep("Error getting user", userError);
}
if (userDataError) {
logStep("Error fetching user data", userDataError);
} else if (userData?.stripe_customer_id) {
// Use existing Stripe customer ID if available
stripeCustomerId = userData.stripe_customer_id;
logStep("Using existing Stripe customer ID", { customerId: stripeCustomerId
});
sessionConfig.customer = stripeCustomerId;
} else {
// Create a new customer in Stripe
const email = userData?.email || user.email;
try {
const customerData = {
email,
metadata: {
user_id: user.id
}
};
if (updateError) {
logStep("Error storing customer ID in profile", updateError);
} else {
logStep("Stored new customer ID in user profile", { customerId:
stripeCustomerId });
}
if (insertError) {
logStep("Error creating payment record", insertError);
// Continue anyway - non-critical
}
} catch (dbError) {
logStep("Error creating payment record", dbError);
// Continue anyway - non-critical
}
} else {
// For guest checkouts with no authentication
logStep("Proceeding with guest checkout (no userId provided)");