The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Renew and charge .link domain (#3882)
Pedro Ladeira0210d2197655
diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/renew-domain.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/renew-domain.tsxnew file mode 100644index 0000000000..e9352e271f--- /dev/null+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/components/renew-domain.tsx@@ -0,0 +1,100 @@+"use client";++import { LoadingSpinner } from "@dub/ui";+import { cn } from "@dub/utils";+import { useFormStatus } from "react-dom";+import { toast } from "sonner";++export function RenewDomain() {+ return (+ <div className="flex flex-col space-y-5">+ <form+ action={async (data) => {+ try {+ const res = await fetch("/api/admin/renew-domain", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ domain: data.get("domain"),+ }),+ });++ const text = await res.text();+ let payload: Record<string, unknown> = {};+ try {+ payload = text ? (JSON.parse(text) as Record<string, unknown>) : {};+ } catch {+ payload = {};+ }++ if (!res.ok) {+ toast.error(+ typeof payload.error === "string"+ ? payload.error+ : text.trim().slice(0, 200) || "Request failed",+ );+ return;+ }++ const message =+ typeof payload.message === "string"+ ? payload.message+ : "Renewal initiated";+ const invoiceId =+ typeof payload.invoiceId === "string"+ ? payload.invoiceId+ : undefined;+ const paymentIntentStatus =+ typeof payload.paymentIntentStatus === "string"+ ? payload.paymentIntentStatus+ : undefined;++ toast.success(message, {+ description: invoiceId+ ? `Invoice: ${invoiceId}${+ paymentIntentStatus+ ? ` · Payment status: ${paymentIntentStatus}`+ : ""+ }`+ : undefined,+ });+ } catch {+ toast.error(+ "Could not reach the server or complete renewal. Check your connection and try again.",+ );+ }+ }}+ >+ <Form />+ </form>+ </div>+ );+}++const Form = () => {+ const { pending } = useFormStatus();++ return (+ <div className="relative flex w-full rounded-md shadow-sm">+ <input+ name="domain"+ id="renew-domain"+ type="text"+ required+ disabled={pending}+ autoComplete="off"+ className={cn(+ "block w-full rounded-md border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:outline-none focus:ring-neutral-500 sm:text-sm",+ pending && "bg-neutral-100",+ )}+ placeholder="acme.link"+ aria-invalid="true"+ />+ {pending && (+ <LoadingSpinner className="absolute inset-y-0 right-2 my-auto h-full w-5 text-neutral-400" />+ )}+ </div>+ );+};diff --git a/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx b/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsxindex 52d77b8ed8..338d9beae3 100644--- a/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx+++ b/apps/web/app/(ee)/admin.dub.co/(dashboard)/page.tsx@@ -3,6 +3,7 @@ import { DeletePartnerAccount } from "./components/delete-partner-account";import { ImpersonateUser } from "./components/impersonate-user";import { ImpersonateWorkspace } from "./components/impersonate-workspace";import { RefreshDomain } from "./components/refresh-domain";+import { RenewDomain } from "./components/renew-domain";import { ResetLoginAttempts } from "./components/reset-login-attempts";import { SlackSupportInvite } from "./components/slack-support-invite";@@ -42,6 +43,16 @@ export default function AdminPage() {</p><DeletePartnerAccount /></div>+ <div className="flex flex-col space-y-4 px-5 py-10">+ <h2 className="text-xl font-semibold">Renew domain (.link)</h2>+ <p className="text-sm text-neutral-500">+ Create a new domain-renewal invoice and charge the workspace default+ payment method. On success, Stripe webhooks extend Dub expiry and+ re-enable Dynadot auto-renew. If the domain has already expired at+ Dynadot, you may still need to renew it in the Dynadot dashboard.+ </p>+ <RenewDomain />+ </div><div className="flex flex-col space-y-4 px-5 py-10"><h2 className="text-xl font-semibold">Refresh Domain</h2><p className="text-sm text-neutral-500">diff --git a/apps/web/app/(ee)/api/admin/renew-domain/route.ts b/apps/web/app/(ee)/api/admin/renew-domain/route.tsnew file mode 100644index 0000000000..053d54e2e8--- /dev/null+++ b/apps/web/app/(ee)/api/admin/renew-domain/route.ts@@ -0,0 +1,189 @@+import { createId } from "@/lib/api/create-id";+import { withAdmin } from "@/lib/auth";+import { createPaymentIntent } from "@/lib/stripe/create-payment-intent";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";+import * as z from "zod/v4";++const schema = z.object({+ domain: z.string().min(1),+});++// POST /api/admin/renew-domain+export const POST = withAdmin(async ({ req }) => {+ const parsed = schema.safeParse(await req.json());+ if (!parsed.success) {+ return NextResponse.json({ error: parsed.error.message }, { status: 400 });+ }++ const normalized = normalizeDomainInput(parsed.data.domain);+ if (!normalized) {+ return NextResponse.json({ error: "Invalid domain." }, { status: 400 });+ }++ const registered = await prisma.registeredDomain.findFirst({+ where: { slug: normalized },+ select: {+ slug: true,+ renewalFee: true,+ projectId: true,+ project: {+ select: {+ id: true,+ stripeId: true,+ invoicePrefix: true,+ },+ },+ },+ });++ if (!registered) {+ return NextResponse.json(+ { error: `No registered domain found for "${normalized}".` },+ { status: 404 },+ );+ }++ if (!registered.project.stripeId) {+ return NextResponse.json(+ { error: "Workspace has no Stripe customer; add billing first." },+ { status: 400 },+ );+ }++ if (!registered.renewalFee || registered.renewalFee <= 0) {+ return NextResponse.json(+ { error: `Domain "${normalized}" has no valid renewal fee configured.` },+ { status: 400 },+ );+ }++ const outcome = await prisma.$transaction(async (tx) => {+ const pendingInvoices = await tx.invoice.findMany({+ where: {+ workspaceId: registered.projectId,+ type: "domainRenewal",+ status: "processing",+ },+ select: {+ registeredDomains: true,+ },+ });++ const hasPendingForSlug = pendingInvoices.some((inv) => {+ const slugs = inv.registeredDomains as string[] | null;+ return (+ Array.isArray(slugs) &&+ (slugs.includes(registered.slug) || slugs.includes(normalized))+ );+ });++ if (hasPendingForSlug) {+ return { ok: false as const };+ }++ const totalInvoices = await tx.invoice.count({+ where: {+ workspaceId: registered.projectId,+ },+ });+ const paddedNumber = String(totalInvoices + 1).padStart(4, "0");+ const invoiceNumber = `${registered.project.invoicePrefix}-${paddedNumber}`;+ const renewalFee = registered.renewalFee;++ const invoice = await tx.invoice.create({+ data: {+ id: createId({ prefix: "inv_" }),+ workspaceId: registered.projectId,+ number: invoiceNumber,+ type: "domainRenewal",+ amount: renewalFee,+ total: renewalFee,+ registeredDomains: [registered.slug],+ },+ });++ return { ok: true as const, invoice };+ });++ if (!outcome.ok) {+ return NextResponse.json(+ {+ error:+ "A domain renewal charge is already processing for this domain. Wait for it to complete or fail before retrying.",+ },+ { status: 409 },+ );+ }++ const invoice = outcome.invoice;++ const { paymentIntent } = await createPaymentIntent({+ stripeId: registered.project.stripeId!,+ amount: invoice.total,+ invoiceId: invoice.id,+ statementDescriptor: "DUB.CO DOMAIN RENEWAL",+ description: `Domain renewal invoice (${invoice.id})`,+ idempotencyKey: `${invoice.id}-${invoice.failedAttempts}`,+ });++ if (!paymentIntent) {+ await prisma.invoice.update({+ where: { id: invoice.id },+ data: {+ status: "failed",+ failedReason: "Could not charge the workspace payment method.",+ },+ });++ return NextResponse.json(+ {+ error: "Could not charge the workspace payment method.",+ invoiceId: invoice.id,+ },+ { status: 422 },+ );+ }++ const status = paymentIntent.status;++ if (status === "succeeded") {+ return NextResponse.json({+ success: true,+ message:+ "Charge succeeded. Domain renewal will finalize via Stripe webhook (updates expiry and Dynadot auto-renew).",+ invoiceId: invoice.id,+ paymentIntentStatus: status,+ });+ }++ return NextResponse.json({+ success: true,+ message:+ "Payment initiated. If the payment is not yet succeeded, the customer may need to complete authentication; Stripe webhooks will update the invoice.",+ invoiceId: invoice.id,+ paymentIntentStatus: status,+ });+});++function normalizeDomainInput(raw: string): string {+ let s = raw.trim().toLowerCase();+ if (!s) {+ return s;+ }+ try {+ if (s.includes("://")) {+ const url = new URL(s);+ s = url.hostname;+ } else if (s.includes("/")) {+ const url = new URL(`https://${s}`);+ s = url.hostname;+ }+ } catch {+ // keep s as typed+ }+ if (s.startsWith("www.")) {+ s = s.slice(4);+ }+ return s;+}diff --git a/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts b/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.tsindex 9949f9c1af..886b1a2566 100644--- a/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts+++ b/apps/web/app/(ee)/api/cron/domains/renewal-payments/route.ts@@ -140,7 +140,7 @@ export async function GET(req: Request) {stripeId: workspace.stripeId!,amount: invoice.total,invoiceId: invoice.id,- statementDescriptor: "Dub",+ statementDescriptor: "DUB.CO DOMAIN RENEWAL",description: `Domain renewal invoice (${invoice.id})`,idempotencyKey: `${invoice.id}-${invoice.failedAttempts}`,});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.tsindex cb9845a114..0180161df9 100644--- a/apps/web/app/(ee)/api/cron/invoices/retry-failed/route.ts+++ b/apps/web/app/(ee)/api/cron/invoices/retry-failed/route.ts@@ -72,7 +72,7 @@ export async function POST(req: Request) {stripeId: invoice.workspace.stripeId,amount: invoice.total,invoiceId: invoice.id,- statementDescriptor: "Dub",+ statementDescriptor: "DUB.CO DOMAIN RENEWAL",description: `Domain renewal invoice (${invoice.id})`,idempotencyKey: `${invoice.id}-${invoice.failedAttempts}`,});diff --git a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.tsindex 4287624667..b08203b6bf 100644--- a/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts+++ b/apps/web/app/(ee)/api/stripe/webhook/charge-succeeded.ts@@ -5,7 +5,7 @@ import DomainRenewed from "@dub/email/templates/domain-renewed";import { prisma } from "@dub/prisma";import { Invoice } from "@dub/prisma/client";import { APP_DOMAIN_WITH_NGROK, pluralize } from "@dub/utils";-import { addDays } from "date-fns";+import { addDays, startOfDay } from "date-fns";import Stripe from "stripe";export async function chargeSucceeded(event: Stripe.ChargeSucceededEvent) {@@ -120,7 +120,11 @@ async function processDomainRenewalInvoice({ invoice }: { invoice: Invoice }) {return `No domains found for invoice ${invoice.id}, skipping...`;}- const newExpiresAt = addDays(domains[0].expiresAt, 365);+ const earliestExpiresAt = domains[0].expiresAt;+ const todayStart = startOfDay(new Date());+ const renewalBase =+ earliestExpiresAt > todayStart ? earliestExpiresAt : todayStart;+ const newExpiresAt = addDays(renewalBase, 365);await prisma.registeredDomain.updateMany({where: {diff --git a/apps/web/lib/dynadot/set-renew-option.ts b/apps/web/lib/dynadot/set-renew-option.tsindex 7a9d4b652c..93abccee86 100644--- a/apps/web/lib/dynadot/set-renew-option.ts+++ b/apps/web/lib/dynadot/set-renew-option.ts@@ -51,7 +51,7 @@ export const setRenewOption = async ({);} catch (error) {await log({- message: `Failed to set renew option for ${domain}: ${error.message}`,+ message: `Failed to set renew option for ${domain}: ${error instanceof Error ? error.message : String(error)}`,type: "errors",mention: true,});diff --git a/apps/web/lib/stripe/create-payment-intent.ts b/apps/web/lib/stripe/create-payment-intent.tsindex 35c0b75ed2..58dadf09b5 100644--- a/apps/web/lib/stripe/create-payment-intent.ts+++ b/apps/web/lib/stripe/create-payment-intent.ts@@ -51,7 +51,8 @@ export const createPaymentIntent = async ({currency: "usd",confirmation_method: "automatic",confirm: true,- statement_descriptor: statementDescriptor,+ // Card PI creation rejects `statement_descriptor`; use suffix (max 22 chars on networks).+ statement_descriptor_suffix: statementDescriptor.slice(0, 22),description,},idempotencyKey ? { idempotencyKey } : undefined,