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 automated retry for failed domain renewal invoices

Kiran K28dd4fb92ba9
diff --git a/apps/web/app/(ee)/api/cron/invoices/retry-failed/route.ts b/apps/web/app/(ee)/api/cron/invoices/retry-failed/route.ts
new file mode 100644
index 0000000000..e86c799de3
--- /dev/null
+++ b/apps/web/app/(ee)/api/cron/invoices/retry-failed/route.ts
@@ -0,0 +1,80 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
+import { createPaymentIntent } from "@/lib/stripe/create-payment-intent";
+import { prisma } from "@dub/prisma";
+import { z } from "zod";
+
+export const dynamic = "force-dynamic";
+
+const schema = z.object({
+ invoiceId: z.string().min(1),
+});
+
+// POST /api/cron/invoices/retry-failed
+export async function POST(req: Request) {
+ try {
+ const rawBody = await req.text();
+
+ await verifyQstashSignature({
+ req,
+ rawBody,
+ });
+
+ const { invoiceId } = schema.parse(JSON.parse(rawBody));
+
+ const invoice = await prisma.invoice.findUnique({
+ where: {
+ id: invoiceId,
+ },
+ select: {
+ id: true,
+ type: true,
+ status: true,
+ total: true,
+ failedAttempts: true,
+ workspace: {
+ select: {
+ id: true,
+ stripeId: true,
+ },
+ },
+ },
+ });
+
+ if (!invoice) {
+ return new Response(`Invoice ${invoiceId} not found.`);
+ }
+
+ if (invoice.status !== "failed") {
+ return new Response(`Invoice ${invoiceId} is not failed.`);
+ }
+
+ if (invoice.failedAttempts >= 3) {
+ return new Response(
+ `Invoice ${invoiceId} has reached max failed attempts of 3.`,
+ );
+ }
+
+ if (invoice.type !== "domainRenewal") {
+ return new Response(`Only domain renewals can be retried at this time.`);
+ }
+
+ if (!invoice.workspace.stripeId) {
+ return new Response(`Workspace ${invoice.workspace.id} has no stripeId.`);
+ }
+
+ await createPaymentIntent({
+ stripeId: invoice.workspace.stripeId,
+ amount: invoice.total,
+ invoiceId: invoice.id,
+ statementDescriptor: "Dub",
+ description: `Domain renewal invoice (${invoice.id})`,
+ });
+
+ return new Response(`Retrying invoice ${invoice.id}...`);
+ } catch (error) {
+ console.error(error);
+
+ return handleAndReturnErrorResponse(error);
+ }
+}
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 d4c8386912..a621c5f9bc 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-failed.ts
@@ -1,3 +1,4 @@
+import { qstash } from "@/lib/cron";
import {
DIRECT_DEBIT_PAYMENT_METHOD_TYPES,
PAYOUT_FAILURE_FEE_CENTS,
@@ -7,7 +8,7 @@ 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 { log } from "@dub/utils";
+import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import Stripe from "stripe";
@@ -21,17 +22,10 @@ export async function chargeFailed(event: Stripe.Event) {
return;
}
- const invoice = await prisma.invoice.findUnique({
+ let invoice = await prisma.invoice.findUnique({
where: {
id: invoiceId,
},
- select: {
- id: true,
- status: true,
- type: true,
- workspaceId: true,
- amount: true,
- },
});
if (!invoice) {
@@ -39,13 +33,16 @@ export async function chargeFailed(event: Stripe.Event) {
return;
}
- await prisma.invoice.update({
+ invoice = await prisma.invoice.update({
where: {
id: invoiceId,
},
data: {
status: "failed",
failedReason,
+ failedAttempts: {
+ increment: 1,
+ },
},
});
@@ -208,10 +205,20 @@ async function processRenewalInvoice({
invoice,
charge,
}: {
- invoice: Pick<Invoice, "id">;
+ invoice: Pick<Invoice, "id" | "failedAttempts">;
charge: Stripe.Charge;
}) {
+ 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,
+ },
+ });
+ }
+
// TODO:
- // Schedule another charge in 3 days (total 3 charges) using qstash
// Send email to the user
}
diff --git a/apps/web/lib/stripe/create-payment-intent.ts b/apps/web/lib/stripe/create-payment-intent.ts
new file mode 100644
index 0000000000..e29553236d
--- /dev/null
+++ b/apps/web/lib/stripe/create-payment-intent.ts
@@ -0,0 +1,69 @@
+import { log } from "@dub/utils";
+import { stripe } from ".";
+
+export const createPaymentIntent = async ({
+ stripeId,
+ amount,
+ invoiceId,
+ description,
+ statementDescriptor,
+}: {
+ stripeId: string;
+ amount: number;
+ invoiceId: string;
+ description: string;
+ statementDescriptor: string;
+}) => {
+ const [cards, links] = await Promise.all([
+ stripe.paymentMethods.list({
+ customer: stripeId,
+ type: "card",
+ }),
+
+ stripe.paymentMethods.list({
+ customer: stripeId,
+ type: "link",
+ }),
+ ]);
+
+ if (cards.data.length === 0 && links.data.length === 0) {
+ console.error(`No valid payment methods found for customer ${stripeId}.`);
+ return;
+ }
+
+ const paymentMethod = cards.data[0] || links.data[0];
+
+ if (!paymentMethod) {
+ console.error(`No valid payment method found for customer ${stripeId}.`);
+ return;
+ }
+
+ try {
+ const paymentIntent = await stripe.paymentIntents.create({
+ amount,
+ customer: stripeId,
+ transfer_group: invoiceId,
+ payment_method_types: ["card", "link"],
+ payment_method: paymentMethod.id,
+ currency: "usd",
+ confirmation_method: "automatic",
+ confirm: true,
+ statement_descriptor: statementDescriptor,
+ description,
+ });
+
+ console.log(
+ `Payment intent ${paymentIntent.id} created for the invoice ${invoiceId}.`,
+ );
+
+ return paymentIntent;
+ } catch (error) {
+ console.error(error);
+
+ await log({
+ message: `Failed to create payment intent for the invoice ${invoiceId}.`,
+ type: "errors",
+ mention: true,
+ });
+ }
+};
diff --git a/packages/prisma/schema/invoice.prisma b/packages/prisma/schema/invoice.prisma
index 0b60606f91..e3c0de3959 100644
--- a/packages/prisma/schema/invoice.prisma
+++ b/packages/prisma/schema/invoice.prisma
@@ -22,6 +22,7 @@ model Invoice {
receiptUrl String? @db.Text
failedReason String? @db.Text
stripeChargeMetadata Json? @db.Json // Stripe charge metadata
+ failedAttempts Int @default(0) // number of failed attempts to charge the invoice
createdAt DateTime @default(now())
paidAt DateTime?