The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Centralize Stripe integration webhook workspace resolution
Kiran Kfd58d4b4b582
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/account-application-deauthorized.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/account-application-deauthorized.tsindex 334d301308..5b61ab6821 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/account-application-deauthorized.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/account-application-deauthorized.ts@@ -1,39 +1,21 @@-import { StripeMode } from "@/lib/types";import { prisma } from "@dub/prisma";import { STRIPE_INTEGRATION_ID } from "@dub/utils";-import type Stripe from "stripe";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";// Handle event "account.application.deauthorized"-export async function accountApplicationDeauthorized(- event: Stripe.AccountApplicationDeauthorizedEvent,- mode: StripeMode,-) {- const stripeAccountId = event.account;-+export async function accountApplicationDeauthorized({+ mode,+ workspace,+}: StripeWebhookInput): Promise<StripeWebhookOutput> {if (mode === "test") {return {- response: `Stripe Connect account ${stripeAccountId} deauthorized in test mode. Skipping...`,- };- }-- const workspace = await prisma.project.findUnique({- where: {- stripeConnectId: stripeAccountId,- },- select: {- id: true,- },- });-- if (!workspace) {- return {- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,+ response: `Stripe Connect account ${workspace.stripeConnectId} deauthorized in test mode. Skipping...`,};}await prisma.project.update({where: {- stripeConnectId: stripeAccountId,+ stripeConnectId: workspace.stripeConnectId!,},data: {stripeConnectId: null,@@ -51,7 +33,6 @@ export async function accountApplicationDeauthorized(});return {- response: `Stripe Connect account ${stripeAccountId} deauthorized for workspace ${workspace.id}`,- workspaceId: workspace.id,+ response: `Stripe Connect account ${workspace.stripeConnectId} deauthorized for workspace ${workspace.id}`,};}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/charge-refunded.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/charge-refunded.tsindex c1719e1710..f7bb3ffad2 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/charge-refunded.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/charge-refunded.ts@@ -1,15 +1,18 @@import { trackCommissionStatusUpdate } from "@/lib/api/commissions/track-commission-update-activity-log";import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";import { stripeAppClient } from "@/lib/stripe";-import { StripeMode } from "@/lib/types";import { prisma } from "@dub/prisma";import type Stripe from "stripe";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";// Handle event "charge.refunded"-export async function chargeRefunded(- event: Stripe.ChargeRefundedEvent,- mode: StripeMode,-) {+export async function chargeRefunded({+ event,+ mode,+ workspace,+}: StripeWebhookInput & {+ event: Stripe.ChargeRefundedEvent;+}): Promise<StripeWebhookOutput> {const charge = event.data.object;const stripeAccountId = event.account as string;@@ -39,28 +42,9 @@ export async function chargeRefunded(};}- const workspace = await prisma.project.findUnique({- where: {- stripeConnectId: stripeAccountId,- },- select: {- id: true,- programs: true,- },- });-- if (!workspace) {- return {- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,- };- }-- const workspaceId = workspace.id;-- if (!workspace.programs.length) {+ if (!workspace.defaultProgramId) {return {- response: `Workspace ${workspaceId} for stripe account ${stripeAccountId} has no programs, skipping...`,- workspaceId,+ response: `Workspace ${workspace.id} for stripe account ${stripeAccountId} has no default program, skipping...`,};}@@ -68,7 +52,7 @@ export async function chargeRefunded(where: {invoiceId_programId: {invoiceId: invoicePayment.invoice as string,- programId: workspace.programs[0].id,+ programId: workspace.defaultProgramId,},},select: {@@ -85,14 +69,12 @@ export async function chargeRefunded(if (!commission) {return {response: `Commission not found for invoice ${invoicePayment.invoice}`,- workspaceId,};}if (commission.status === "paid") {return {response: `Commission ${commission.id} is already paid, skipping...`,- workspaceId,};}@@ -142,6 +124,5 @@ export async function chargeRefunded(return {response: `Commission ${commission.id} updated to status "refunded"`,- workspaceId,};}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsindex 1627cd2477..117a801451 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts@@ -30,13 +30,17 @@ import type Stripe from "stripe";import { getCheckoutSessionProductId } from "./utils/get-checkout-session-product-id";import { getConnectedCustomer } from "./utils/get-connected-customer";import { getPromotionCode } from "./utils/get-promotion-code";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";import { updateCustomerWithStripeCustomerId } from "./utils/update-customer-with-stripe-customer-id";// Handle event "checkout.session.completed"-export async function checkoutSessionCompleted(- event: Stripe.CheckoutSessionCompletedEvent,- mode: StripeMode,-) {+export async function checkoutSessionCompleted({+ event,+ mode,+ workspace,+}: StripeWebhookInput & {+ event: Stripe.CheckoutSessionCompletedEvent;+}): Promise<StripeWebhookOutput> {let charge = event.data.object;let dubCustomerExternalId =charge.metadata?.dubCustomerExternalId || charge.metadata?.dubCustomerId;@@ -57,24 +61,6 @@ export async function checkoutSessionCompleted(let leadEvent: LeadEventTB | undefined;let linkId: string | undefined;- const workspace = await prisma.project.findUnique({- where: {- stripeConnectId: stripeAccountId,- },- select: {- id: true,- stripeConnectId: true,- defaultProgramId: true,- webhookEnabled: true,- },- });-- if (!workspace) {- return {- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,- };- }-/*for stripe checkout links:- if client_reference_id is a dub_id, we find the click event@@ -89,7 +75,6 @@ export async function checkoutSessionCompleted(if (!clickEvent) {return {response: `Click event with dub_id ${dubClickId} not found, skipping...`,- workspaceId: workspace.id,};}@@ -206,13 +191,11 @@ export async function checkoutSessionCompleted(} else {return {response: `Failed to attribute via promotion code ${promotionCodeId}, skipping...`,- workspaceId: workspace.id,};}} else {return {response: `dubCustomerExternalId was provided but customer with dubCustomerExternalId ${dubCustomerExternalId} not found on Dub, skipping...`,- workspaceId: workspace.id,};}}@@ -260,7 +243,6 @@ export async function checkoutSessionCompleted(if (!customer) {return {response: `dubCustomerExternalId was found on the connected customer ${stripeCustomerId} but customer with dubCustomerExternalId ${dubCustomerExternalId} not found on Dub, skipping...`,- workspaceId: workspace.id,};}} else if (promotionCodeId) {@@ -276,13 +258,11 @@ export async function checkoutSessionCompleted(} else {return {response: `Failed to attribute via promotion code ${promotionCodeId}, skipping...`,- workspaceId: workspace.id,};}} else {return {response: `dubCustomerExternalId not found in Stripe checkout session metadata (nor is it available on the connected customer ${stripeCustomerId}), client_reference_id is not a dub_id, and promotion code is not provided, skipping...`,- workspaceId: workspace.id,};}}@@ -294,7 +274,6 @@ export async function checkoutSessionCompleted(if (!leadEventData) {return {response: `No lead event found for customer ${customer.id}, skipping...`,- workspaceId: workspace.id,};}leadEvent = {@@ -306,7 +285,6 @@ export async function checkoutSessionCompleted(} else {return {response: `No stripeCustomerId or dubCustomerExternalId found in Stripe checkout session metadata, skipping...`,- workspaceId: workspace.id,};}@@ -317,21 +295,18 @@ export async function checkoutSessionCompleted(if (chargeAmountTotal <= 0) {return {response: `Checkout session completed for Stripe customer ${stripeCustomerId} but amount is 0, skipping...`,- workspaceId: workspace.id,};}if (charge.mode === "setup") {return {response: `Checkout session completed for Stripe customer ${stripeCustomerId} but mode is "setup", skipping...`,- workspaceId: workspace.id,};}if (charge.payment_status !== "paid") {return {response: `Checkout session completed for Stripe customer ${stripeCustomerId} but payment_status is not "paid", skipping...`,- workspaceId: workspace.id,};}@@ -363,7 +338,6 @@ export async function checkoutSessionCompleted();return {response: `Invoice with ID ${invoiceId} already processed, skipping...`,- workspaceId: workspace.id,};}}@@ -589,7 +563,6 @@ export async function checkoutSessionCompleted(return {response: `Checkout session completed for customer with external ID ${dubCustomerExternalId} and invoice ID ${invoiceId}`,- workspaceId: workspace.id,};}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.tsindex 36b20631f4..881bfc2172 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/coupon-deleted.ts@@ -7,34 +7,20 @@ import { prisma } from "@dub/prisma";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";// Handle event "coupon.deleted"-export async function couponDeleted(event: Stripe.CouponDeletedEvent) {+export async function couponDeleted({+ event,+ workspace,+}: StripeWebhookInput & {+ event: Stripe.CouponDeletedEvent;+}): Promise<StripeWebhookOutput> {const coupon = event.data.object;- const stripeAccountId = event.account as string;-- const workspace = await prisma.project.findUnique({- where: {- stripeConnectId: stripeAccountId,- },- select: {- id: true,- slug: true,- defaultProgramId: true,- stripeConnectId: true,- },- });-- if (!workspace) {- return {- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,- };- }if (!workspace.defaultProgramId) {return {- response: `Workspace ${workspace.id} for stripe account ${stripeAccountId} has no programs.`,- workspaceId: workspace.id,+ response: `Workspace ${workspace.id} for stripe account ${workspace.stripeConnectId} has no programs.`,};}@@ -51,7 +37,6 @@ export async function couponDeleted(event: Stripe.CouponDeletedEvent) {if (!discounts.length) {return {response: `Discount not found for Stripe coupon ${coupon.id}.`,- workspaceId: workspace.id,};}@@ -139,6 +124,5 @@ export async function couponDeleted(event: Stripe.CouponDeletedEvent) {return {response: `Stripe coupon ${coupon.id} deleted.`,- workspaceId: workspace.id,};}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.tsindex dd2b82b685..2392b4f72c 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts@@ -1,11 +1,16 @@import { prisma } from "@dub/prisma";import type Stripe from "stripe";import { createNewCustomer } from "./utils/create-new-customer";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";// Handle event "customer.created"-export async function customerCreated(event: Stripe.CustomerCreatedEvent) {+export async function customerCreated({+ event,+ workspace,+}: Omit<StripeWebhookInput, "mode"> & {+ event: Stripe.CustomerCreatedEvent;+}): Promise<StripeWebhookOutput> {const stripeCustomer = event.data.object;- const stripeAccountId = event.account as string;const dubCustomerExternalId =stripeCustomer.metadata?.dubCustomerExternalId ||stripeCustomer.metadata?.dubCustomerId;@@ -17,23 +22,6 @@ export async function customerCreated(event: Stripe.CustomerCreatedEvent) {};}- const workspace = await prisma.project.findUnique({- where: {- stripeConnectId: stripeAccountId,- },- select: {- id: true,- },- });-- if (!workspace) {- return {- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,- };- }-- const workspaceId = workspace.id;-// Check the customer is not already createdconst customer = await prisma.customer.findFirst({where: {@@ -60,19 +48,17 @@ export async function customerCreated(event: Stripe.CustomerCreatedEvent) {data: {externalId: dubCustomerExternalId,stripeCustomerId: stripeCustomer.id,- projectConnectId: stripeAccountId,+ projectConnectId: workspace.stripeConnectId,},});return {response: `Dub customer with ID ${customer.id} updated with Stripe customer ID ${stripeCustomer.id}`,- workspaceId,};} catch (error) {console.error(error);return {response: `Error updating Dub customer with ID ${customer.id}: ${error}`,- workspaceId,};}}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-created.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-created.tsindex fbaf463976..4cd62dd8b4 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-created.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-created.ts@@ -1,19 +1,22 @@import { trackLead } from "@/lib/api/conversions/track-lead";import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";-import { StripeMode } from "@/lib/types";import { prisma } from "@dub/prisma";import { Customer } from "@dub/prisma/client";import { pick, STRIPE_INTEGRATION_ID } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";import { getConnectedCustomer } from "./utils/get-connected-customer";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";// Handle event "customer.subscription.created"// only used for recording free trial creations-export async function customerSubscriptionCreated(- event: Stripe.CustomerSubscriptionCreatedEvent,- mode: StripeMode,-) {+export async function customerSubscriptionCreated({+ event,+ mode,+ workspace,+}: StripeWebhookInput & {+ event: Stripe.CustomerSubscriptionCreatedEvent;+}): Promise<StripeWebhookOutput> {const createdSubscription = event.data.object;if (createdSubscription.status !== "trialing") {@@ -22,49 +25,31 @@ export async function customerSubscriptionCreated(};}- const stripeAccountId = event.account as string;const stripeCustomerId = createdSubscription.customer as string;- const workspace = await prisma.project.findUnique({+ const installedIntegration = await prisma.installedIntegration.findFirst({where: {- stripeConnectId: stripeAccountId,+ integrationId: STRIPE_INTEGRATION_ID,+ projectId: workspace.id,},select: {- id: true,- slug: true,- stripeConnectId: true,- webhookEnabled: true,- installedIntegrations: {- where: {- integrationId: STRIPE_INTEGRATION_ID,- },- },+ settings: true,},});- if (!workspace) {- return {- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,- };- }-- const workspaceId = workspace.id;-- if (!workspace.installedIntegrations.length) {+ if (!installedIntegration) {return {- response: `Workspace ${workspace.slug} has no Stripe integration installed, skipping...`,- workspaceId,+ response: `Workspace ${workspace.id} has no Stripe integration installed, skipping...`,};}const stripeIntegrationSettings = stripeIntegrationSettingsSchema.parse(- workspace.installedIntegrations[0].settings || {},+ installedIntegration.settings || {},);if (!stripeIntegrationSettings?.freeTrials?.enabled) {return {- response: `Stripe free trial tracking is not enabled for workspace ${workspace.slug}, skipping...`,- workspaceId,+ response: `Stripe free trial tracking is not enabled for workspace ${workspace.id}, skipping...`,};}@@ -80,7 +65,7 @@ export async function customerSubscriptionCreated(if (!customer) {const stripeCustomer = await getConnectedCustomer({stripeCustomerId,- stripeAccountId,+ stripeAccountId: workspace.stripeConnectId,mode,});@@ -96,7 +81,6 @@ export async function customerSubscriptionCreated(// this should never happen, but just in casereturn {response: `Customer ${stripeCustomer.id} with email ${stripeCustomer.email} has not been tracked yet, skipping...`,- workspaceId,};}// update the customer with the Stripe customer ID (for future reference by invoice.paid)@@ -114,7 +98,6 @@ export async function customerSubscriptionCreated(// this should never happen either, but just in casereturn {response: `Customer with stripeCustomerId ${stripeCustomerId} ${stripeCustomer ? "does not have an email on Stripe" : "does not exist"}, skipping...`,- workspaceId,};}}@@ -122,14 +105,12 @@ export async function customerSubscriptionCreated(if (!customer.clickId) {return {response: `Customer ${customer.id} has no clickId, skipping...`,- workspaceId,};}if (!customer.externalId) {return {response: `Customer ${customer.id} has no externalId, skipping...`,- workspaceId,};}@@ -151,7 +132,6 @@ export async function customerSubscriptionCreated(});return {- response: `Customer subscription created for customer ${customer.id} with stripeCustomerId ${stripeCustomerId} and workspace ${workspace.slug}`,- workspaceId,+ response: `Customer subscription created for customer ${customer.id} with stripeCustomerId ${stripeCustomerId} and workspace ${workspace.id}`,};}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-deleted.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-deleted.tsindex 7d67cd0977..3f4fd7ac0b 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-deleted.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-subscription-deleted.ts@@ -1,10 +1,13 @@import { prisma } from "@dub/prisma";import type Stripe from "stripe";+import { StripeWebhookOutput } from "./utils/types";// Handle event "customer.subscription.deleted"-export async function customerSubscriptionDeleted(- event: Stripe.CustomerSubscriptionDeletedEvent,-) {+export async function customerSubscriptionDeleted({+ event,+}: {+ event: Stripe.CustomerSubscriptionDeletedEvent;+}): Promise<StripeWebhookOutput> {const deletedSubscription = event.data.object;const customer = await prisma.customer.findUnique({@@ -26,6 +29,5 @@ export async function customerSubscriptionDeleted(return {response: `Subscription cancelled, updating customer ${updatedCustomer.id} with subscriptionCanceledAt: ${updatedCustomer.subscriptionCanceledAt}`,- workspaceId: customer.projectId,};}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.tsindex 773f90874e..20da66c7f8 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts@@ -1,11 +1,16 @@import { prisma } from "@dub/prisma";import type Stripe from "stripe";import { createNewCustomer } from "./utils/create-new-customer";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";// Handle event "customer.updated"-export async function customerUpdated(event: Stripe.CustomerUpdatedEvent) {+export async function customerUpdated({+ event,+ workspace,+}: Omit<StripeWebhookInput, "mode"> & {+ event: Stripe.CustomerUpdatedEvent;+}): Promise<StripeWebhookOutput> {const stripeCustomer = event.data.object;- const stripeAccountId = event.account as string;const dubCustomerExternalId =stripeCustomer.metadata?.dubCustomerExternalId ||stripeCustomer.metadata?.dubCustomerId;@@ -17,23 +22,6 @@ export async function customerUpdated(event: Stripe.CustomerUpdatedEvent) {};}- const workspace = await prisma.project.findUnique({- where: {- stripeConnectId: stripeAccountId,- },- select: {- id: true,- },- });-- if (!workspace) {- return {- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,- };- }-- const workspaceId = workspace.id;-const customer = await prisma.customer.findFirst({where: {OR: [@@ -59,19 +47,17 @@ export async function customerUpdated(event: Stripe.CustomerUpdatedEvent) {email: stripeCustomer.email,externalId: dubCustomerExternalId,stripeCustomerId: stripeCustomer.id,- projectConnectId: stripeAccountId,+ projectConnectId: workspace.stripeConnectId,},});return {response: `Dub customer with ID ${customer.id} updated.`,- workspaceId,};} catch (error) {console.error(error);return {response: `Error updating Dub customer with ID ${customer.id}: ${error}`,- workspaceId,};}}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.tsindex 64bf076b01..5a27ac4757 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts@@ -7,7 +7,6 @@ import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";import { getLeadEvent, recordSale } from "@/lib/tinybird";-import { StripeMode } from "@/lib/types";import { redis } from "@/lib/upstash";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";import { transformSaleEventData } from "@/lib/webhook/transform";@@ -16,14 +15,17 @@ import { nanoid, pick } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";import { getConnectedCustomer } from "./utils/get-connected-customer";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";// Handle event "invoice.paid"-export async function invoicePaid(- event: Stripe.InvoicePaidEvent,- mode: StripeMode,-) {+export async function invoicePaid({+ event,+ mode,+ workspace,+}: StripeWebhookInput & {+ event: Stripe.InvoicePaidEvent;+}): Promise<StripeWebhookOutput> {const invoice = event.data.object;- const stripeAccountId = event.account as string;const stripeCustomerId = invoice.customer as string;const invoiceId = invoice.id;@@ -38,7 +40,7 @@ export async function invoicePaid(if (!customer) {const connectedCustomer = await getConnectedCustomer({stripeCustomerId,- stripeAccountId,+ stripeAccountId: workspace.stripeConnectId,mode,});@@ -52,7 +54,7 @@ export async function invoicePaid(customer = await prisma.customer.update({where: {projectConnectId_externalId: {- projectConnectId: stripeAccountId,+ projectConnectId: workspace.stripeConnectId!,externalId: dubCustomerExternalId,},},@@ -90,7 +92,7 @@ export async function invoicePaid(timestamp: new Date().toISOString(),dubCustomerExternalId: customer.externalId,stripeCustomerId,- stripeAccountId,+ stripeAccountId: workspace.stripeConnectId,invoiceId,customerId: customer.id,workspaceId: customer.projectId,@@ -110,7 +112,6 @@ export async function invoicePaid();return {response: `Invoice with ID ${invoiceId} already processed, skipping...`,- workspaceId: customer.projectId,};}@@ -118,7 +119,6 @@ export async function invoicePaid(if (invoiceSaleAmount <= 0) {return {response: `Invoice with ID ${invoiceId} has an amount of 0, skipping...`,- workspaceId: customer.projectId,};}@@ -140,7 +140,6 @@ export async function invoicePaid(if (!leadEvent) {return {response: `Lead event with customer ID ${customer.id} not found, skipping...`,- workspaceId: customer.projectId,};}@@ -175,7 +174,6 @@ export async function invoicePaid(if (!link) {return {response: `Link with ID ${linkId} not found, skipping...`,- workspaceId: customer.projectId,};}@@ -184,7 +182,7 @@ export async function invoicePaid(linkId,});- const [_sale, linkUpdated, workspace] = await Promise.all([+ const [_sale, linkUpdated] = await Promise.all([recordSale(saleData),// update link stats@@ -344,6 +342,5 @@ export async function invoicePaid(return {response: `Sale recorded for customer ID ${customer.id} and invoice ID ${invoiceId}`,- workspaceId: customer.projectId,};}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.tsindex 121ec1183f..b14371211e 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/promotion-code-updated.ts@@ -1,44 +1,25 @@import { prisma } from "@dub/prisma";import type Stripe from "stripe";+import { StripeWebhookInput, StripeWebhookOutput } from "./utils/types";// Handle event "promotion_code.updated"-export async function promotionCodeUpdated(- event: Stripe.PromotionCodeUpdatedEvent,-) {+export async function promotionCodeUpdated({+ event,+ workspace,+}: Omit<StripeWebhookInput, "mode"> & {+ event: Stripe.PromotionCodeUpdatedEvent;+}): Promise<StripeWebhookOutput> {const promotionCode = event.data.object;- const stripeAccountId = event.account as string;-- const workspace = await prisma.project.findUnique({- where: {- stripeConnectId: stripeAccountId,- },- select: {- id: true,- slug: true,- defaultProgramId: true,- stripeConnectId: true,- },- });-- if (!workspace) {- return {- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,- };- }-- const workspaceId = workspace.id;if (!workspace.defaultProgramId) {return {- response: `Workspace ${workspaceId} for stripe account ${stripeAccountId} has no programs.`,- workspaceId,+ response: `Workspace ${workspace.id} for stripe account ${workspace.stripeConnectId} has no programs.`,};}if (promotionCode.active) {return {response: `Promotion code ${promotionCode.id} is active.`,- workspaceId,};}@@ -55,7 +36,6 @@ export async function promotionCodeUpdated(if (!discountCode) {return {response: `Discount code not found for Stripe promotion code ${promotionCode.id}.`,- workspaceId,};}@@ -67,6 +47,5 @@ export async function promotionCodeUpdated(return {response: `Discount code ${discountCode.id} deleted from the program ${workspace.defaultProgramId}.`,- workspaceId,};}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/route.tsindex 39011e883e..9b8b6a1586 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts@@ -2,7 +2,6 @@ import { captureWebhookLog } from "@/lib/api-logs/capture-webhook-log";import { withAxiom } from "@/lib/axiom/server";import { stripe } from "@/lib/stripe";import { StripeMode } from "@/lib/types";-import { prisma } from "@dub/prisma";import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";import Stripe from "stripe";@@ -16,6 +15,8 @@ import { customerSubscriptionDeleted } from "./customer-subscription-deleted";import { customerUpdated } from "./customer-updated";import { invoicePaid } from "./invoice-paid";import { promotionCodeUpdated } from "./promotion-code-updated";+import { resolveWebhookWorkspace } from "./utils/resolve-webhook-workspace";+import { StripeWebhookOutput } from "./utils/types";const relevantEvents = new Set(["account.application.deauthorized",@@ -89,43 +90,87 @@ export const POST = withAxiom(async (req: Request) => {});}- let result: {- response: string;- workspaceId?: string;- } = {+ const workspace = await resolveWebhookWorkspace({+ stripeAccountId: event.account!,+ mode,+ });++ // Workspace not found+ if (workspace === null) {+ return NextResponse.json({+ eventType: event.type,+ response: `Workspace not found for Stripe account ${event.account}, skipping...`,+ });+ }++ let result: StripeWebhookOutput = {response: "OK",};switch (event.type) {case "account.application.deauthorized":- result = await accountApplicationDeauthorized(event, mode);+ result = await accountApplicationDeauthorized({+ mode,+ workspace,+ });break;case "charge.refunded":- result = await chargeRefunded(event, mode);+ result = await chargeRefunded({+ event,+ mode,+ workspace,+ });break;case "checkout.session.completed":- result = await checkoutSessionCompleted(event, mode);+ result = await checkoutSessionCompleted({+ event,+ mode,+ workspace,+ });break;case "coupon.deleted":- result = await couponDeleted(event);+ result = await couponDeleted({+ event,+ mode,+ workspace,+ });break;case "customer.created":- result = await customerCreated(event);+ result = await customerCreated({+ event,+ workspace,+ });break;case "customer.updated":- result = await customerUpdated(event);+ result = await customerUpdated({+ event,+ workspace,+ });break;case "customer.subscription.created":- result = await customerSubscriptionCreated(event, mode);+ result = await customerSubscriptionCreated({+ event,+ mode,+ workspace,+ });break;case "customer.subscription.deleted":- result = await customerSubscriptionDeleted(event);+ result = await customerSubscriptionDeleted({+ event,+ });break;case "invoice.paid":- result = await invoicePaid(event, mode);+ result = await invoicePaid({+ event,+ mode,+ workspace,+ });break;case "promotion_code.updated":- result = await promotionCodeUpdated(event);+ result = await promotionCodeUpdated({+ event,+ workspace,+ });break;}@@ -134,43 +179,18 @@ export const POST = withAxiom(async (req: Request) => {response: result.response,};- // if workspaceId is returned as undefined- // AND the response does not contain "Workspace not found" (indicating the workspace doesn't exist)- // we try to find the workspace ID from the Stripe account ID- if (- !result.workspaceId &&- !result.response.startsWith("Workspace not found") &&- event.account- ) {- const stripeWebhookWorkspace = await prisma.project.findUnique({- where: {- stripeConnectId: event.account,- },- select: {- id: true,- },- });- if (stripeWebhookWorkspace) {- // if workspace exists, we set the workspace ID- result.workspaceId = stripeWebhookWorkspace.id;- }- }-- // if workspace ID exists, we capture the webhook log- if (result.workspaceId) {- waitUntil(- captureWebhookLog({- workspaceId: result.workspaceId,- method: req.method,- path: "/stripe/integration/webhook",- statusCode: 200,- duration: Date.now() - startTime,- requestBody: event,- responseBody,- userAgent: req.headers.get("user-agent"),- }),- );- }+ waitUntil(+ captureWebhookLog({+ workspaceId: workspace.id,+ method: req.method,+ path: "/stripe/integration/webhook",+ statusCode: 200,+ duration: Date.now() - startTime,+ requestBody: event,+ responseBody,+ userAgent: req.headers.get("user-agent"),+ }),+ );console.log(`[${event.type}]: ${result.response}`);diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/resolve-webhook-workspace.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/resolve-webhook-workspace.tsnew file mode 100644index 0000000000..805e9e9a11--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/resolve-webhook-workspace.ts@@ -0,0 +1,51 @@+import { StripeMode } from "@/lib/types";+import { prisma } from "@dub/prisma";++export async function resolveWebhookWorkspace({+ stripeAccountId,+ mode,+}: {+ stripeAccountId: string;+ mode: StripeMode;+}) {+ const workspace = await prisma.project.findUnique({+ where: {+ stripeConnectId: stripeAccountId,+ },+ select: {+ id: true,+ stripeConnectId: true,+ defaultProgramId: true,+ webhookEnabled: true,+ stagingWorkspaceId: true,+ },+ });++ if (!workspace) {+ return null;+ }++ if (mode === "test" && workspace.stagingWorkspaceId) {+ const stagingWorkspace = await prisma.project.findUnique({+ where: {+ id: workspace.stagingWorkspaceId,+ },+ select: {+ id: true,+ stripeConnectId: true,+ defaultProgramId: true,+ webhookEnabled: true,+ stagingWorkspaceId: true,+ },+ });++ if (stagingWorkspace && !stagingWorkspace.stripeConnectId) {+ return {+ ...stagingWorkspace,+ stripeConnectId: stripeAccountId,+ };+ }+ }++ return workspace;+}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/types.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/types.tsnew file mode 100644index 0000000000..0bcd0a92df--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/types.ts@@ -0,0 +1,18 @@+import { StripeMode } from "@/lib/types";+import { Project } from "@dub/prisma/client";++export type StripeWebhookInput = {+ mode: StripeMode;+ workspace: Pick<+ Project,+ | "id"+ | "stripeConnectId"+ | "defaultProgramId"+ | "webhookEnabled"+ | "stagingWorkspaceId"+ >;+};++export type StripeWebhookOutput = {+ response: string;+};