Skip to content

Commit

Permalink
Create route.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
devkiran committed Jan 17, 2025
1 parent 76a5be7 commit 8f6d344
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions apps/web/app/api/stripe/integration/callback/route.ts
Original file line number Diff line number Diff line change
@@ -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 });
};

0 comments on commit 8f6d344

Please sign in to comment.