Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Refactor stripe checkout code (#1784)

Luke Vella1cec524d0f15
diff --git a/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx b/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx
index 40bb2d437..fa78dc8d2 100644
--- a/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/billing/page.tsx
@@ -30,9 +30,9 @@ import {
import { PayWallDialog } from "@/components/pay-wall-dialog";
import { Trans } from "@/components/trans";
import { FormattedDateTime } from "@/features/timezone/client/formatted-date-time";
-import { requireUser } from "@/next-auth";
import { isSelfHosted } from "@/utils/constants";
+import { requireUser } from "@/auth/queries";
import {
SettingsContent,
SettingsSection,
@@ -42,10 +42,10 @@ import { SubscriptionPrice } from "./components/subscription-price";
import { SubscriptionStatus } from "./components/subscription-status";
async function getData() {
- const { userId } = await requireUser();
+ const user = await requireUser();
const data = await prisma.user.findUnique({
- where: { id: userId },
+ where: { id: user.id },
select: {
customerId: true,
subscription: {
diff --git a/apps/web/src/app/api/stripe/checkout/route.ts b/apps/web/src/app/api/stripe/checkout/route.ts
index 00a746317..f5f544a58 100644
--- a/apps/web/src/app/api/stripe/checkout/route.ts
+++ b/apps/web/src/app/api/stripe/checkout/route.ts
@@ -5,11 +5,11 @@ import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { z } from "zod";
+import { getActiveSpace, requireUser } from "@/auth/queries";
import type {
SubscriptionCheckoutMetadata,
SubscriptionMetadata,
} from "@/features/subscription/schema";
-import { auth } from "@/next-auth";
const inputSchema = z.object({
period: z.enum(["monthly", "yearly"]).optional(),
@@ -18,63 +18,31 @@ const inputSchema = z.object({
});
export async function POST(request: NextRequest) {
- const userSession = await auth();
+ const user = await requireUser();
const formData = await request.formData();
- const { period = "monthly", return_path } = inputSchema.parse(
- Object.fromEntries(formData.entries()),
- );
+ const data = inputSchema.safeParse(Object.fromEntries(formData.entries()));
- if (!userSession?.user || userSession.user?.email === null) {
- // You need to be logged in to subscribe
- return NextResponse.redirect(
- new URL(
- `/login${
- return_path ? `?redirect=${encodeURIComponent(return_path)}` : ""
- }`,
- request.url,
- ),
- 303,
- );
+ if (!data.success) {
+ return NextResponse.json(data.error, { status: 400 });
}
- const user = await prisma.user.findUnique({
+ const { period, return_path } = data.data;
+
+ let customerId: string;
+
+ const res = await prisma.user.findUniqueOrThrow({
where: {
- id: userSession.user.id,
+ id: user.id,
},
select: {
- email: true,
- name: true,
customerId: true,
- subscription: {
- select: {
- active: true,
- },
- },
- spaces: {
- select: {
- id: true,
- },
- },
},
});
- if (!user) {
- return NextResponse.json(
- { error: `User with ID ${userSession.user.id} not found` },
- { status: 404 },
- );
- }
-
- if (user.spaces.length === 0) {
- return NextResponse.json(
- { error: `Space with owner ID ${userSession.user.id} not found` },
- { status: 404 },
- );
- }
-
- let customerId = user.customerId;
-
- if (!customerId) {
+ if (res.customerId) {
+ customerId = res.customerId;
+ } else {
+ // create a new customer in stripe
const customer = await stripe.customers.create({
email: user.email,
name: user.name,
@@ -82,7 +50,7 @@ export async function POST(request: NextRequest) {
await prisma.user.update({
where: {
- id: userSession.user.id,
+ id: user.id,
},
data: {
customerId: customer.id,
@@ -92,7 +60,7 @@ export async function POST(request: NextRequest) {
customerId = customer.id;
}
- if (user.subscription?.active === true) {
+ if (user.isPro) {
// User already has an active subscription. Take them to customer portal
return NextResponse.redirect(
new URL("/api/stripe/portal", request.url),
@@ -102,9 +70,11 @@ export async function POST(request: NextRequest) {
const proPricingData = await getProPricing();
- const spaceId = user.spaces[0].id;
+ const space = await getActiveSpace();
+
+ const spaceId = space.id;
- const session = await stripe.checkout.sessions.create({
+ const checkoutSession = await stripe.checkout.sessions.create({
success_url: absoluteUrl(
return_path ?? "/api/stripe/portal?session_id={CHECKOUT_SESSION_ID}",
),
@@ -121,12 +91,12 @@ export async function POST(request: NextRequest) {
enabled: true,
},
metadata: {
- userId: userSession.user.id,
+ userId: user.id,
spaceId,
} satisfies SubscriptionCheckoutMetadata,
subscription_data: {
metadata: {
- userId: userSession.user.id,
+ userId: user.id,
spaceId,
} satisfies SubscriptionMetadata,
},
@@ -151,9 +121,9 @@ export async function POST(request: NextRequest) {
},
});
- if (session.url) {
+ if (checkoutSession.url) {
// redirect to checkout session
- return NextResponse.redirect(session.url, 303);
+ return NextResponse.redirect(checkoutSession.url, 303);
}
return NextResponse.json(
diff --git a/apps/web/src/next-auth.ts b/apps/web/src/next-auth.ts
index b0523b0be..5765dceaa 100644
--- a/apps/web/src/next-auth.ts
+++ b/apps/web/src/next-auth.ts
@@ -2,7 +2,6 @@ import { prisma } from "@rallly/database";
import { posthog } from "@rallly/posthog/server";
import NextAuth from "next-auth";
import type { Provider } from "next-auth/providers";
-import { redirect } from "next/navigation";
import { cache } from "react";
import { CustomPrismaAdapter } from "./auth/adapters/prisma";
@@ -171,14 +170,6 @@ const auth = cache(async () => {
}
});
-const requireUser = async () => {
- const session = await auth();
- if (!session?.user) {
- redirect("/login");
- }
- return { userId: session.user.id };
-};
-
/**
* If email is not set it means the user is a guest
* @returns
@@ -193,4 +184,4 @@ export const getLoggedIn = async () => {
return !!session?.user?.email;
};
-export { auth, handlers, requireUser, signIn, signOut };
+export { auth, handlers, signIn, signOut };