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 microdeposit verification support (#4342)

Steven Tey70f61ca32b3a
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/route.ts
index 381e6ac282..2de6675303 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/route.ts
@@ -7,6 +7,10 @@ import {
PAYMENT_METHOD_TYPES,
} from "@/lib/constants/payouts";
import { stripe } from "@/lib/stripe";
+import {
+ listPendingMicrodeposits,
+ withMicrodepositStatus,
+} from "@/lib/stripe/microdeposits";
import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
import Stripe from "stripe";
@@ -61,6 +65,10 @@ export const GET = withWorkspace(
stripe.customers.retrieve(workspace.stripeId),
]);
+ const pendingMicrodeposits = await listPendingMicrodeposits(
+ workspace.stripeId,
+ ).catch(() => []);
+
const defaultPaymentMethod =
customer.deleted !== true
? customer.invoice_settings?.default_payment_method
@@ -71,17 +79,20 @@ export const GET = withWorkspace(
? defaultPaymentMethod
: defaultPaymentMethod?.id ?? null;
+ const methods = withMicrodepositStatus({
+ paymentMethods: paymentMethods.data,
+ pendingMicrodeposits,
+ });
+
// reorder to put direct debit first
- const directDebit = paymentMethods.data.find((method) =>
+ const directDebit = methods.find((method) =>
DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(method.type),
);
return NextResponse.json({
paymentMethods: [
...(directDebit ? [directDebit] : []),
- ...paymentMethods.data.filter(
- (method) => method.id !== directDebit?.id,
- ),
+ ...methods.filter((method) => method.id !== directDebit?.id),
],
defaultPaymentMethodId,
});
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/verify-microdeposits/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/verify-microdeposits/route.ts
new file mode 100644
index 0000000000..4d3ec2456c
--- /dev/null
+++ b/apps/web/app/api/workspaces/[idOrSlug]/billing/payment-methods/verify-microdeposits/route.ts
@@ -0,0 +1,98 @@
+import { DubApiError } from "@/lib/api/errors";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import {
+ findPendingMicrodeposit,
+ verifyIntentMicrodeposits,
+} from "@/lib/stripe/microdeposits";
+import { NextResponse } from "next/server";
+import Stripe from "stripe";
+import * as z from "zod/v4";
+
+const verifyMicrodepositsSchema = z
+ .object({
+ paymentMethodId: z.string().min(1),
+ amounts: z
+ .tuple([z.number().int().min(1).max(99), z.number().int().min(1).max(99)])
+ .optional(),
+ descriptorCode: z
+ .string()
+ .regex(/^SM[0-9A-Z]{4}$/i, {
+ message: "Descriptor code must be 6 characters starting with SM.",
+ })
+ .optional(),
+ })
+ .refine((data) => Boolean(data.amounts) !== Boolean(data.descriptorCode), {
+ message: "Provide either deposit amounts or a descriptor code.",
+ });
+
+// POST /api/workspaces/[idOrSlug]/billing/payment-methods/verify-microdeposits
+export const POST = withWorkspace(
+ async ({ workspace, req }) => {
+ if (!workspace.stripeId) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Workspace does not have a Stripe ID.",
+ });
+ }
+
+ const { paymentMethodId, amounts, descriptorCode } =
+ verifyMicrodepositsSchema.parse(await parseRequestBody(req));
+
+ const pending = await findPendingMicrodeposit({
+ stripeId: workspace.stripeId,
+ paymentMethodId,
+ });
+
+ if (!pending) {
+ throw new DubApiError({
+ code: "not_found",
+ message:
+ "No pending microdeposit verification found for this payment method.",
+ });
+ }
+
+ if (pending.type === "descriptor_code" && !descriptorCode) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "This bank account requires a 6-character descriptor code starting with SM.",
+ });
+ }
+
+ if (pending.type === "amounts" && !amounts) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "This bank account requires the two microdeposit amounts.",
+ });
+ }
+
+ try {
+ const intent = await verifyIntentMicrodeposits({
+ pending,
+ amounts,
+ descriptorCode,
+ });
+
+ return NextResponse.json({
+ id: paymentMethodId,
+ status: intent.status,
+ });
+ } catch (error) {
+ if (error instanceof DubApiError || error instanceof z.ZodError) {
+ throw error;
+ }
+
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ error instanceof Stripe.errors.StripeError
+ ? error.message
+ : "Failed to verify microdeposits. Please check the values and try again.",
+ });
+ }
+ },
+ {
+ requiredPermissions: ["billing.write"],
+ },
+);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/program-payout-methods.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/program-payout-methods.tsx
index 9027b87b4a..f500cf61b6 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/program-payout-methods.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/payouts/program-payout-methods.tsx
@@ -69,13 +69,17 @@ export function ProgramPayoutMethods() {
details = `Account ending in ••••${pm.card.last4}`;
} else if (pm.us_bank_account) {
title = "ACH";
- details = `Account ending in ••••${pm.us_bank_account.last4}`;
+ details = pm.us_bank_account.bank_name
+ ? `${pm.us_bank_account.bank_name} ••••${pm.us_bank_account.last4}`
+ : `••••${pm.us_bank_account.last4}`;
} else if (pm.acss_debit) {
title = "ACSS Debit";
- details = `Account ending in ••••${pm.acss_debit.last4}`;
+ details = pm.acss_debit.bank_name
+ ? `${pm.acss_debit.bank_name} ••••${pm.acss_debit.last4}`
+ : `••••${pm.acss_debit.last4}`;
} else if (pm.sepa_debit) {
title = "SEPA Debit";
- details = `Account ending in ••••${pm.sepa_debit.last4}`;
+ details = `••••${pm.sepa_debit.last4}`;
} else {
title = paymentMethod.label;
details = `Account ending in ••••${pm[paymentMethod.type]?.last4 || "****"}`;
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-method-types.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-method-types.ts
index 2eb6cd1bfc..226f092fe6 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-method-types.ts
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-method-types.ts
@@ -12,6 +12,17 @@ import {
import { capitalize } from "@dub/utils";
import { Stripe } from "stripe";
+const formatBankAccountDescription = ({
+ bankName,
+ last4,
+}: {
+ bankName?: string | null;
+ last4?: string | null;
+}) => {
+ const masked = `••••${last4 ?? ""}`;
+ return bankName ? `${bankName} ${masked}` : masked;
+};
+
export const PaymentMethodTypesList = (paymentMethod?: Stripe.PaymentMethod) =>
[
{
@@ -35,7 +46,10 @@ export const PaymentMethodTypesList = (paymentMethod?: Stripe.PaymentMethod) =>
title: "ACH",
icon: GreekTemple,
description: paymentMethod?.us_bank_account
- ? `Account ending in ****${paymentMethod.us_bank_account.last4}`
+ ? formatBankAccountDescription({
+ bankName: paymentMethod.us_bank_account.bank_name,
+ last4: paymentMethod.us_bank_account.last4,
+ })
: "Not connected",
},
{
@@ -43,7 +57,10 @@ export const PaymentMethodTypesList = (paymentMethod?: Stripe.PaymentMethod) =>
title: "ACSS Debit",
icon: GreekTemple,
description: paymentMethod?.acss_debit
- ? `Account ending in ****${paymentMethod.acss_debit.last4}`
+ ? formatBankAccountDescription({
+ bankName: paymentMethod.acss_debit.bank_name,
+ last4: paymentMethod.acss_debit.last4,
+ })
: "Not connected",
},
{
@@ -51,7 +68,9 @@ export const PaymentMethodTypesList = (paymentMethod?: Stripe.PaymentMethod) =>
title: "SEPA Debit",
icon: GreekTemple,
description: paymentMethod?.sepa_debit
- ? `Account ending in ****${paymentMethod.sepa_debit.last4}`
+ ? formatBankAccountDescription({
+ last4: paymentMethod.sepa_debit.last4,
+ })
: "Not connected",
},
{
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-methods.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-methods.tsx
index f31b3b5c75..cb23264d12 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-methods.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/settings/billing/payment-methods.tsx
@@ -2,11 +2,16 @@
import { clientAccessCheck } from "@/lib/client-access-check";
import { DIRECT_DEBIT_PAYMENT_METHOD_TYPES } from "@/lib/constants/payouts";
+import type {
+ PaymentMethodMicrodeposit,
+ WorkspacePaymentMethod,
+} from "@/lib/stripe/microdeposit-types";
import { mutatePrefix } from "@/lib/swr/mutate";
import usePaymentMethods from "@/lib/swr/use-payment-methods";
import useWorkspace from "@/lib/swr/use-workspace";
import { useAddPaymentMethodModal } from "@/ui/modals/add-payment-method-modal";
import { useConfirmModal } from "@/ui/modals/confirm-modal";
+import { useVerifyMicrodepositsModal } from "@/ui/modals/verify-microdeposits-modal";
import { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";
import { ThreeDots } from "@/ui/shared/icons";
import {
@@ -143,7 +148,7 @@ const PaymentMethodCard = ({
isDefault = false,
}: {
type: Stripe.PaymentMethod.Type;
- paymentMethod?: Stripe.PaymentMethod;
+ paymentMethod?: WorkspacePaymentMethod;
forPayouts?: boolean;
isDefault?: boolean;
}) => {
@@ -156,6 +161,8 @@ const PaymentMethodCard = ({
description,
} = result.find((method) => method.type === type) || result[0];
+ const microdeposit = paymentMethod?.microdeposit ?? null;
+
return (
<>
<RecommendedForPayoutsWrapper recommended={forPayouts}>
@@ -177,6 +184,16 @@ const PaymentMethodCard = ({
Default
</Badge>
)}
+ {forPayouts &&
+ (microdeposit ? (
+ <Badge variant="amber" className="text-[0.625rem]">
+ Unverified
+ </Badge>
+ ) : (
+ <Badge variant="green" className="text-[0.625rem]">
+ Verified
+ </Badge>
+ ))}
</div>
<p className="text-sm text-neutral-500">{description}</p>
</div>
@@ -186,7 +203,8 @@ const PaymentMethodCard = ({
paymentMethod={paymentMethod}
title={title}
isDefault={isDefault}
- canSetDefault={!forPayouts}
+ canSetDefault={!forPayouts && !microdeposit}
+ microdeposit={microdeposit}
/>
)}
</div>
@@ -200,11 +218,13 @@ const PaymentMethodActions = ({
title,
isDefault,
canSetDefault,
+ microdeposit,
}: {
- paymentMethod: Stripe.PaymentMethod;
+ paymentMethod: WorkspacePaymentMethod;
title: string;
isDefault: boolean;
canSetDefault: boolean;
+ microdeposit: PaymentMethodMicrodeposit | null;
}) => {
const [openPopover, setOpenPopover] = useState(false);
const [isSettingDefault, setIsSettingDefault] = useState(false);
@@ -216,6 +236,12 @@ const PaymentMethodActions = ({
customPermissionDescription: "manage payment methods",
}).error;
+ const { setShowVerifyMicrodepositsModal, verifyMicrodepositsModal } =
+ useVerifyMicrodepositsModal({
+ paymentMethodId: paymentMethod.id,
+ microdeposit: microdeposit ?? { type: "amounts", arrivalDate: null },
+ });
+
const setDefaultPaymentMethod = async () => {
setIsSettingDefault(true);
@@ -277,55 +303,67 @@ const PaymentMethodActions = ({
return (
<>
{confirmModal}
- <Popover
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- align="end"
- content={
- <Command tabIndex={0} loop className="focus:outline-none">
- <Command.List className="flex w-screen flex-col gap-1 p-1.5 text-sm focus-visible:outline-none sm:w-auto sm:min-w-[160px]">
- {canSetDefault && !isDefault && (
+ {microdeposit && verifyMicrodepositsModal}
+ <div className="flex items-center gap-2">
+ {microdeposit && (
+ <Button
+ type="button"
+ className="h-9 w-fit"
+ text="Verify"
+ onClick={() => setShowVerifyMicrodepositsModal(true)}
+ disabledTooltip={billingWriteError}
+ />
+ )}
+ <Popover
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ align="end"
+ content={
+ <Command tabIndex={0} loop className="focus:outline-none">
+ <Command.List className="flex w-screen flex-col gap-1 p-1.5 text-sm focus-visible:outline-none sm:w-auto sm:min-w-[160px]">
+ {canSetDefault && !isDefault && (
+ <MenuItem
+ as={Command.Item}
+ icon={isSettingDefault ? LoadingSpinner : Flag2}
+ onSelect={() => {
+ setDefaultPaymentMethod();
+ }}
+ loading={isSettingDefault}
+ disabledTooltip={billingWriteError}
+ >
+ Set as default
+ </MenuItem>
+ )}
<MenuItem
as={Command.Item}
- icon={isSettingDefault ? LoadingSpinner : Flag2}
+ icon={Trash}
+ variant="danger"
onSelect={() => {
- setDefaultPaymentMethod();
+ setOpenPopover(false);
+ setShowConfirmModal(true);
}}
- loading={isSettingDefault}
- disabledTooltip={billingWriteError}
+ disabledTooltip={
+ isDefault
+ ? "Default payment method cannot be removed. Set a new default payment method first before removing."
+ : billingWriteError
+ }
>
- Set as default
+ Remove
</MenuItem>
- )}
- <MenuItem
- as={Command.Item}
- icon={Trash}
- variant="danger"
- onSelect={() => {
- setOpenPopover(false);
- setShowConfirmModal(true);
- }}
- disabledTooltip={
- isDefault
- ? "Default payment method cannot be removed. Set a new default payment method first before removing."
- : billingWriteError
- }
- >
- Remove
- </MenuItem>
- </Command.List>
- </Command>
- }
- >
- <Button
- type="button"
- variant="secondary"
- className="h-9 w-fit px-1.5"
- aria-label="Open payment method actions"
- icon={<ThreeDots className="size-3.5 shrink-0" />}
- onClick={() => setOpenPopover(!openPopover)}
- />
- </Popover>
+ </Command.List>
+ </Command>
+ }
+ >
+ <Button
+ type="button"
+ variant="secondary"
+ className="h-9 w-fit px-1.5"
+ aria-label="Open payment method actions"
+ icon={<ThreeDots className="size-3.5 shrink-0" />}
+ onClick={() => setOpenPopover(!openPopover)}
+ />
+ </Popover>
+ </div>
</>
);
};
diff --git a/apps/web/lib/api-logs/constants.ts b/apps/web/lib/api-logs/constants.ts
index 9e616eefb7..80834cbfff 100644
--- a/apps/web/lib/api-logs/constants.ts
+++ b/apps/web/lib/api-logs/constants.ts
@@ -131,6 +131,7 @@ export const ROUTE_PATTERNS = [
"/workspaces/:id/billing/activate-paid-plan",
"/workspaces/:id/billing/cancel",
"/workspaces/:id/billing/manage",
+ "/workspaces/:id/billing/payment-methods/verify-microdeposits",
"/workspaces/:id/billing/payment-methods",
"/workspaces/:id/billing/retry-payment",
"/workspaces/:id/billing/upgrade",
diff --git a/apps/web/lib/stripe/microdeposit-types.ts b/apps/web/lib/stripe/microdeposit-types.ts
new file mode 100644
index 0000000000..1c31170b84
--- /dev/null
+++ b/apps/web/lib/stripe/microdeposit-types.ts
@@ -0,0 +1,12 @@
+import Stripe from "stripe";
+
+export type MicrodepositType = "amounts" | "descriptor_code";
+
+export type PaymentMethodMicrodeposit = {
+ type: MicrodepositType;
+ arrivalDate: number | null;
+};
+
+export type WorkspacePaymentMethod = Stripe.PaymentMethod & {
+ microdeposit: PaymentMethodMicrodeposit | null;
+};
diff --git a/apps/web/lib/stripe/microdeposits.ts b/apps/web/lib/stripe/microdeposits.ts
new file mode 100644
index 0000000000..a67708e341
--- /dev/null
+++ b/apps/web/lib/stripe/microdeposits.ts
@@ -0,0 +1,190 @@
+import { stripe } from "@/lib/stripe";
+import type {
+ MicrodepositType,
+ PaymentMethodMicrodeposit,
+ WorkspacePaymentMethod,
+} from "@/lib/stripe/microdeposit-types";
+import Stripe from "stripe";
+
+export type {
+ MicrodepositType,
+ PaymentMethodMicrodeposit,
+ WorkspacePaymentMethod,
+};
+
+export type PendingMicrodeposit = PaymentMethodMicrodeposit & {
+ intentId: string;
+ intentObject: "setup_intent" | "payment_intent";
+ paymentMethodId: string;
+ paymentMethod: Stripe.PaymentMethod | null;
+};
+
+type VerifyMicrodepositsParams = {
+ amounts?: number[];
+ descriptor_code?: string;
+};
+
+type VerifyMicrodepositsResource = {
+ verifyMicrodeposits: (
+ id: string,
+ params: VerifyMicrodepositsParams,
+ ) => Promise<Stripe.PaymentIntent | Stripe.SetupIntent>;
+};
+
+function getPaymentMethodFromIntent(
+ paymentMethod:
+ | Stripe.SetupIntent["payment_method"]
+ | Stripe.PaymentIntent["payment_method"],
+): { id: string; paymentMethod: Stripe.PaymentMethod | null } | null {
+ if (!paymentMethod) {
+ return null;
+ }
+
+ if (typeof paymentMethod === "string") {
+ return { id: paymentMethod, paymentMethod: null };
+ }
+
+ if ("deleted" in paymentMethod && paymentMethod.deleted) {
+ return null;
+ }
+
+ return {
+ id: paymentMethod.id,
+ paymentMethod,
+ };
+}
+
+function getPendingMicrodepositFromIntent(
+ intent: Stripe.SetupIntent | Stripe.PaymentIntent,
+): PendingMicrodeposit | null {
+ if (
+ intent.status !== "requires_action" ||
+ intent.next_action?.type !== "verify_with_microdeposits"
+ ) {
+ return null;
+ }
+
+ const paymentMethod = getPaymentMethodFromIntent(intent.payment_method);
+
+ if (!paymentMethod) {
+ return null;
+ }
+
+ const details = intent.next_action.verify_with_microdeposits;
+ const type: MicrodepositType =
+ details?.microdeposit_type === "descriptor_code"
+ ? "descriptor_code"
+ : "amounts";
+
+ return {
+ type,
+ arrivalDate: details?.arrival_date ?? null,
+ intentId: intent.id,
+ intentObject:
+ intent.object === "setup_intent" ? "setup_intent" : "payment_intent",
+ paymentMethodId: paymentMethod.id,
+ paymentMethod: paymentMethod.paymentMethod,
+ };
+}
+
+export async function listPendingMicrodeposits(
+ stripeId: string,
+): Promise<PendingMicrodeposit[]> {
+ const [setupIntents, paymentIntents] = await Promise.all([
+ stripe.setupIntents.list({
+ customer: stripeId,
+ limit: 100,
+ expand: ["data.payment_method"],
+ }),
+ stripe.paymentIntents.list({
+ customer: stripeId,
+ limit: 100,
+ expand: ["data.payment_method"],
+ }),
+ ]);
+
+ return [...setupIntents.data, ...paymentIntents.data]
+ .map(getPendingMicrodepositFromIntent)
+ .filter((pending): pending is PendingMicrodeposit => pending !== null);
+}
+
+export async function findPendingMicrodeposit({
+ stripeId,
+ paymentMethodId,
+}: {
+ stripeId: string;
+ paymentMethodId: string;
+}): Promise<PendingMicrodeposit | null> {
+ const pending = await listPendingMicrodeposits(stripeId);
+
+ return (
+ pending.find((item) => item.paymentMethodId === paymentMethodId) ?? null
+ );
+}
+
+export function withMicrodepositStatus({
+ paymentMethods,
+ pendingMicrodeposits,
+}: {
+ paymentMethods: Stripe.PaymentMethod[];
+ pendingMicrodeposits: PendingMicrodeposit[];
+}): WorkspacePaymentMethod[] {
+ const pendingByPaymentMethodId = new Map(
+ pendingMicrodeposits.map((pending) => [pending.paymentMethodId, pending]),
+ );
+
+ const methods: WorkspacePaymentMethod[] = paymentMethods.map(
+ (paymentMethod) => {
+ const pending = pendingByPaymentMethodId.get(paymentMethod.id);
+
+ return {
+ ...paymentMethod,
+ microdeposit: pending
+ ? { type: pending.type, arrivalDate: pending.arrivalDate }
+ : null,
+ };
+ },
+ );
+
+ const listedIds = new Set(methods.map((method) => method.id));
+
+ for (const pending of pendingMicrodeposits) {
+ if (!pending.paymentMethod || listedIds.has(pending.paymentMethodId)) {
+ continue;
+ }
+
+ methods.push({
+ ...pending.paymentMethod,
+ microdeposit: {
+ type: pending.type,
+ arrivalDate: pending.arrivalDate,
+ },
+ });
+ listedIds.add(pending.paymentMethodId);
+ }
+
+ return methods;
+}
+
+export async function verifyIntentMicrodeposits({
+ pending,
+ amounts,
+ descriptorCode,
+}: {
+ pending: PendingMicrodeposit;
+ amounts?: [number, number];
+ descriptorCode?: string;
+}) {
+ const params: VerifyMicrodepositsParams = descriptorCode
+ ? { descriptor_code: descriptorCode.toUpperCase() }
+ : { amounts };
+
+ const resource =
+ pending.intentObject === "setup_intent"
+ ? stripe.setupIntents
+ : stripe.paymentIntents;
+
+ return (
+ resource as unknown as VerifyMicrodepositsResource
+ ).verifyMicrodeposits(pending.intentId, params);
+}
diff --git a/apps/web/lib/swr/use-payment-methods.ts b/apps/web/lib/swr/use-payment-methods.ts
index 2f9fc1099c..a5e660bdf0 100644
--- a/apps/web/lib/swr/use-payment-methods.ts
+++ b/apps/web/lib/swr/use-payment-methods.ts
@@ -1,10 +1,12 @@
+import type { WorkspacePaymentMethod } from "@/lib/stripe/microdeposit-types";
import { fetcher } from "@dub/utils";
-import Stripe from "stripe";
import useSWR from "swr";
import useWorkspace from "./use-workspace";
+export type { WorkspacePaymentMethod };
+
type PaymentMethodsResponse = {
- paymentMethods: Stripe.PaymentMethod[];
+ paymentMethods: WorkspacePaymentMethod[];
defaultPaymentMethodId: string | null;
};
diff --git a/apps/web/ui/modals/verify-microdeposits-modal.tsx b/apps/web/ui/modals/verify-microdeposits-modal.tsx
new file mode 100644
index 0000000000..e5843a5039
--- /dev/null
+++ b/apps/web/ui/modals/verify-microdeposits-modal.tsx
@@ -0,0 +1,277 @@
+"use client";
+
+import { clientAccessCheck } from "@/lib/client-access-check";
+import type { PaymentMethodMicrodeposit } from "@/lib/stripe/microdeposit-types";
+import { mutatePrefix } from "@/lib/swr/mutate";
+import useWorkspace from "@/lib/swr/use-workspace";
+import { Button, Input, Label, Modal } from "@dub/ui";
+import { formatDate } from "@dub/utils";
+import { Dispatch, SetStateAction, useState } from "react";
+import { toast } from "sonner";
+
+const DESCRIPTOR_PREFIX = "SM";
+
+function parseDollarAmountToCents(value: string): number | null {
+ const parsed = Number.parseFloat(value.replace(/[^0-9.]/g, ""));
+
+ if (!Number.isFinite(parsed)) {
+ return null;
+ }
+
+ return Math.round(parsed * 100);
+}
+
+// Users only type the 4-character suffix; SM is shown as a prefix and prepended on submit.
+// If they paste a full code (SM11AA / SM-11AA), strip the prefix so we don't double it.
+function normalizeDescriptorSuffix(value: string): string {
+ const alphanumeric = value.replace(/[^0-9a-z]/gi, "").toUpperCase();
+ const suffix = alphanumeric.startsWith(DESCRIPTOR_PREFIX)
+ ? alphanumeric.slice(DESCRIPTOR_PREFIX.length)
+ : alphanumeric;
+
+ return suffix.slice(0, 4);
+}
+
+function VerifyMicrodepositsModal({
+ showModal,
+ setShowModal,
+ paymentMethodId,
+ microdeposit,
+}: {
+ showModal: boolean;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+ paymentMethodId: string;
+ microdeposit: PaymentMethodMicrodeposit;
+}) {
+ const { slug, role } = useWorkspace();
+ const [amount1, setAmount1] = useState("");
+ const [amount2, setAmount2] = useState("");
+ const [descriptorCode, setDescriptorCode] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const billingWriteError = clientAccessCheck({
+ action: "billing.write",
+ role,
+ customPermissionDescription: "verify payment methods",
+ }).error;
+
+ const isDescriptorCode = microdeposit.type === "descriptor_code";
+ const arrivalDate = microdeposit.arrivalDate
+ ? formatDate(new Date(microdeposit.arrivalDate * 1000), {
+ month: "short",
+ day: "numeric",
+ })
+ : null;
+
+ const resetForm = () => {
+ setAmount1("");
+ setAmount2("");
+ setDescriptorCode("");
+ };
+
+ const handleSubmit = async () => {
+ if (isSubmitting || billingWriteError) {
+ return;
+ }
+
+ let body: {
+ paymentMethodId: string;
+ amounts?: [number, number];
+ descriptorCode?: string;
+ } = { paymentMethodId };
+
+ if (isDescriptorCode) {
+ const suffix = normalizeDescriptorSuffix(descriptorCode);
+
+ if (!/^[0-9A-Z]{4}$/.test(suffix)) {
+ toast.error(
+ "Enter the 6-digit code from the statement descriptor of this deposit.",
+ );
+ return;
+ }
+
+ body.descriptorCode = `${DESCRIPTOR_PREFIX}${suffix}`;
+ } else {
+ const first = parseDollarAmountToCents(amount1);
+ const second = parseDollarAmountToCents(amount2);
+
+ if (
+ first === null ||
+ second === null ||
+ first < 1 ||
+ first > 99 ||
+ second < 1 ||
+ second > 99
+ ) {
+ toast.error(
+ "Enter both deposit amounts in dollars, e.g. 0.32 and 0.45.",
+ );
+ return;
+ }
+
+ body.amounts = [first, second];
+ }
+
+ setIsSubmitting(true);
+
+ try {
+ const response = await fetch(
+ `/api/workspaces/${slug}/billing/payment-methods/verify-microdeposits`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(body),
+ },
+ );
+
+ if (!response.ok) {
+ const { error } = await response.json();
+ toast.error(error.message);
+ return;
+ }
+
+ await mutatePrefix(`/api/workspaces/${slug}/billing/payment-methods`);
+ toast.success("Bank account verified!");
+ resetForm();
+ setShowModal(false);
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <Modal
+ showModal={showModal}
+ setShowModal={setShowModal}
+ className="max-w-md"
+ >
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ handleSubmit();
+ }}
+ >
+ <div className="divide-y divide-neutral-200">
+ <div className="p-4 sm:px-6">
+ <h3 className="text-content-emphasis text-lg font-medium">
+ Verify bank account
+ </h3>
+ <p className="mt-1 text-sm text-neutral-600">
+ {isDescriptorCode
+ ? "Stripe sent a small deposit to this bank account. To verify this account, please confirm the 6-digit code in the statement descriptor of this deposit."
+ : arrivalDate
+ ? `Stripe sent two small deposits to this bank account. Enter the amounts below to verify it. They typically appear by ${arrivalDate}.`
+ : "Stripe sent two small deposits to this bank account. Enter the amounts below to verify it. They typically appear within 1–2 business days."}
+ </p>
+ </div>
+ <div className="flex flex-col gap-4 bg-neutral-50 px-4 py-6 sm:px-6">
+ {isDescriptorCode ? (
+ <div className="grid gap-1.5">
+ <Label htmlFor="descriptor-code">Descriptor code</Label>
+ <div className="flex w-full max-w-md items-center rounded-md border border-neutral-300 bg-white px-3 focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500">
+ <span className="text-sm text-neutral-500">
+ {DESCRIPTOR_PREFIX}
+ </span>
+ <input
+ id="descriptor-code"
+ value={descriptorCode}
+ onChange={(e) =>
+ setDescriptorCode(
+ normalizeDescriptorSuffix(e.target.value),
+ )
+ }
+ placeholder="XXXX"
+ autoComplete="off"
+ autoCapitalize="off"
+ autoCorrect="off"
+ spellCheck={false}
+ className="min-w-0 flex-1 border-0 bg-transparent py-2 uppercase text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0 sm:text-sm"
+ />
+ </div>
+ </div>
+ ) : (
+ <div className="grid grid-cols-2 gap-3">
+ <div className="grid gap-1.5">
+ <Label htmlFor="microdeposit-amount-1">First amount</Label>
+ <div className="relative">
+ <span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-neutral-500">
+ $
+ </span>
+ <Input
+ id="microdeposit-amount-1"
+ inputMode="decimal"
+ placeholder="0.32"
+ value={amount1}
+ onChange={(e) => setAmount1(e.target.value)}
+ autoComplete="off"
+ className="max-w-none pl-7"
+ />
+ </div>
+ </div>
+ <div className="grid gap-1.5">
+ <Label htmlFor="microdeposit-amount-2">Second amount</Label>
+ <div className="relative">
+ <span className="pointer-events-none absolute inset-y-0 left-3 flex items-center text-sm text-neutral-500">
+ $
+ </span>
+ <Input
+ id="microdeposit-amount-2"
+ inputMode="decimal"
+ placeholder="0.45"
+ value={amount2}
+ onChange={(e) => setAmount2(e.target.value)}
+ autoComplete="off"
+ className="max-w-none pl-7"
+ />
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center justify-end gap-2 border-t border-neutral-200 px-4 py-4 sm:px-6">
+ <Button
+ type="button"
+ variant="secondary"
+ className="h-8 w-fit"
+ text="Cancel"
+ disabled={isSubmitting}
+ onClick={() => setShowModal(false)}
+ />
+ <Button
+ type="submit"
+ className="h-8 w-fit"
+ text="Verify"
+ loading={isSubmitting}
+ disabledTooltip={billingWriteError}
+ />
+ </div>
+ </form>
+ </Modal>
+ );
+}
+
+export function useVerifyMicrodepositsModal({
+ paymentMethodId,
+ microdeposit,
+}: {
+ paymentMethodId: string;
+ microdeposit: PaymentMethodMicrodeposit;
+}) {
+ const [showVerifyMicrodepositsModal, setShowVerifyMicrodepositsModal] =
+ useState(false);
+
+ return {
+ setShowVerifyMicrodepositsModal,
+ verifyMicrodepositsModal: (
+ <VerifyMicrodepositsModal
+ showModal={showVerifyMicrodepositsModal}
+ setShowModal={setShowVerifyMicrodepositsModal}
+ paymentMethodId={paymentMethodId}
+ microdeposit={microdeposit}
+ />
+ ),
+ };
+}
diff --git a/packages/ui/src/badge.tsx b/packages/ui/src/badge.tsx
index c88d6cb3ef..cfca9751fc 100644
--- a/packages/ui/src/badge.tsx
+++ b/packages/ui/src/badge.tsx
@@ -9,13 +9,13 @@ const badgeVariants = cva(
default: "border-neutral-400 text-neutral-500",
violet: "border-violet-600 bg-violet-600 text-white",
blue: "border-blue-500 bg-blue-500 text-white",
- green: "border-green-100 bg-green-100 text-green-900",
+ green: "border-green-200 bg-green-100 text-green-900",
red: "border-red-100 bg-red-100 text-red-800",
sky: "border-sky-900 bg-sky-900 text-white",
black: "border-black bg-black text-white",
gray: "border-neutral-200 bg-neutral-100 text-neutral-800",
neutral: "border-neutral-400 text-neutral-500",
- amber: "border-amber-800 bg-amber-800 text-white",
+ amber: "border-amber-200 bg-amber-100 text-amber-800",
blueGradient:
"bg-gradient-to-r from-blue-100 via-blue-100/50 to-blue-100 border border-blue-200 text-blue-900",
rainbow: