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.

Improve Stripe webhook log (#4177)

Kiran Kaac9cefc4aef
diff --git a/apps/web/app/(ee)/api/cron/utils.ts b/apps/web/app/(ee)/api/cron/utils.ts
index fc5258504c..200db6e438 100644
--- a/apps/web/app/(ee)/api/cron/utils.ts
+++ b/apps/web/app/(ee)/api/cron/utils.ts
@@ -1,5 +1,5 @@
export function logAndRespond(
- message: string,
+ body: string | Record<string, unknown>,
{
status = 200,
logLevel = "info",
@@ -8,8 +8,20 @@ export function logAndRespond(
logLevel?: "error" | "warn" | "info";
} = {},
) {
- console[logLevel](message);
- return new Response(message, { status });
+ // When string
+ if (typeof body === "string") {
+ console[logLevel](body);
+ return new Response(body, { status });
+ }
+
+ // When object
+ console[logLevel](body);
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
}
export function logAndReturn<T>(value: T): T {
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.ts
index 449a59536b..fed4f31f86 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,13 +1,14 @@
import { prisma } from "@/lib/prisma";
-import { StripeMode } from "@/lib/types";
import { STRIPE_INTEGRATION_ID } from "@dub/utils";
import type Stripe from "stripe";
+import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
// Handle event "account.application.deauthorized"
-export async function accountApplicationDeauthorized(
- event: Stripe.AccountApplicationDeauthorizedEvent,
- mode: StripeMode,
-) {
+export async function accountApplicationDeauthorized({
+ event,
+ mode,
+ workspace,
+}: WebhookHandlerInput<Stripe.AccountApplicationDeauthorizedEvent>): Promise<WebhookHandlerResponse> {
const stripeAccountId = event.account;
if (mode === "test") {
@@ -16,21 +17,6 @@ export async function accountApplicationDeauthorized(
};
}
- const workspace = await prisma.project.findUnique({
- where: {
- stripeConnectId: stripeAccountId,
- },
- select: {
- id: true,
- },
- });
-
- if (!workspace) {
- return {
- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,
- };
- }
-
await prisma.project.update({
where: {
stripeConnectId: stripeAccountId,
@@ -52,6 +38,5 @@ export async function accountApplicationDeauthorized(
return {
response: `Stripe Connect account ${stripeAccountId} deauthorized for workspace ${workspace.id}`,
- workspaceId: 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.ts
index 435afd1157..d768055e1b 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
@@ -2,14 +2,15 @@ import { trackCommissionStatusUpdate } from "@/lib/api/commissions/track-commiss
import { syncTotalCommissions } from "@/lib/api/partners/sync-total-commissions";
import { prisma } from "@/lib/prisma";
import { stripeAppClient } from "@/lib/stripe";
-import { StripeMode } from "@/lib/types";
import type Stripe from "stripe";
+import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
// Handle event "charge.refunded"
-export async function chargeRefunded(
- event: Stripe.ChargeRefundedEvent,
- mode: StripeMode,
-) {
+export async function chargeRefunded({
+ event,
+ mode,
+ workspace,
+}: WebhookHandlerInput<Stripe.ChargeRefundedEvent>): Promise<WebhookHandlerResponse> {
const charge = event.data.object;
const stripeAccountId = event.account as string;
@@ -39,28 +40,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 program, skipping...`,
};
}
@@ -68,7 +50,7 @@ export async function chargeRefunded(
where: {
invoiceId_programId: {
invoiceId: invoicePayment.invoice as string,
- programId: workspace.programs[0].id,
+ programId: workspace.defaultProgramId,
},
},
select: {
@@ -85,14 +67,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 +122,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.ts
index 1eca82db2d..989d126b09 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
@@ -13,7 +13,7 @@ import {
recordLead,
recordSale,
} from "@/lib/tinybird";
-import { ClickEventTB, LeadEventTB, StripeMode } from "@/lib/types";
+import { ClickEventTB, LeadEventTB } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformSaleEventData } from "@/lib/webhook/transform";
@@ -21,6 +21,7 @@ import { nanoid } from "@dub/utils";
import { Customer } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
+import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";
import { getCheckoutSessionProducts } from "./utils/get-checkout-session-products";
import { getConnectedCustomer } from "./utils/get-connected-customer";
@@ -28,10 +29,11 @@ import { incrementLinkLeads } from "./utils/increment-link-leads";
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,
+}: WebhookHandlerInput<Stripe.CheckoutSessionCompletedEvent>): Promise<WebhookHandlerResponse> {
let charge = event.data.object;
let dubCustomerExternalId =
charge.metadata?.dubCustomerExternalId || charge.metadata?.dubCustomerId;
@@ -52,24 +54,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
@@ -84,7 +68,6 @@ export async function checkoutSessionCompleted(
if (!clickEvent) {
return {
response: `Click event with dub_id ${dubClickId} not found, skipping...`,
- workspaceId: workspace.id,
};
}
@@ -206,13 +189,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 +241,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) {
@@ -281,13 +261,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,
};
}
}
@@ -299,7 +277,6 @@ export async function checkoutSessionCompleted(
if (!leadEventData) {
return {
response: `No lead event found for customer ${customer.id}, skipping...`,
- workspaceId: workspace.id,
};
}
leadEvent = {
@@ -311,7 +288,6 @@ export async function checkoutSessionCompleted(
} else {
return {
response: `No stripeCustomerId or dubCustomerExternalId found in Stripe checkout session metadata, skipping...`,
- workspaceId: workspace.id,
};
}
@@ -322,21 +298,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,
};
}
@@ -369,7 +342,6 @@ export async function checkoutSessionCompleted(
return {
response: `Invoice with ID ${invoiceId} already processed, skipping...`,
- workspaceId: workspace.id,
};
}
}
@@ -592,6 +564,5 @@ 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.ts
index 7abc7298b0..cedb449c39 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,22 @@ import DiscountDeleted from "@dub/email/templates/discount-deleted";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
+import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
// Handle event "coupon.deleted"
-export async function couponDeleted(event: Stripe.CouponDeletedEvent) {
+export async function couponDeleted({
+ event,
+ workspace,
+}: Omit<
+ WebhookHandlerInput<Stripe.CouponDeletedEvent>,
+ "mode"
+>): Promise<WebhookHandlerResponse> {
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,
};
}
@@ -51,7 +39,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 +126,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.ts
deleted file mode 100644
index 94999bd54d..0000000000
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import type Stripe from "stripe";
-import { syncCustomer } from "./utils/sync-customer";
-
-// Handle event "customer.created"
-export async function customerCreated(event: Stripe.CustomerCreatedEvent) {
- return await syncCustomer(event);
-}
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.ts
index 93bdc71c67..6c7c288df8 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,20 @@
import { trackLead } from "@/lib/api/conversions/track-lead";
import { stripeIntegrationSettingsSchema } from "@/lib/integrations/stripe/schema";
import { prisma } from "@/lib/prisma";
-import { StripeMode } from "@/lib/types";
import { pick, STRIPE_INTEGRATION_ID } from "@dub/utils";
import { Customer } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
+import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
import { getConnectedCustomer } from "./utils/get-connected-customer";
// 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,
+}: WebhookHandlerInput<Stripe.CustomerSubscriptionCreatedEvent>): Promise<WebhookHandlerResponse> {
const createdSubscription = event.data.object;
if (createdSubscription.status !== "trialing") {
@@ -25,46 +26,29 @@ 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,
+ projectId: workspace.id,
+ integrationId: STRIPE_INTEGRATION_ID,
},
- select: {
- id: true,
- slug: true,
- stripeConnectId: true,
- webhookEnabled: true,
- installedIntegrations: {
- where: {
- integrationId: STRIPE_INTEGRATION_ID,
- },
- },
+ orderBy: {
+ createdAt: "asc",
},
});
- 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...`,
};
}
@@ -96,7 +80,6 @@ export async function customerSubscriptionCreated(
// this should never happen, but just in case
return {
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 +97,6 @@ export async function customerSubscriptionCreated(
// this should never happen either, but just in case
return {
response: `Customer with stripeCustomerId ${stripeCustomerId} ${stripeCustomer ? "does not have an email on Stripe" : "does not exist"}, skipping...`,
- workspaceId,
};
}
}
@@ -122,14 +104,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 +131,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.ts
index 262e903e52..5b99edf729 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,11 @@
import { prisma } from "@/lib/prisma";
import type Stripe from "stripe";
+import { WebhookHandlerResponse } from "./types";
// Handle event "customer.subscription.deleted"
export async function customerSubscriptionDeleted(
event: Stripe.CustomerSubscriptionDeletedEvent,
-) {
+): Promise<WebhookHandlerResponse> {
const deletedSubscription = event.data.object;
const customer = await prisma.customer.findUnique({
@@ -26,6 +27,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.ts
deleted file mode 100644
index 25256f9ebf..0000000000
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import type Stripe from "stripe";
-import { syncCustomer } from "./utils/sync-customer";
-
-// Handle event "customer.updated"
-export async function customerUpdated(event: Stripe.CustomerUpdatedEvent) {
- return await syncCustomer(event);
-}
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.ts
index 2c4aa8bb93..225934e111 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
@@ -15,14 +15,16 @@ import { transformSaleEventData } from "@/lib/webhook/transform";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
+import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";
import { getConnectedCustomer } from "./utils/get-connected-customer";
// Handle event "invoice.paid"
-export async function invoicePaid(
- event: Stripe.InvoicePaidEvent,
- mode: StripeMode,
-) {
+export async function invoicePaid({
+ event,
+ mode,
+ workspace,
+}: WebhookHandlerInput<Stripe.InvoicePaidEvent>): Promise<WebhookHandlerResponse> {
const invoice = event.data.object;
const stripeAccountId = event.account as string;
const stripeCustomerId = invoice.customer as string | null;
@@ -84,28 +86,9 @@ export async function invoicePaid(
// if customer is still not found, try to attribute via partner discount on the invoice
if (!customer) {
- const workspace = await prisma.project.findUnique({
- where: {
- stripeConnectId: stripeAccountId,
- },
- select: {
- id: true,
- defaultProgramId: true,
- stripeConnectId: true,
- webhookEnabled: true,
- },
- });
-
- if (!workspace) {
- return {
- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,
- };
- }
-
if (!workspace.defaultProgramId) {
return {
response: `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub and workspace has no default program, skipping...`,
- workspaceId: workspace.id,
};
}
@@ -142,7 +125,6 @@ export async function invoicePaid(
if (!customer) {
return {
response: `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub (nor does the connected customer ${stripeCustomerId} have a valid dubCustomerExternalId or partner discount code on the invoice), skipping...`,
- workspaceId: workspace.id,
};
}
}
@@ -181,7 +163,6 @@ export async function invoicePaid(
);
return {
response: `Invoice with ID ${invoiceId} already processed, skipping...`,
- workspaceId: customer.projectId,
};
}
@@ -189,7 +170,6 @@ export async function invoicePaid(
if (invoiceSaleAmount <= 0) {
return {
response: `Invoice with ID ${invoiceId} has an amount of 0, skipping...`,
- workspaceId: customer.projectId,
};
}
@@ -211,7 +191,6 @@ export async function invoicePaid(
if (!leadEvent) {
return {
response: `Lead event with customer ID ${customer.id} not found, skipping...`,
- workspaceId: customer.projectId,
};
}
@@ -246,7 +225,6 @@ export async function invoicePaid(
if (!link) {
return {
response: `Link with ID ${linkId} not found, skipping...`,
- workspaceId: customer.projectId,
};
}
@@ -255,7 +233,7 @@ export async function invoicePaid(
linkId,
});
- const [_sale, linkUpdated, workspace] = await Promise.all([
+ const [_sale, linkUpdated] = await Promise.all([
recordSale(saleData),
// update link stats
@@ -438,7 +416,6 @@ 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.ts
index 9d4d1f9ec4..e47c1352d9 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,27 @@
import { prisma } from "@/lib/prisma";
import type Stripe from "stripe";
+import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
// Handle event "promotion_code.updated"
-export async function promotionCodeUpdated(
- event: Stripe.PromotionCodeUpdatedEvent,
-) {
+export async function promotionCodeUpdated({
+ event,
+ workspace,
+}: Omit<
+ WebhookHandlerInput<Stripe.PromotionCodeUpdatedEvent>,
+ "mode"
+>): Promise<WebhookHandlerResponse> {
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 ${stripeAccountId} has no programs.`,
};
}
if (promotionCode.active) {
return {
response: `Promotion code ${promotionCode.id} is active, no action needed.`,
- workspaceId,
};
}
@@ -55,7 +38,6 @@ export async function promotionCodeUpdated(
if (!discountCode) {
return {
response: `Discount code not found for Stripe promotion code ${promotionCode.id}.`,
- workspaceId,
};
}
@@ -67,6 +49,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.ts
index fdef964455..26f2a6552b 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts
@@ -4,18 +4,20 @@ import { prisma } from "@/lib/prisma";
import { stripe } from "@/lib/stripe";
import { StripeMode } from "@/lib/types";
import { waitUntil } from "@vercel/functions";
-import { NextResponse } from "next/server";
+import { logAndRespond } from "app/(ee)/api/cron/utils";
import Stripe from "stripe";
import { accountApplicationDeauthorized } from "./account-application-deauthorized";
import { chargeRefunded } from "./charge-refunded";
import { checkoutSessionCompleted } from "./checkout-session-completed";
import { couponDeleted } from "./coupon-deleted";
-import { customerCreated } from "./customer-created";
import { customerSubscriptionCreated } from "./customer-subscription-created";
import { customerSubscriptionDeleted } from "./customer-subscription-deleted";
-import { customerUpdated } from "./customer-updated";
import { invoicePaid } from "./invoice-paid";
import { promotionCodeUpdated } from "./promotion-code-updated";
+import { WebhookHandlerResponse } from "./types";
+import { syncCustomer } from "./utils/sync-customer";
+
+export const dynamic = "force-dynamic";
const relevantEvents = new Set([
"account.application.deauthorized",
@@ -53,7 +55,7 @@ export const POST = withAxiom(async (req: Request) => {
}
if (!sig || !webhookSecret) {
- return new Response("Invalid request", {
+ return logAndRespond("Invalid request", {
status: 400,
});
}
@@ -62,16 +64,23 @@ export const POST = withAxiom(async (req: Request) => {
try {
event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
} catch (err: any) {
- console.log(`❌ Error message: ${err.message}`);
- return new Response(`Webhook Error: ${err.message}`, {
+ return logAndRespond(`Webhook Error: ${err.message}`, {
status: 400,
});
}
+ console.log("Webhook event", {
+ eventId: event.id,
+ eventType: event.type,
+ accountId: event.account,
+ mode,
+ });
+
// Ignore unsupported events
if (!relevantEvents.has(event.type)) {
- return new Response("Unsupported event, skipping...", {
- status: 200,
+ return logAndRespond({
+ eventType: event.type,
+ response: "Unsupported event, skipping...",
});
}
@@ -80,52 +89,102 @@ export const POST = withAxiom(async (req: Request) => {
// and live mode events are sent to the live mode endpoint.
// See: https://docs.stripe.com/stripe-apps/build-backend#event-behavior-depends-on-install-mode
if (!event.livemode && mode === "live") {
- const response =
- "Received a test webhook event on our live webhook receiver endpoint, skipping...";
- console.log(`[${event.type}]: ${response}`);
- return NextResponse.json({
+ return logAndRespond({
+ eventType: event.type,
+ response:
+ "Received a test webhook event on our live webhook receiver endpoint, skipping...",
+ });
+ }
+
+ // Should never happen, but just in case
+ if (!event.account) {
+ return logAndRespond({
eventType: event.type,
- response,
+ response: "Missing Stripe Connect account on event, skipping...",
});
}
- let result: {
- response: string;
- workspaceId?: string;
- } = {
+ // Find the workspace
+ const workspace = await prisma.project.findUnique({
+ where: {
+ stripeConnectId: event.account,
+ },
+ select: {
+ id: true,
+ stripeConnectId: true,
+ defaultProgramId: true,
+ webhookEnabled: true,
+ },
+ });
+
+ if (!workspace) {
+ return logAndRespond({
+ eventType: event.type,
+ response: `Workspace not found for Stripe account ${event.account}, skipping...`,
+ });
+ }
+
+ let result: WebhookHandlerResponse = {
response: "OK",
};
switch (event.type) {
case "account.application.deauthorized":
- result = await accountApplicationDeauthorized(event, mode);
+ result = await accountApplicationDeauthorized({
+ event,
+ 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,
+ workspace,
+ });
break;
case "customer.created":
- result = await customerCreated(event);
- break;
case "customer.updated":
- result = await customerUpdated(event);
+ result = await syncCustomer({
+ 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);
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,45 +193,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"),
- }),
- );
- }
-
- console.log(`[${event.type}]: ${result.response}`);
+ 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"),
+ }),
+ );
- return NextResponse.json(responseBody);
+ return logAndRespond(responseBody);
});
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/types.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/types.ts
new file mode 100644
index 0000000000..e5f63cb197
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/types.ts
@@ -0,0 +1,16 @@
+import { StripeMode } from "@/lib/types";
+import { Project } from "@prisma/client";
+import Stripe from "stripe";
+
+export type WebhookHandlerResponse = {
+ response: string;
+};
+
+export type WebhookHandlerInput<T extends Stripe.Event> = {
+ event: T;
+ mode: StripeMode;
+ workspace: Pick<
+ Project,
+ "id" | "stripeConnectId" | "defaultProgramId" | "webhookEnabled"
+ >;
+};
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
index 968c5a3471..dbf7e9f78c 100644
--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/sync-customer.ts
@@ -15,15 +15,17 @@ import { nanoid, pick } from "@dub/utils";
import { Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
-
-type SyncCustomerResponse = {
- response: string;
- workspaceId?: string;
-};
-
-export async function syncCustomer(
- event: Stripe.CustomerCreatedEvent | Stripe.CustomerUpdatedEvent,
-): Promise<SyncCustomerResponse> {
+import { WebhookHandlerInput, WebhookHandlerResponse } from "../types";
+
+export async function syncCustomer({
+ event,
+ workspace,
+}: Omit<
+ WebhookHandlerInput<
+ Stripe.CustomerCreatedEvent | Stripe.CustomerUpdatedEvent
+ >,
+ "mode"
+>): Promise<WebhookHandlerResponse> {
const stripeCustomer = event.data.object;
const stripeAccountId = event.account as string;
const dubCustomerExternalId =
@@ -43,22 +45,6 @@ export async function syncCustomer(
};
}
- const workspace = await prisma.project.findUnique({
- where: {
- stripeConnectId: stripeAccountId,
- },
- select: {
- id: true,
- webhookEnabled: true,
- },
- });
-
- if (!workspace) {
- return {
- response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,
- };
- }
-
const existingCustomer = await prisma.customer.findFirst({
where: {
OR: [
@@ -94,7 +80,6 @@ export async function syncCustomer(
if (!clickId) {
return {
response: "Click ID not found in Stripe customer metadata, skipping...",
- workspaceId: workspace.id,
};
}
@@ -105,7 +90,6 @@ export async function syncCustomer(
if (!clickData) {
return {
response: `Click event with ID ${clickId} not found, skipping...`,
- workspaceId: workspace.id,
};
}
@@ -125,14 +109,12 @@ export async function syncCustomer(
if (!link || !link.projectId) {
return {
response: `Link with ID ${linkId} not found or does not have a project, skipping...`,
- workspaceId: workspace.id,
};
}
if (link.projectId !== workspace.id) {
return {
response: `Link ${linkId} does not belong to workspace ${workspace.id}, skipping...`,
- workspaceId: workspace.id,
};
}
@@ -302,19 +284,17 @@ export async function syncCustomer(
return {
response: `New Dub customer created: ${customer.id}. Lead event recorded: ${leadData.event_id}`,
- workspaceId: workspace.id,
};
}
async function updateStripeCustomer({
customerId,
- workspaceId,
data,
}: {
customerId: string;
workspaceId: string;
data: Prisma.CustomerUncheckedUpdateInput;
-}): Promise<SyncCustomerResponse> {
+}): Promise<{ response: string }> {
try {
await prisma.customer.update({
where: {
@@ -325,12 +305,10 @@ async function updateStripeCustomer({
return {
response: `Dub customer with ID ${customerId} updated.`,
- workspaceId,
};
} catch (error) {
return {
response: `Error updating Dub customer with ID ${customerId}: ${error}`,
- workspaceId,
};
}
}