Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Add guest checkout flow and user creation (#778)

Richie McIlroy136711c74106
diff --git a/apps/web/app/api/settings/billing/guest-checkout/route.ts b/apps/web/app/api/settings/billing/guest-checkout/route.ts
new file mode 100644
index 000000000..04f989f31
--- /dev/null
+++ b/apps/web/app/api/settings/billing/guest-checkout/route.ts
@@ -0,0 +1,65 @@
+import { stripe } from "@cap/utils";
+import { NextRequest } from "next/server";
+import { buildEnv, serverEnv } from "@cap/env";
+import { PostHog } from "posthog-node";
+
+export async function POST(request: NextRequest) {
+ console.log("Starting guest checkout process");
+ const { priceId, quantity } = await request.json();
+
+ console.log("Received guest checkout request:", { priceId, quantity });
+
+ if (!priceId) {
+ console.error("Missing required priceId");
+ return Response.json({ error: "priceId is required" }, { status: 400 });
+ }
+
+ try {
+ console.log("Creating guest checkout session");
+ const checkoutSession = await stripe().checkout.sessions.create({
+ line_items: [{ price: priceId, quantity: quantity || 1 }],
+ mode: "subscription",
+ success_url: `${serverEnv().WEB_URL}/dashboard/caps?upgrade=true&guest=true`,
+ cancel_url: `${serverEnv().WEB_URL}/pricing`,
+ allow_promotion_codes: true,
+ customer_creation: "always", // This ensures Stripe creates a customer
+ metadata: {
+ platform: "web",
+ guestCheckout: "true",
+ },
+ });
+
+ if (checkoutSession.url) {
+ console.log("Successfully created guest checkout session");
+
+ try {
+ const ph = new PostHog(buildEnv.NEXT_PUBLIC_POSTHOG_KEY || "", {
+ host: buildEnv.NEXT_PUBLIC_POSTHOG_HOST || "",
+ });
+
+ ph.capture({
+ distinctId: "guest-" + checkoutSession.id,
+ event: "guest_checkout_started",
+ properties: {
+ price_id: priceId,
+ quantity: quantity || 1,
+ platform: "web",
+ session_id: checkoutSession.id,
+ },
+ });
+
+ await ph.shutdown();
+ } catch (e) {
+ console.error("Failed to capture guest_checkout_started in PostHog", e);
+ }
+
+ return Response.json({ url: checkoutSession.url }, { status: 200 });
+ }
+
+ console.error("Checkout session created but no URL returned");
+ return Response.json({ error: "Failed to create checkout session" }, { status: 400 });
+ } catch (error) {
+ console.error("Error creating guest checkout session:", error);
+ return Response.json({ error: "Internal server error" }, { status: 500 });
+ }
+}
\ No newline at end of file
diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.ts
index 85719d287..4f413431d 100644
--- a/apps/web/app/api/webhooks/stripe/route.ts
+++ b/apps/web/app/api/webhooks/stripe/route.ts
@@ -6,6 +6,7 @@ import { NextResponse } from "next/server";
import Stripe from "stripe";
import { buildEnv, serverEnv } from "@cap/env";
import { PostHog } from "posthog-node";
+import { nanoId } from "@cap/database/helpers";
const relevantEvents = new Set([
"checkout.session.completed",
@@ -13,7 +14,33 @@ const relevantEvents = new Set([
"customer.subscription.deleted",
]);
-// Helper function to find user with retries
+async function createGuestUser(email: string): Promise<typeof users.$inferSelect> {
+ const userId = nanoId();
+
+ await db().insert(users).values({
+ id: userId,
+ email: email,
+ emailVerified: null,
+ name: null,
+ image: null,
+ activeOrganizationId: "",
+ });
+
+
+ const result = await db()
+ .select()
+ .from(users)
+ .where(eq(users.id, userId))
+ .limit(1);
+
+ const newUser = result[0];
+ if (!newUser) {
+ throw new Error("Failed to create user");
+ }
+
+ return newUser;
+}
+
async function findUserWithRetry(
email: string,
userId?: string,
@@ -26,7 +53,6 @@ async function findUserWithRetry(
});
try {
- // Try finding by userId first if available
if (userId) {
console.log(`Attempting to find user by ID: ${userId}`);
const userById = await db()
@@ -43,7 +69,6 @@ async function findUserWithRetry(
console.log(`No user found by ID: ${userId}`);
}
- // If not found by ID or no ID provided, try email
if (email) {
console.log(`Attempting to find user by email: ${email}`);
const userByEmail = await db()
@@ -60,9 +85,8 @@ async function findUserWithRetry(
console.log(`No user found by email: ${email}`);
}
- // If we reach here, no user was found on this attempt
if (i < maxRetries - 1) {
- const delay = Math.pow(2, i) * 3000; // 3s, 6s, 12s, 24s, 48s
+ const delay = Math.pow(2, i) * 3000;
console.log(
`No user found on attempt ${
i + 1
@@ -72,7 +96,6 @@ async function findUserWithRetry(
}
} catch (error) {
console.error(`Error during attempt ${i + 1}:`, error);
- // If this is not the last attempt, continue to next retry
if (i < maxRetries - 1) {
const delay = Math.pow(2, i) * 3000;
await new Promise((resolve) => setTimeout(resolve, delay));
@@ -141,12 +164,35 @@ export const POST = async (req: Request) => {
customerEmail,
});
- // Try to find user with retries
- const dbUser = await findUserWithRetry(
+ let dbUser = await findUserWithRetry(
customerEmail as string,
foundUserId
);
+ if (!dbUser && session.metadata?.guestCheckout === "true") {
+ const guestEmail = customerEmail || session.customer_details?.email;
+
+ if (!guestEmail) {
+ console.error("No email found for guest checkout");
+ return new Response("No email found for guest checkout", { status: 400 });
+ }
+
+ console.log("Guest checkout detected, creating new user with email:", guestEmail);
+ try {
+ dbUser = await createGuestUser(guestEmail);
+
+ await stripe().customers.update(customer.id, {
+ metadata: {
+ ...("metadata" in customer ? customer.metadata : {}),
+ userId: dbUser.id
+ },
+ });
+ } catch (error) {
+ console.error("Failed to create guest user:", error);
+ return new Response("Failed to create user", { status: 500 });
+ }
+ }
+
if (!dbUser) {
console.log(
"No user found after all retries. Returning 202 to allow retry."
@@ -194,16 +240,14 @@ export const POST = async (req: Request) => {
console.log("Successfully updated user in database");
- // Add server-side PostHog tracking here:
try {
- // Initialize server-side PostHog
const serverPostHog = new PostHog(
buildEnv.NEXT_PUBLIC_POSTHOG_KEY || "",
{ host: buildEnv.NEXT_PUBLIC_POSTHOG_HOST || "" }
);
const isFirstPurchase = !dbUser.stripeSubscriptionId;
- // Track purchase completed event
+ const isGuestCheckout = session.metadata?.guestCheckout === "true";
serverPostHog.capture({
distinctId: dbUser.id,
event: "purchase_completed",
@@ -217,15 +261,14 @@ export const POST = async (req: Request) => {
(session.metadata && (session.metadata as any).platform) ||
"web",
is_first_purchase: isFirstPurchase,
+ is_guest_checkout: isGuestCheckout,
},
});
- // Shutdown the client
await serverPostHog.shutdown();
console.log("Successfully tracked purchase event in PostHog");
} catch (error) {
console.error("Error tracking purchase in PostHog:", error);
- // Don't throw - we don't want to fail the webhook because of analytics
}
}
@@ -262,7 +305,6 @@ export const POST = async (req: Request) => {
customerEmail,
});
- // Try to find user with retries
const dbUser = await findUserWithRetry(
customerEmail as string,
foundUserId
@@ -283,7 +325,6 @@ export const POST = async (req: Request) => {
name: dbUser.name,
});
- // Get all active subscriptions for this customer
const subscriptions = await stripe().subscriptions.list({
customer: customer.id,
status: "active",
@@ -293,7 +334,6 @@ export const POST = async (req: Request) => {
count: subscriptions.data.length,
});
- // Calculate total invite quota based on all active subscriptions
const inviteQuota = subscriptions.data.reduce((total, sub) => {
return (
total +
@@ -348,7 +388,6 @@ export const POST = async (req: Request) => {
if (userByEmail && userByEmail.length > 0 && userByEmail[0]) {
foundUserId = userByEmail[0].id;
console.log(`User found by email: ${foundUserId}`);
- // Update customer metadata with userId
await stripe().customers.update(customer.id, {
metadata: { userId: foundUserId },
});
@@ -381,7 +420,7 @@ export const POST = async (req: Request) => {
.set({
stripeSubscriptionId: subscription.id,
stripeSubscriptionStatus: subscription.status,
- inviteQuota: 1, // Reset to default quota
+ inviteQuota: 1,
})
.where(eq(users.id, foundUserId));
diff --git a/apps/web/components/pages/HomePage/Pricing/ProCard.tsx b/apps/web/components/pages/HomePage/Pricing/ProCard.tsx
index 55e244eca..59c83e476 100644
--- a/apps/web/components/pages/HomePage/Pricing/ProCard.tsx
+++ b/apps/web/components/pages/HomePage/Pricing/ProCard.tsx
@@ -14,6 +14,7 @@ export const ProCard = () => {
const [users, setUsers] = useState(1);
const [isAnnually, setIsAnnually] = useState(true);
const [proLoading, setProLoading] = useState(false);
+ const [guestLoading, setGuestLoading] = useState(false);
const proArtRef = useRef<ProArtRef>(null);
const { push } = useRouter();
@@ -33,6 +34,31 @@ export const ProCard = () => {
const incrementUsers = () => setUsers((prev) => prev + 1);
const decrementUsers = () => setUsers((prev) => (prev > 1 ? prev - 1 : 1));
+ const guestCheckout = async (planId: string) => {
+ setGuestLoading(true);
+
+ try {
+ const response = await fetch(`/api/settings/billing/guest-checkout`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ priceId: planId, quantity: users }),
+ });
+ const data = await response.json();
+
+ if (data.url) {
+ window.location.href = data.url;
+ } else {
+ toast.error("Failed to create checkout session");
+ }
+ } catch (error) {
+ toast.error("An error occurred. Please try again.");
+ } finally {
+ setGuestLoading(false);
+ }
+ };
+
const planCheckout = async (planId?: string) => {
setProLoading(true);
@@ -50,9 +76,9 @@ export const ProCard = () => {
const data = await response.json();
if (data.auth === false) {
- localStorage.setItem("pendingPriceId", planId);
- localStorage.setItem("pendingQuantity", users.toString());
- push(`/login?next=/pricing`);
+ // User not authenticated, do guest checkout
+ setProLoading(false);
+ await guestCheckout(planId);
return;
}
@@ -226,11 +252,11 @@ export const ProCard = () => {
variant="blue"
size="lg"
onClick={() => planCheckout()}
- disabled={proLoading}
+ disabled={proLoading || guestLoading}
className="w-full font-medium"
aria-label="Purchase Cap Pro License"
>
- {proLoading ? "Loading..." : homepageCopy.pricing.pro.cta}
+ {proLoading || guestLoading ? "Loading..." : homepageCopy.pricing.pro.cta}
</Button>
</div>
);
diff --git a/packages/database/auth/auth-options.tsx b/packages/database/auth/auth-options.tsx
index e1f42cbd6..f9ddabb1b 100644
--- a/packages/database/auth/auth-options.tsx
+++ b/packages/database/auth/auth-options.tsx
@@ -104,11 +104,20 @@ export const authOptions = (): NextAuthOptions => {
},
events: {
async signIn({ user, account, isNewUser }) {
- if (isNewUser) {
+ // Check if user needs organization setup (new user or guest checkout user)
+ const [dbUser] = await db()
+ .select()
+ .from(users)
+ .where(eq(users.id, user.id))
+ .limit(1);
+
+ const needsOrganizationSetup = isNewUser || (!dbUser?.activeOrganizationId || dbUser.activeOrganizationId === "");
+
+ if (needsOrganizationSetup) {
const dubId = cookies().get("dub_id")?.value;
const dubPartnerData = cookies().get("dub_partner_data")?.value;
- if (dubId) {
+ if (dubId && isNewUser) {
try {
console.log("Attempting to track lead with Dub...");
const trackResult = await dub().track.lead({
@@ -133,8 +142,8 @@ export const authOptions = (): NextAuthOptions => {
console.error("Failed to track lead with Dub:", error);
console.error("Error details:", JSON.stringify(error, null, 2));
}
- } else {
- console.log("No dub_id cookie found - referral tracking skipped");
+ } else if (!isNewUser) {
+ console.log("Guest checkout user signing in for the first time - setting up organization");
}
const organizationId = nanoId();