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.

Add payout failed webhook handling and email notification

Kiran K9d180e7fe134
diff --git a/apps/web/app/(ee)/api/cron/payouts/payout-paid/route.ts b/apps/web/app/(ee)/api/cron/payouts/payout-paid/route.ts
index 1bd6dd4899..7eaf62f95a 100644
--- a/apps/web/app/(ee)/api/cron/payouts/payout-paid/route.ts
+++ b/apps/web/app/(ee)/api/cron/payouts/payout-paid/route.ts
@@ -3,7 +3,7 @@ import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
import { sendEmail } from "@dub/email";
import PartnerPayoutWithdrawalCompleted from "@dub/email/templates/partner-payout-withdrawal-completed";
import { prisma } from "@dub/prisma";
-import { currencyFormatter, log } from "@dub/utils";
+import { currencyFormatter, log, prettyPrint } from "@dub/utils";
import { z } from "zod";
import { logAndRespond } from "../../utils";
@@ -71,7 +71,7 @@ export async function POST(req: Request) {
});
console.log(
- `Sent email to partner ${partner.email} (${stripeAccount}): ${JSON.stringify(sentEmail, null, 2)}`,
+ `Sent email to partner ${partner.email} (${stripeAccount}): ${prettyPrint(sentEmail)}`,
);
}
diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/payout-failed.ts b/apps/web/app/(ee)/api/stripe/connect/webhook/payout-failed.ts
new file mode 100644
index 0000000000..4d0991646a
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/connect/webhook/payout-failed.ts
@@ -0,0 +1,73 @@
+import { stripe } from "@/lib/stripe";
+import { sendEmail } from "@dub/email";
+import PartnerStripePayoutFailed from "@dub/email/templates/partner-stripe-payout-failed";
+import { prisma } from "@dub/prisma";
+import { prettyPrint } from "@dub/utils";
+import Stripe from "stripe";
+
+export async function payoutFailed(event: Stripe.Event) {
+ const stripeConnectId = event.account;
+
+ if (!stripeConnectId) {
+ return "No stripeConnectId found in event. Skipping...";
+ }
+
+ const partner = await prisma.partner.findUnique({
+ where: {
+ stripeConnectId,
+ },
+ select: {
+ email: true,
+ payoutsEnabledAt: true,
+ },
+ });
+
+ if (!partner) {
+ return `Partner not found with Stripe connect account ${stripeConnectId}. Skipping...`;
+ }
+
+ const stripePayout = event.data.object as Stripe.Payout;
+
+ const updatedPayouts = await prisma.payout.updateMany({
+ where: {
+ status: "sent",
+ stripePayoutId: stripePayout.id,
+ },
+ data: {
+ status: "failed",
+ failureReason: stripePayout.failure_message,
+ },
+ });
+
+ if (partner.email) {
+ try {
+ const { url } = await stripe.accounts.createLoginLink(stripeConnectId);
+
+ const sentEmail = await sendEmail({
+ variant: "notifications",
+ subject: `Action Required - Your recent payout failed`,
+ to: partner.email,
+ react: PartnerStripePayoutFailed({
+ email: partner.email,
+ accountUpdateUrl: url,
+ payout: {
+ amount: stripePayout.amount,
+ currency: stripePayout.currency,
+ failureReason: stripePayout.failure_message,
+ },
+ }),
+ });
+
+ console.log(
+ `Sent email to partner ${partner.email} (${stripeConnectId}): ${prettyPrint(sentEmail)}`,
+ );
+ } catch (error) {
+ console.error(
+ `Failed to send payout failed email to ${partner.email}:`,
+ error,
+ );
+ }
+ }
+
+ return `Updated ${updatedPayouts.count} payouts for partner ${partner.email} (${stripeConnectId}) to "failed" status.`;
+}
diff --git a/apps/web/app/(ee)/api/stripe/connect/webhook/route.ts b/apps/web/app/(ee)/api/stripe/connect/webhook/route.ts
index afd1a70805..7c4e6a87b3 100644
--- a/apps/web/app/(ee)/api/stripe/connect/webhook/route.ts
+++ b/apps/web/app/(ee)/api/stripe/connect/webhook/route.ts
@@ -5,6 +5,7 @@ import Stripe from "stripe";
import { accountApplicationDeauthorized } from "./account-application-deauthorized";
import { accountUpdated } from "./account-updated";
import { balanceAvailable } from "./balance-available";
+import { payoutFailed } from "./payout-failed";
import { payoutPaid } from "./payout-paid";
const relevantEvents = new Set([
@@ -12,6 +13,7 @@ const relevantEvents = new Set([
"account.updated",
"balance.available",
"payout.paid",
+ "payout.failed",
]);
// POST /api/stripe/connect/webhook – listen to Stripe Connect webhooks (for connected accounts)
@@ -53,6 +55,9 @@ export const POST = async (req: Request) => {
case "payout.paid":
response = await payoutPaid(event);
break;
+ case "payout.failed":
+ response = await payoutFailed(event);
+ break;
}
} catch (error) {
await log({
diff --git a/packages/email/src/templates/partner-stripe-payout-failed.tsx b/packages/email/src/templates/partner-stripe-payout-failed.tsx
new file mode 100644
index 0000000000..6ed69ded97
--- /dev/null
+++ b/packages/email/src/templates/partner-stripe-payout-failed.tsx
@@ -0,0 +1,103 @@
+import { currencyFormatter, DUB_WORDMARK } from "@dub/utils";
+import {
+ Body,
+ Container,
+ Head,
+ Heading,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Section,
+ Tailwind,
+ Text,
+} from "@react-email/components";
+import { Footer } from "../components/footer";
+
+// Send this email to the partner when the Stripe payout fails
+export default function PartnerStripePayoutFailed({
+ email = "[email protected]",
+ accountUpdateUrl = "https://partners.dub.co/payouts",
+ payout = {
+ amount: 530000,
+ currency: "usd",
+ failureReason:
+ "Your bank notified us that the bank account holder tax ID on file is incorrect.",
+ },
+}: {
+ email: string;
+ accountUpdateUrl: string;
+ payout: {
+ amount: number; // in cents
+ currency: string;
+ failureReason?: string | null;
+ };
+}) {
+ const amountFormatted = currencyFormatter(payout.amount, {
+ currency: payout.currency,
+ });
+
+ return (
+ <Html>
+ <Head />
+ <Preview>Action Required - Your recent payout failed</Preview>
+ <Tailwind>
+ <Body className="mx-auto my-auto bg-white font-sans">
+ <Container className="mx-auto my-8 max-w-[600px] px-8 py-8">
+ <Section className="mt-8">
+ <Img src={DUB_WORDMARK} height="32" alt="Dub" />
+ </Section>
+
+ <Heading className="mx-0 my-8 p-0 text-lg font-medium text-black">
+ Your recent payout failed
+ </Heading>
+
+ <Text>
+ We attempted to send your recent payout of{" "}
+ <span className="font-semibold text-purple-600">
+ {amountFormatted}
+ </span>{" "}
+ to your connected bank account, but the transaction failed.
+ </Text>
+
+ {payout.failureReason && (
+ <Text className="text-sm leading-6 text-neutral-600">
+ Reason:{" "}
+ <span className="font-semibold italic text-neutral-800">
+ {payout.failureReason}
+ </span>
+ </Text>
+ )}
+
+ <Text>
+ Please update your bank account details as soon as possible. A
+ failed payout is automatically retried, so having accurate bank
+ details on file ensures your payout can be successfully deposited.
+ </Text>
+
+ <Section className="my-8">
+ <Link
+ className="rounded-lg bg-neutral-900 px-6 py-3 text-[13px] font-medium text-white no-underline"
+ href={accountUpdateUrl}
+ >
+ Update bank account
+ </Link>
+ </Section>
+
+ <Text className="text-sm leading-6 text-neutral-600">
+ If you have any questions, please reach out to us:{" "}
+ <Link
+ href="https://dub.co/contact/support"
+ className="font-medium text-black underline"
+ >
+ https://dub.co/contact/support
+ </Link>
+ </Text>
+
+ <Footer email={email} />
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}