The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Rename Stripe integration webhook routes
Steven Teyd52452d6b6df
diff --git a/apps/web/app/api/stripe/connect/callback/route.ts b/apps/web/app/api/stripe/connect/callback/route.tsindex 4ca9489d4f..eb3c7ec861 100644--- a/apps/web/app/api/stripe/connect/callback/route.ts+++ b/apps/web/app/api/stripe/connect/callback/route.ts@@ -1,81 +1 @@-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 });-};+export * from "../../integration/callback/route";diff --git a/apps/web/app/api/stripe/connect/webhook/route.ts b/apps/web/app/api/stripe/connect/webhook/route.tsindex e3a92b11c2..a1108fa804 100644--- a/apps/web/app/api/stripe/connect/webhook/route.ts+++ b/apps/web/app/api/stripe/connect/webhook/route.ts@@ -1,69 +1 @@-import { stripe } from "@/lib/stripe";-import { withAxiom } from "next-axiom";-import Stripe from "stripe";-import { accountApplicationDeauthorized } from "./account-application-deauthorized";-import { checkoutSessionCompleted } from "./checkout-session-completed";-import { customerCreated } from "./customer-created";-import { invoicePaid } from "./invoice-paid";--const relevantEvents = new Set([- "customer.created",- "checkout.session.completed",- "invoice.paid",- "account.application.deauthorized",-]);--export const POST = withAxiom(- async (req: Request) => {- const buf = await req.text();- const sig = req.headers.get("Stripe-Signature");- const webhookSecret = process.env.STRIPE_APP_WEBHOOK_SECRET;-- if (!sig || !webhookSecret) {- return new Response("Invalid request", {- status: 400,- });- }-- let event: Stripe.Event;- try {- event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);- } catch (err: any) {- console.log(`❌ Error message: ${err.message}`);- return new Response(`Webhook Error: ${err.message}`, {- status: 400,- });- }-- // Ignore unsupported events- if (!relevantEvents.has(event.type)) {- return new Response("Unsupported event, skipping...", {- status: 200,- });- }-- let response = "OK";-- switch (event.type) {- case "customer.created":- response = await customerCreated(event);- break;- case "checkout.session.completed":- response = await checkoutSessionCompleted(event);- break;- case "invoice.paid":- response = await invoicePaid(event);- break;- case "account.application.deauthorized":- response = await accountApplicationDeauthorized(event);- break;- }-- return new Response(response, {- status: 200,- });- },- {- logRequestDetails: ["body", "nextUrl"],- },-);+export * from "../../integration/webhook/route";diff --git a/apps/web/app/api/stripe/integration/callback/route.ts b/apps/web/app/api/stripe/integration/callback/route.tsnew file mode 100644index 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 });+};diff --git a/apps/web/app/api/stripe/connect/webhook/account-application-deauthorized.ts b/apps/web/app/api/stripe/integration/webhook/account-application-deauthorized.tssimilarity index 100%rename from apps/web/app/api/stripe/connect/webhook/account-application-deauthorized.tsrename to apps/web/app/api/stripe/integration/webhook/account-application-deauthorized.tsdiff --git a/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts b/apps/web/app/api/stripe/integration/webhook/checkout-session-completed.tssimilarity index 100%rename from apps/web/app/api/stripe/connect/webhook/checkout-session-completed.tsrename to apps/web/app/api/stripe/integration/webhook/checkout-session-completed.tsdiff --git a/apps/web/app/api/stripe/connect/webhook/customer-created.ts b/apps/web/app/api/stripe/integration/webhook/customer-created.tssimilarity index 100%rename from apps/web/app/api/stripe/connect/webhook/customer-created.tsrename to apps/web/app/api/stripe/integration/webhook/customer-created.tsdiff --git a/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts b/apps/web/app/api/stripe/integration/webhook/invoice-paid.tssimilarity index 100%rename from apps/web/app/api/stripe/connect/webhook/invoice-paid.tsrename to apps/web/app/api/stripe/integration/webhook/invoice-paid.tsdiff --git a/apps/web/app/api/stripe/integration/webhook/route.ts b/apps/web/app/api/stripe/integration/webhook/route.tsnew file mode 100644index 0000000000..e3a92b11c2--- /dev/null+++ b/apps/web/app/api/stripe/integration/webhook/route.ts@@ -0,0 +1,69 @@+import { stripe } from "@/lib/stripe";+import { withAxiom } from "next-axiom";+import Stripe from "stripe";+import { accountApplicationDeauthorized } from "./account-application-deauthorized";+import { checkoutSessionCompleted } from "./checkout-session-completed";+import { customerCreated } from "./customer-created";+import { invoicePaid } from "./invoice-paid";++const relevantEvents = new Set([+ "customer.created",+ "checkout.session.completed",+ "invoice.paid",+ "account.application.deauthorized",+]);++export const POST = withAxiom(+ async (req: Request) => {+ const buf = await req.text();+ const sig = req.headers.get("Stripe-Signature");+ const webhookSecret = process.env.STRIPE_APP_WEBHOOK_SECRET;++ if (!sig || !webhookSecret) {+ return new Response("Invalid request", {+ status: 400,+ });+ }++ let event: Stripe.Event;+ try {+ event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);+ } catch (err: any) {+ console.log(`❌ Error message: ${err.message}`);+ return new Response(`Webhook Error: ${err.message}`, {+ status: 400,+ });+ }++ // Ignore unsupported events+ if (!relevantEvents.has(event.type)) {+ return new Response("Unsupported event, skipping...", {+ status: 200,+ });+ }++ let response = "OK";++ switch (event.type) {+ case "customer.created":+ response = await customerCreated(event);+ break;+ case "checkout.session.completed":+ response = await checkoutSessionCompleted(event);+ break;+ case "invoice.paid":+ response = await invoicePaid(event);+ break;+ case "account.application.deauthorized":+ response = await accountApplicationDeauthorized(event);+ break;+ }++ return new Response(response, {+ status: 200,+ });+ },+ {+ logRequestDetails: ["body", "nextUrl"],+ },+);diff --git a/apps/web/lib/integrations/stripe/install.ts b/apps/web/lib/integrations/stripe/install.tsindex c25cb0bc2a..d475be4fc2 100644--- a/apps/web/lib/integrations/stripe/install.ts+++ b/apps/web/lib/integrations/stripe/install.ts@@ -25,7 +25,7 @@ export const getStripeInstallationUrl = async (workspaceId: string) => {const url = new URL(STRIPE_APP_INSTALL_URL);url.searchParams.set("redirect_uri",- `${APP_DOMAIN_WITH_NGROK}/api/stripe/connect/callback`,+ `${APP_DOMAIN_WITH_NGROK}/api/stripe/integration/callback`,);url.searchParams.set("state", state);diff --git a/packages/stripe-app/stripe-app.json b/packages/stripe-app/stripe-app.jsonindex c6d4979f74..d072babe7c 100644--- a/packages/stripe-app/stripe-app.json+++ b/packages/stripe-app/stripe-app.json@@ -46,8 +46,10 @@},"allowed_redirect_uris": ["https://app.dub.co/api/stripe/connect/callback",- "https://preview.dub.co/api/stripe/connect/callback"+ "https://preview.dub.co/api/stripe/connect/callback",+ "https://app.dub.co/api/stripe/integration/callback",+ "https://preview.dub.co/api/stripe/integration/callback"],"stripe_api_access_type": "oauth","distribution_type": "public"-}\ No newline at end of file+}