The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Move `transfer.reversed` to main Stripe webhook + refactor them
Steven Tey649c8f4aa058
diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/route.ts b/apps/web/app/(ee)/api/stripe/connect/webhook/route.tsindex 1ab7051c25..99acf67632 100644--- a/apps/web/app/(ee)/api/stripe/connect/webhook/route.ts+++ b/apps/web/app/(ee)/api/stripe/connect/webhook/route.ts@@ -7,7 +7,6 @@ import { accountUpdated } from "./account-updated";import { balanceAvailable } from "./balance-available";import { payoutFailed } from "./payout-failed";import { payoutPaid } from "./payout-paid";-import { transferReversed } from "./transfer-reversed";const relevantEvents = new Set(["account.application.deauthorized",@@ -16,7 +15,6 @@ const relevantEvents = new Set(["balance.available","payout.paid","payout.failed",- "transfer.reversed",]);// POST /api/stripe/connect/webhook – listen to Stripe Connect webhooks (for connected accounts)@@ -62,9 +60,6 @@ export const POST = async (req: Request) => {case "payout.failed":response = await payoutFailed(event);break;- case "transfer.reversed":- response = await transferReversed(event);- break;}} catch (error) {await log({diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.tsindex b991cce2a5..173799e70e 100644--- a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts@@ -9,8 +9,7 @@ export async function chargeFailed(event: Stripe.Event) {const { transfer_group: invoiceId, failure_message: failedReason } = charge;if (!invoiceId) {- console.log("No transfer group found, skipping...");- return;+ return "No transfer group found, skipping...";}let invoice = await prisma.invoice.findUnique({@@ -20,8 +19,7 @@ export async function chargeFailed(event: Stripe.Event) {});if (!invoice) {- console.log(`Invoice with transfer group ${invoiceId} not found.`);- return;+ return `Invoice with transfer group ${invoiceId} not found.`;}invoice = await prisma.invoice.update({@@ -39,7 +37,11 @@ export async function chargeFailed(event: Stripe.Event) {if (invoice.type === "partnerPayout") {await processPayoutInvoiceFailure({ invoice, charge });+ return `Processed partner payout failure for invoice ${invoice.id}.`;} else if (invoice.type === "domainRenewal") {await processDomainRenewalFailure({ invoice });+ return `Processed domain renewal failure for invoice ${invoice.id}.`;}++ return `Unsupported invoice type (${invoice.type}), skipping...`;}diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-refunded.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-refunded.tsindex 218149dfbb..f0304a5dd8 100644--- a/apps/web/app/(ee)/api/stripe/webhook/charge-refunded.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-refunded.ts@@ -9,8 +9,7 @@ export async function chargeRefunded(event: Stripe.Event) {const { transfer_group: invoiceId } = charge;if (!invoiceId) {- console.log("No transfer group found, skipping...");- return;+ return "No transfer group found, skipping...";}const invoice = await prisma.invoice.findUnique({@@ -20,16 +19,15 @@ export async function chargeRefunded(event: Stripe.Event) {});if (!invoice) {- console.log(`Invoice with transfer group ${invoiceId} not found.`);- return;+ return `Invoice with transfer group ${invoiceId} not found.`;}if (invoice.type !== "domainRenewal") {- console.log(`Invoice ${invoice.id} is not a 'domainRenewal' type.`);- return;+ return `Invoice ${invoice.id} is not a 'domainRenewal' type, skipping...`;}await processDomainRenewalInvoice({ invoice });+ return `Disabled auto-renew for domains on invoice ${invoice.id}.`;}async function processDomainRenewalInvoice({ invoice }: { invoice: Invoice }) {diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.tsindex 7095154769..4e11679e7a 100644--- a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts@@ -34,10 +34,7 @@ export async function chargeSucceeded(event: Stripe.Event) {});}}- console.log(- "No transfer_group (invoiceId) found, skipping invoice update flow...",- );- return;+ return "No transfer_group (invoiceId) found, skipping invoice update flow...";}let invoice = await prisma.invoice.findUnique({@@ -47,13 +44,11 @@ export async function chargeSucceeded(event: Stripe.Event) {});if (!invoice) {- console.log(`Invoice with transfer group ${invoiceId} not found.`);- return;+ return `Invoice with transfer group ${invoiceId} not found.`;}if (invoice.status === "completed") {- console.log(`Invoice ${invoice.id} already completed, skipping...`);- return;+ return `Invoice ${invoice.id} already completed, skipping...`;}invoice = await prisma.invoice.update({@@ -69,10 +64,12 @@ export async function chargeSucceeded(event: Stripe.Event) {});if (invoice.type === "partnerPayout") {- await processPayoutInvoice({ invoice });+ return await processPayoutInvoice({ invoice });} else if (invoice.type === "domainRenewal") {- await processDomainRenewalInvoice({ invoice });+ return await processDomainRenewalInvoice({ invoice });}++ return `Unsupported invoice type (${invoice.type}), skipping...`;}async function processPayoutInvoice({ invoice }: { invoice: Invoice }) {@@ -86,10 +83,7 @@ async function processPayoutInvoice({ invoice }: { invoice: Invoice }) {});if (payoutsToProcess === 0) {- console.log(- `No payouts to process found for invoice ${invoice.id}, skipping...`,- );- return;+ return `No payouts to process found for invoice ${invoice.id}, skipping...`;}const qstashResponse = await qstash.publishJSON({@@ -100,9 +94,9 @@ async function processPayoutInvoice({ invoice }: { invoice: Invoice }) {});if (qstashResponse.messageId) {- console.log(`Message sent to Qstash with id ${qstashResponse.messageId}`);+ return `Message sent to Qstash with id ${qstashResponse.messageId}`;} else {- console.error("Error sending message to Qstash", qstashResponse);+ return `Error sending message to Qstash: ${JSON.stringify(qstashResponse)}`;}}@@ -119,8 +113,7 @@ async function processDomainRenewalInvoice({ invoice }: { invoice: Invoice }) {});if (domains.length === 0) {- console.log(`No domains found for invoice ${invoice.id}, skipping...`);- return;+ return `No domains found for invoice ${invoice.id}, skipping...`;}const newExpiresAt = addDays(domains[0].expiresAt, 365);@@ -165,8 +158,7 @@ async function processDomainRenewalInvoice({ invoice }: { invoice: Invoice }) {const workspaceOwners = workspace.users.filter(({ user }) => user.email);if (workspaceOwners.length === 0) {- console.log("No users found to send domain renewal success email.");- return;+ return "No users found to send domain renewal success email.";}await sendBatchEmail(@@ -184,4 +176,6 @@ async function processDomainRenewalInvoice({ invoice }: { invoice: Invoice }) {}),})),);++ return `Domain renewal success email sent to ${workspaceOwners.length} users.`;}diff --git a/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.tsindex 9d8b6b46ef..b8a5b790ce 100644--- a/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/checkout-session-completed.ts@@ -19,7 +19,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {checkoutSession.mode === "setup" ||checkoutSession.payment_status !== "paid") {- return;+ return "Session is setup mode or not paid, skipping...";}if (@@ -30,7 +30,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {message: "Missing items in Stripe webhook callback",type: "errors",});- return;+ return "Missing client_reference_id or customer in checkout session.";}const subscription = await stripe.subscriptions.retrieve(@@ -41,10 +41,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {const { plan, planTier } = getPlanAndTierFromPriceId({ priceId });if (!plan) {- console.log(- `Invalid price ID in checkout.session.completed event: ${priceId}`,- );- return;+ return `Invalid price ID in checkout.session.completed event: ${priceId}`;}const stripeId = checkoutSession.customer.toString();@@ -139,6 +136,8 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {hashedKeys: workspace.restrictedTokens.map(({ hashedKey }) => hashedKey),}),]);++ return `Checkout completed for workspace ${workspaceId}, upgraded to ${plan.name}.`;}async function completeOnboarding({diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.tsindex 59c39c9ced..36d6c45770 100644--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts@@ -10,7 +10,6 @@ import { recordLink } from "@/lib/tinybird";import { webhookCache } from "@/lib/webhook/cache";import { prisma } from "@dub/prisma";import { capitalize, FREE_PLAN, log } from "@dub/utils";-import { NextResponse } from "next/server";import Stripe from "stripe";import { sendCancellationFeedback } from "./utils/send-cancellation-feedback";import { updateWorkspacePlan } from "./utils/update-workspace-plan";@@ -69,12 +68,7 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {});if (!workspace) {- console.log(- "Workspace with Stripe ID *`" +- stripeId +- "`* not found in Stripe webhook `customer.subscription.deleted` callback",- );- return NextResponse.json({ received: true });+ return `Workspace with Stripe ID ${stripeId} not found in customer.subscription.deleted callback.`;}// Check if the customer has another active subscription@@ -92,7 +86,7 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {priceId,});- return NextResponse.json({ received: true });+ return `Workspace ${workspace.slug} has another active subscription; updated plan.`;}const workspaceLinks = workspace.links;@@ -235,5 +229,5 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {await deactivateProgram(workspace.defaultProgramId);}- return NextResponse.json({ received: true });+ return `Workspace ${workspace.slug} subscription deleted; downgraded to free.`;}diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.tsindex b28c6bbb52..f04d38fa9b 100644--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts@@ -1,6 +1,5 @@import { prisma } from "@dub/prisma";import { getPlanAndTierFromPriceId } from "@dub/utils";-import { NextResponse } from "next/server";import Stripe from "stripe";import { sendCancellationFeedback } from "./utils/send-cancellation-feedback";import { updateWorkspacePlan } from "./utils/update-workspace-plan";@@ -12,10 +11,7 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {const { plan } = getPlanAndTierFromPriceId({ priceId });if (!plan) {- console.log(- `Invalid price ID in customer.subscription.updated event: ${priceId}`,- );- return;+ return `Invalid price ID in customer.subscription.updated event: ${priceId}`;}const stripeId = subscriptionUpdated.customer.toString();@@ -57,12 +53,7 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {});if (!workspace) {- console.log(- "Workspace with Stripe ID *`" +- stripeId +- "`* not found in Stripe webhook `customer.subscription.updated` callback",- );- return NextResponse.json({ received: true });+ return `Workspace with Stripe ID ${stripeId} not found in customer.subscription.updated callback.`;}await updateWorkspacePlan({@@ -82,5 +73,8 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {owners,reason: cancelReason,});+ return `Updated workspace ${workspace.id} plan; cancellation at period end requested.`;}++ return `Updated workspace ${workspace.id} plan to ${plan.name}.`;}diff --git a/apps/web/app/(ee)/api/stripe/webhook/invoice-payment-failed.tsx b/apps/web/app/(ee)/api/stripe/webhook/invoice-payment-failed.tsxindex ede48846a4..1b4e39fd9c 100644--- a/apps/web/app/(ee)/api/stripe/webhook/invoice-payment-failed.tsx+++ b/apps/web/app/(ee)/api/stripe/webhook/invoice-payment-failed.tsx@@ -11,12 +11,7 @@ export async function invoicePaymentFailed(event: Stripe.Event) {} = event.data.object as Stripe.Invoice;if (!stripeId) {- console.log(- "Invoice with Stripe ID *`" +- stripeId +- "`* not found in invoice.payment_failed event",- );- return;+ return "No customer found in invoice.payment_failed event.";}const workspace = await prisma.project.findUnique({@@ -48,12 +43,7 @@ export async function invoicePaymentFailed(event: Stripe.Event) {});if (!workspace) {- console.log(- "Workspace with Stripe ID *`" +- stripeId +- "`* not found in invoice.payment_failed event",- );- return;+ return `Workspace with Stripe ID ${stripeId} not found in invoice.payment_failed event.`;}await Promise.allSettled([@@ -90,4 +80,6 @@ export async function invoicePaymentFailed(event: Stripe.Event) {}),),]);++ return `Recorded payment failure and sent ${workspace.users.length} notice(s) for workspace ${workspace.slug}.`;}diff --git a/apps/web/app/(ee)/api/stripe/webhook/payment-intent-requires-action.ts b/apps/web/app/(ee)/api/stripe/webhook/payment-intent-requires-action.tsindex fd2e11aa11..d2e31f3398 100644--- a/apps/web/app/(ee)/api/stripe/webhook/payment-intent-requires-action.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/payment-intent-requires-action.ts@@ -8,8 +8,7 @@ export async function paymentIntentRequiresAction(event: Stripe.Event) {.object as Stripe.PaymentIntent;if (!invoiceId) {- console.log("No transfer group found, skipping...");- return;+ return "No transfer group found, skipping...";}let invoice = await prisma.invoice.findUnique({@@ -19,8 +18,7 @@ export async function paymentIntentRequiresAction(event: Stripe.Event) {});if (!invoice) {- console.log(`Invoice with transfer group ${invoiceId} not found.`);- return;+ return `Invoice with transfer group ${invoiceId} not found.`;}invoice = await prisma.invoice.update({@@ -38,8 +36,12 @@ export async function paymentIntentRequiresAction(event: Stripe.Event) {});if (invoice.type === "partnerPayout") {- return await processPayoutInvoiceFailure({ invoice });+ await processPayoutInvoiceFailure({ invoice });+ return `Processed partner payout failure for invoice ${invoice.id}.`;} else if (invoice.type === "domainRenewal") {- return await processDomainRenewalFailure({ invoice });+ await processDomainRenewalFailure({ invoice });+ return `Processed domain renewal failure for invoice ${invoice.id}.`;}++ return `Unsupported invoice type (${invoice.type}), skipping...`;}diff --git a/apps/web/app/(ee)/api/stripe/webhook/route.ts b/apps/web/app/(ee)/api/stripe/webhook/route.tsindex 52ce4b22aa..dcd744ecbf 100644--- a/apps/web/app/(ee)/api/stripe/webhook/route.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/route.ts@@ -1,7 +1,7 @@import { stripe } from "@/lib/stripe";import { log } from "@dub/utils";-import { NextResponse } from "next/server";import Stripe from "stripe";+import { logAndRespond } from "../../cron/utils";import { chargeFailed } from "./charge-failed";import { chargeRefunded } from "./charge-refunded";import { chargeSucceeded } from "./charge-succeeded";@@ -10,6 +10,7 @@ import { customerSubscriptionDeleted } from "./customer-subscription-deleted";import { customerSubscriptionUpdated } from "./customer-subscription-updated";import { invoicePaymentFailed } from "./invoice-payment-failed";import { paymentIntentRequiresAction } from "./payment-intent-requires-action";+import { transferReversed } from "./transfer-reversed";const relevantEvents = new Set(["charge.succeeded",@@ -20,6 +21,7 @@ const relevantEvents = new Set(["customer.subscription.deleted","invoice.payment_failed","payment_intent.requires_action",+ "transfer.reversed",]);// POST /api/stripe/webhook – listen to Stripe webhooks@@ -45,31 +47,35 @@ export const POST = async (req: Request) => {});}+ let response = "OK";try {switch (event.type) {case "charge.succeeded":- await chargeSucceeded(event);+ response = await chargeSucceeded(event);break;case "charge.failed":- await chargeFailed(event);+ response = await chargeFailed(event);break;case "charge.refunded":- await chargeRefunded(event);+ response = await chargeRefunded(event);break;case "checkout.session.completed":- await checkoutSessionCompleted(event);+ response = await checkoutSessionCompleted(event);break;case "customer.subscription.updated":- await customerSubscriptionUpdated(event);+ response = await customerSubscriptionUpdated(event);break;case "customer.subscription.deleted":- await customerSubscriptionDeleted(event);+ response = await customerSubscriptionDeleted(event);break;case "invoice.payment_failed":- await invoicePaymentFailed(event);+ response = await invoicePaymentFailed(event);break;case "payment_intent.requires_action":- await paymentIntentRequiresAction(event);+ response = await paymentIntentRequiresAction(event);+ break;+ case "transfer.reversed":+ response = await transferReversed(event);break;}} catch (error) {@@ -82,5 +88,5 @@ export const POST = async (req: Request) => {});}- return NextResponse.json({ received: true });+ return logAndRespond(`[${event.type}]: ${response}`);};diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/transfer-reversed.ts b/apps/web/app/(ee)/api/stripe/webhook/transfer-reversed.tssimilarity index 100%rename from apps/web/app/(ee)/api/stripe/connect/webhook/transfer-reversed.tsrename to apps/web/app/(ee)/api/stripe/webhook/transfer-reversed.ts