Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Create route.ts

Kiran K8f6d3445f3cd
diff --git a/apps/web/app/api/stripe/integration/callback/route.ts b/apps/web/app/api/stripe/integration/callback/route.ts
new file mode 100644
index 0000000000..4ca9489d4f
--- /dev/null
+++ b/apps/web/app/api/stripe/integration/callback/route.ts
@@ -0,0 +1,81 @@
+import { getSession } from "@/lib/auth";
+import { installIntegration } from "@/lib/integrations/install";
+import { redis } from "@/lib/upstash";
+import z from "@/lib/zod";
+import { prisma } from "@dub/prisma";
+import { APP_DOMAIN, getSearchParams, STRIPE_INTEGRATION_ID } from "@dub/utils";
+import { redirect } from "next/navigation";
+import { NextRequest } from "next/server";
+
+const schema = z.object({
+ state: z.string(),
+ stripe_user_id: z.string().optional(),
+ error: z.string().optional(),
+ error_description: z.string().optional(),
+});
+
+export const GET = async (req: NextRequest) => {
+ const session = await getSession();
+
+ if (!session?.user.id) {
+ return new Response("Unauthorized", { status: 401 });
+ }
+
+ const parsed = schema.safeParse(getSearchParams(req.url));
+
+ if (!parsed.success) {
+ console.error("[Stripe OAuth callback] Error", parsed.error);
+ return new Response("Invalid request", { status: 400 });
+ }
+
+ const {
+ state,
+ stripe_user_id: stripeAccountId,
+ error,
+ error_description,
+ } = parsed.data;
+
+ // Find workspace that initiated the Stripe app install
+ const workspaceId = await redis.get<string>(`stripe:install:state:${state}`);
+
+ if (!workspaceId) {
+ redirect(APP_DOMAIN);
+ }
+
+ // Delete the state key from Redis
+ await redis.del(`stripe:install:state:${state}`);
+
+ if (error) {
+ const workspace = await prisma.project.findUnique({
+ where: {
+ id: workspaceId,
+ },
+ });
+ if (!workspace) {
+ redirect(APP_DOMAIN);
+ }
+ redirect(
+ `${APP_DOMAIN}/${workspace.slug}/settings/integrations/stripe?stripeConnectError=${error_description}`,
+ );
+ } else if (stripeAccountId) {
+ // Update the workspace with the Stripe Connect ID
+ const workspace = await prisma.project.update({
+ where: {
+ id: workspaceId,
+ },
+ data: {
+ stripeConnectId: stripeAccountId,
+ },
+ });
+
+ await installIntegration({
+ integrationId: STRIPE_INTEGRATION_ID,
+ userId: session.user.id,
+ workspaceId: workspace.id,
+ });
+
+ redirect(`${APP_DOMAIN}/${workspace.slug}/settings/integrations/stripe`);
+ }
+
+ return new Response("Invalid request", { status: 400 });
+};