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.

Implement domain renewal failure handling and add payment intent action webhook

Kiran K755c5adf13e8
diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
index 64abf17554..a5f5e152c4 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
@@ -1,19 +1,16 @@
-import { qstash } from "@/lib/cron";
-import { setRenewOption } from "@/lib/dynadot/set-renew-option";
import {
DIRECT_DEBIT_PAYMENT_METHOD_TYPES,
PAYOUT_FAILURE_FEE_CENTS,
} from "@/lib/partners/constants";
import { createPaymentIntent } from "@/lib/stripe/create-payment-intent";
-import { sendBatchEmail, sendEmail } from "@dub/email";
-import DomainExpired from "@dub/email/templates/domain-expired";
-import DomainRenewalFailed from "@dub/email/templates/domain-renewal-failed";
+import { sendEmail } from "@dub/email";
import PartnerPayoutFailed from "@dub/email/templates/partner-payout-failed";
import { prisma } from "@dub/prisma";
import { Invoice } from "@dub/prisma/client";
-import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
+import { log } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import Stripe from "stripe";
+import { processDomainRenewalFailure } from "./process-domain-renewal-failure";
export async function chargeFailed(event: Stripe.Event) {
const charge = event.data.object as Stripe.Charge;
@@ -52,7 +49,7 @@ export async function chargeFailed(event: Stripe.Event) {
if (invoice.type === "partnerPayout") {
await processPayoutInvoice({ invoice, charge });
} else if (invoice.type === "domainRenewal") {
- await processDomainRenewalInvoice({ invoice });
+ await processDomainRenewalFailure({ invoice });
}
}
@@ -182,111 +179,3 @@ async function processPayoutInvoice({
})(),
);
}
-
-async function processDomainRenewalInvoice({ invoice }: { invoice: Invoice }) {
- const domains = await prisma.registeredDomain.findMany({
- where: {
- slug: {
- in: invoice.registeredDomains as string[],
- },
- },
- select: {
- slug: true,
- expiresAt: true,
- },
- });
-
- const workspace = await prisma.project.findUniqueOrThrow({
- where: {
- id: invoice.workspaceId,
- },
- include: {
- users: {
- where: {
- role: "owner",
- },
- select: {
- user: true,
- },
- },
- },
- });
-
- const workspaceOwners = workspace.users.filter(({ user }) => user.email);
-
- // Domain renewal failed 3 times:
- // 1. Turn off auto-renew for the domains on Dynadot
- // 2. Disable auto-renew for the domains on Dub
- // 3. Send email to the workspace users
- if (invoice.failedAttempts >= 3) {
- await Promise.allSettled(
- domains.map((domain) =>
- setRenewOption({
- domain: domain.slug,
- autoRenew: false,
- }),
- ),
- );
-
- const updateDomains = await prisma.registeredDomain.updateMany({
- where: {
- slug: {
- in: domains.map(({ slug }) => slug),
- },
- },
- data: {
- autoRenewalDisabledAt: new Date(),
- },
- });
- console.log(
- `Updated autoRenewalDisabledAt for ${updateDomains.count} domains.`,
- );
-
- if (workspaceOwners.length > 0) {
- await sendBatchEmail(
- workspaceOwners.map(({ user }) => ({
- variant: "notifications",
- to: user.email!,
- subject: "Domain expired",
- react: DomainExpired({
- email: user.email!,
- workspace: {
- name: workspace.name,
- slug: workspace.slug,
- },
- domains,
- }),
- })),
- );
- }
- }
-
- // We'll retry the invoice 3 times, if it fails 3 times, we'll turn off auto-renew for the domains
- if (invoice.failedAttempts < 3) {
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/invoices/retry-failed`,
- delay: 3 * 24 * 60 * 60, // 3 days in seconds
- deduplicationId: `${invoice.id}-attempt-${invoice.failedAttempts + 1}`,
- body: {
- invoiceId: invoice.id,
- },
- });
-
- if (workspaceOwners.length > 0) {
- await sendBatchEmail(
- workspaceOwners.map(({ user }) => ({
- variant: "notifications",
- to: user.email!,
- subject: "Domain renewal failed",
- react: DomainRenewalFailed({
- email: user.email!,
- workspace: {
- slug: workspace.slug,
- },
- domains,
- }),
- })),
- );
- }
- }
-}
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.ts
new file mode 100644
index 0000000000..a1a918ac8c
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/webhook/payment-intent-requires-action.ts
@@ -0,0 +1,47 @@
+import { prisma } from "@dub/prisma";
+import Stripe from "stripe";
+import { processDomainRenewalFailure } from "./process-domain-renewal-failure";
+
+export async function paymentIntentRequiresAction(event: Stripe.Event) {
+ const { transfer_group: invoiceId } = event.data
+ .object as Stripe.PaymentIntent;
+
+ if (!invoiceId) {
+ console.log("No transfer group found, skipping...");
+ return;
+ }
+
+ let invoice = await prisma.invoice.findUnique({
+ where: {
+ id: invoiceId,
+ },
+ });
+
+ if (!invoice) {
+ console.log(`Invoice with transfer group ${invoiceId} not found.`);
+ return;
+ }
+
+ if (invoice.type !== "domainRenewal") {
+ console.log(
+ `Invoice with transfer group ${invoiceId} is not a domain renewal.`,
+ );
+ return;
+ }
+
+ invoice = await prisma.invoice.update({
+ where: {
+ id: invoiceId,
+ },
+ data: {
+ status: "failed",
+ failedReason:
+ "Your payment requires additional authentication to complete.",
+ failedAttempts: {
+ increment: 1,
+ },
+ },
+ });
+
+ return await processDomainRenewalFailure({ invoice });
+}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/process-domain-renewal-failure.ts b/apps/web/app/(ee)/api/stripe/webhook/process-domain-renewal-failure.ts
new file mode 100644
index 0000000000..4322d692d1
--- /dev/null
+++ b/apps/web/app/(ee)/api/stripe/webhook/process-domain-renewal-failure.ts
@@ -0,0 +1,120 @@
+import { qstash } from "@/lib/cron";
+import { setRenewOption } from "@/lib/dynadot/set-renew-option";
+import { sendBatchEmail } from "@dub/email";
+import DomainExpired from "@dub/email/templates/domain-expired";
+import DomainRenewalFailed from "@dub/email/templates/domain-renewal-failed";
+import { prisma } from "@dub/prisma";
+import { Invoice } from "@dub/prisma/client";
+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+
+export async function processDomainRenewalFailure({
+ invoice,
+}: {
+ invoice: Invoice;
+}) {
+ const domains = await prisma.registeredDomain.findMany({
+ where: {
+ slug: {
+ in: invoice.registeredDomains as string[],
+ },
+ },
+ select: {
+ slug: true,
+ expiresAt: true,
+ },
+ });
+
+ const workspace = await prisma.project.findUniqueOrThrow({
+ where: {
+ id: invoice.workspaceId,
+ },
+ include: {
+ users: {
+ where: {
+ role: "owner",
+ },
+ select: {
+ user: true,
+ },
+ },
+ },
+ });
+
+ const workspaceOwners = workspace.users.filter(({ user }) => user.email);
+
+ // Domain renewal failed 3 times:
+ // 1. Turn off auto-renew for the domains on Dynadot
+ // 2. Disable auto-renew for the domains on Dub
+ // 3. Send email to the workspace users
+ if (invoice.failedAttempts >= 3) {
+ await Promise.allSettled(
+ domains.map((domain) =>
+ setRenewOption({
+ domain: domain.slug,
+ autoRenew: false,
+ }),
+ ),
+ );
+
+ const updateDomains = await prisma.registeredDomain.updateMany({
+ where: {
+ slug: {
+ in: domains.map(({ slug }) => slug),
+ },
+ },
+ data: {
+ autoRenewalDisabledAt: new Date(),
+ },
+ });
+ console.log(
+ `Updated autoRenewalDisabledAt for ${updateDomains.count} domains.`,
+ );
+
+ if (workspaceOwners.length > 0) {
+ await sendBatchEmail(
+ workspaceOwners.map(({ user }) => ({
+ variant: "notifications",
+ to: user.email!,
+ subject: "Domain expired",
+ react: DomainExpired({
+ email: user.email!,
+ workspace: {
+ name: workspace.name,
+ slug: workspace.slug,
+ },
+ domains,
+ }),
+ })),
+ );
+ }
+ }
+
+ // We'll retry the invoice 3 times, if it fails 3 times, we'll turn off auto-renew for the domains
+ if (invoice.failedAttempts < 3) {
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/invoices/retry-failed`,
+ delay: 3 * 24 * 60 * 60, // 3 days in seconds
+ deduplicationId: `${invoice.id}-attempt-${invoice.failedAttempts + 1}`,
+ body: {
+ invoiceId: invoice.id,
+ },
+ });
+
+ if (workspaceOwners.length > 0) {
+ await sendBatchEmail(
+ workspaceOwners.map(({ user }) => ({
+ variant: "notifications",
+ to: user.email!,
+ subject: "Domain renewal failed",
+ react: DomainRenewalFailed({
+ email: user.email!,
+ workspace: {
+ slug: workspace.slug,
+ },
+ domains,
+ }),
+ })),
+ );
+ }
+ }
+}
diff --git a/apps/web/app/(ee)/api/stripe/webhook/route.ts b/apps/web/app/(ee)/api/stripe/webhook/route.ts
index 76f79b778a..52ce4b22aa 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/route.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/route.ts
@@ -9,6 +9,7 @@ import { checkoutSessionCompleted } from "./checkout-session-completed";
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";
const relevantEvents = new Set([
"charge.succeeded",
@@ -18,6 +19,7 @@ const relevantEvents = new Set([
"customer.subscription.updated",
"customer.subscription.deleted",
"invoice.payment_failed",
+ "payment_intent.requires_action",
]);
// POST /api/stripe/webhook – listen to Stripe webhooks
@@ -66,6 +68,9 @@ export const POST = async (req: Request) => {
case "invoice.payment_failed":
await invoicePaymentFailed(event);
break;
+ case "payment_intent.requires_action":
+ await paymentIntentRequiresAction(event);
+ break;
}
} catch (error) {
await log({