The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Improve payment methods (POST, PATCH, DELETE) (#4090)
Steven Teyb33ae48cf675
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.tsindex a0c84bce9a..ac9033da7f 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@@ -16,32 +16,81 @@ const addPaymentMethodSchema = z.object({method: z.enum(PAYMENT_METHOD_TYPES as [string, ...string[]]).optional(),});+const deletePaymentMethodSchema = z.object({+ paymentMethodId: z.string().min(1),+});++const updatePaymentMethodSchema = z.object({+ paymentMethodId: z.string().min(1),+});++async function getWorkspacePaymentMethod({+ stripeId,+ paymentMethodId,+}: {+ stripeId: string;+ paymentMethodId: string;+}) {+ const paymentMethod = await stripe.paymentMethods.retrieve(paymentMethodId);++ if (paymentMethod.customer !== stripeId) {+ throw new DubApiError({+ code: "not_found",+ message: "Payment method not found.",+ });+ }++ return paymentMethod;+}+// GET /api/workspaces/[idOrSlug]/billing/payment-methods - get all payment methodsexport const GET = withWorkspace(async ({ workspace }) => {if (!workspace.stripeId) {- return NextResponse.json([]);+ return NextResponse.json({+ paymentMethods: [],+ defaultPaymentMethodId: null,+ });}try {- const paymentMethods = await stripe.paymentMethods.list({- customer: workspace.stripeId,- });+ const [paymentMethods, customer] = await Promise.all([+ stripe.paymentMethods.list({+ customer: workspace.stripeId,+ }),+ stripe.customers.retrieve(workspace.stripeId),+ ]);++ const defaultPaymentMethod =+ customer.deleted !== true+ ? customer.invoice_settings?.default_payment_method+ : null;++ const defaultPaymentMethodId =+ typeof defaultPaymentMethod === "string"+ ? defaultPaymentMethod+ : defaultPaymentMethod?.id ?? null;// reorder to put direct debit firstconst directDebit = paymentMethods.data.find((method) =>DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(method.type),);- return NextResponse.json([- ...(directDebit ? [directDebit] : []),- ...paymentMethods.data.filter(- (method) => method.id !== directDebit?.id,- ),- ]);+ return NextResponse.json({+ paymentMethods: [+ ...(directDebit ? [directDebit] : []),+ ...paymentMethods.data.filter(+ (method) => method.id !== directDebit?.id,+ ),+ ],+ defaultPaymentMethodId,+ });} catch (error) {console.error(error);- return NextResponse.json([]);+ return NextResponse.json({+ paymentMethods: [],+ defaultPaymentMethodId: null,+ });}},{@@ -106,3 +155,71 @@ export const POST = withWorkspace(requiredPermissions: ["billing.write"],},);++// PATCH /api/workspaces/[idOrSlug]/billing/payment-methods - set default payment method+export const PATCH = withWorkspace(+ async ({ workspace, req }) => {+ if (!workspace.stripeId) {+ throw new DubApiError({+ code: "bad_request",+ message: "Workspace does not have a Stripe ID.",+ });+ }++ const { paymentMethodId } = updatePaymentMethodSchema.parse(+ await parseRequestBody(req),+ );++ const paymentMethod = await getWorkspacePaymentMethod({+ stripeId: workspace.stripeId,+ paymentMethodId,+ });++ if (DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(paymentMethod.type)) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "Direct debit payment methods cannot be set as the default billing method.",+ });+ }++ await stripe.customers.update(workspace.stripeId, {+ invoice_settings: {+ default_payment_method: paymentMethodId,+ },+ });++ return NextResponse.json({ id: paymentMethodId });+ },+ {+ requiredPermissions: ["billing.write"],+ },+);++// DELETE /api/workspaces/[idOrSlug]/billing/payment-methods - remove a payment method+export const DELETE = withWorkspace(+ async ({ workspace, req }) => {+ if (!workspace.stripeId) {+ throw new DubApiError({+ code: "bad_request",+ message: "Workspace does not have a Stripe ID.",+ });+ }++ const { paymentMethodId } = deletePaymentMethodSchema.parse(+ await parseRequestBody(req),+ );++ await getWorkspacePaymentMethod({+ stripeId: workspace.stripeId,+ paymentMethodId,+ });++ await stripe.paymentMethods.detach(paymentMethodId);++ return NextResponse.json({ id: paymentMethodId });+ },+ {+ requiredPermissions: ["billing.write"],+ },+);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.tsxindex 1547978d06..f68b8803c2 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,21 +2,35 @@import { clientAccessCheck } from "@/lib/client-access-check";import { DIRECT_DEBIT_PAYMENT_METHOD_TYPES } from "@/lib/constants/payouts";+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 { AnimatedEmptyState } from "@/ui/shared/animated-empty-state";-import { Badge, Button, CreditCard, GreekTemple, MoneyBill2 } from "@dub/ui";+import { ThreeDots } from "@/ui/shared/icons";+import {+ Badge,+ Button,+ CreditCard,+ GreekTemple,+ MenuItem,+ MoneyBill2,+ Popover,+} from "@dub/ui";+import { LoadingSpinner, Star, Trash } from "@dub/ui/icons";import { cn } from "@dub/utils";+import { Command } from "cmdk";import Link from "next/link";import { useRouter } from "next/navigation";import { useState } from "react";+import { toast } from "sonner";import { Stripe } from "stripe";import { PaymentMethodTypesList } from "./payment-method-types";export default function PaymentMethods() {const router = useRouter();- const { paymentMethods } = usePaymentMethods();+ const { paymentMethods, defaultPaymentMethodId } = usePaymentMethods();const [isLoading, setIsLoading] = useState(false);const { slug, stripeId, plan, role } = useWorkspace();@@ -78,6 +92,7 @@ export default function PaymentMethods() {key={paymentMethod.id}type={paymentMethod.type}paymentMethod={paymentMethod}+ isDefault={paymentMethod.id === defaultPaymentMethodId}/>))) : (@@ -122,10 +137,12 @@ const PaymentMethodCard = ({type,paymentMethod,forPayouts = false,+ isDefault = false,}: {type: Stripe.PaymentMethod.Type;paymentMethod?: Stripe.PaymentMethod;forPayouts?: boolean;+ isDefault?: boolean;}) => {const result = PaymentMethodTypesList(paymentMethod);@@ -152,23 +169,163 @@ const PaymentMethodCard = ({<div><div className="flex items-center gap-2"><p className="font-medium text-neutral-900">{title}</p>- {paymentMethod &&- (DIRECT_DEBIT_PAYMENT_METHOD_TYPES.includes(type) ||- paymentMethod.link?.email) && (- <Badge className="border-transparent bg-green-200 text-[0.625rem] text-green-900">- Connected- </Badge>- )}+ {isDefault && (+ <Badge className="border-transparent bg-blue-100 text-[0.625rem] text-blue-700">+ Default+ </Badge>+ )}</div><p className="text-sm text-neutral-500">{description}</p></div></div>+ {paymentMethod && (+ <PaymentMethodActions+ paymentMethod={paymentMethod}+ title={title}+ isDefault={isDefault}+ canSetDefault={!forPayouts}+ />+ )}</div></RecommendedForPayoutsWrapper></>);};+const PaymentMethodActions = ({+ paymentMethod,+ title,+ isDefault,+ canSetDefault,+}: {+ paymentMethod: Stripe.PaymentMethod;+ title: string;+ isDefault: boolean;+ canSetDefault: boolean;+}) => {+ const [openPopover, setOpenPopover] = useState(false);+ const [isSettingDefault, setIsSettingDefault] = useState(false);+ const { slug, role } = useWorkspace();++ const billingWriteError = clientAccessCheck({+ action: "billing.write",+ role,+ customPermissionDescription: "manage payment methods",+ }).error;++ const setDefaultPaymentMethod = async () => {+ setIsSettingDefault(true);++ try {+ const response = await fetch(+ `/api/workspaces/${slug}/billing/payment-methods`,+ {+ method: "PATCH",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ paymentMethodId: paymentMethod.id }),+ },+ );++ if (!response.ok) {+ const { error } = await response.json();+ toast.error(error.message);+ return;+ }++ await mutatePrefix(`/api/workspaces/${slug}/billing/payment-methods`);+ toast.success("Default payment method updated!");+ } finally {+ setIsSettingDefault(false);+ }+ };++ const { setShowConfirmModal, confirmModal } = useConfirmModal({+ title: "Remove payment method",+ description: isDefault+ ? `Are you sure you want to remove your default ${title} payment method? You will need to add another payment method to continue billing.`+ : `Are you sure you want to remove this ${title} payment method? This action cannot be undone.`,+ confirmText: "Remove",+ confirmVariant: "danger",+ onConfirm: async () => {+ const response = await fetch(+ `/api/workspaces/${slug}/billing/payment-methods`,+ {+ method: "DELETE",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ paymentMethodId: paymentMethod.id }),+ },+ );++ if (!response.ok) {+ const { error } = await response.json();+ toast.error(error.message);+ return;+ }++ await mutatePrefix(`/api/workspaces/${slug}/billing/payment-methods`);+ toast.success("Payment method removed successfully!");+ },+ });++ 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 && (+ <MenuItem+ as={Command.Item}+ icon={isSettingDefault ? LoadingSpinner : Star}+ onSelect={() => {+ setDefaultPaymentMethod();+ }}+ loading={isSettingDefault}+ disabledTooltip={billingWriteError}+ >+ Set as default+ </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"+ icon={<ThreeDots className="size-3.5 shrink-0" />}+ onClick={() => setOpenPopover(!openPopover)}+ />+ </Popover>+ </>+ );+};+const NoPartnerPaymentMethods = () => {const { stripeId } = useWorkspace();const { setShowAddPaymentMethodModal, AddPaymentMethodModal } =diff --git a/apps/web/lib/swr/use-payment-methods.ts b/apps/web/lib/swr/use-payment-methods.tsindex bc080473b5..2f9fc1099c 100644--- a/apps/web/lib/swr/use-payment-methods.ts+++ b/apps/web/lib/swr/use-payment-methods.ts@@ -3,23 +3,28 @@ import Stripe from "stripe";import useSWR from "swr";import useWorkspace from "./use-workspace";+type PaymentMethodsResponse = {+ paymentMethods: Stripe.PaymentMethod[];+ defaultPaymentMethodId: string | null;+};+// Returns the Stripe payment methods for the businessexport default function usePaymentMethods({enabled = true,}: { enabled?: boolean } = {}) {const { slug } = useWorkspace();- const {- data: paymentMethods,- isLoading,- error,- } = useSWR<Stripe.PaymentMethod[]>(+ const { data, isLoading, error } = useSWR<PaymentMethodsResponse>(enabled && slug && `/api/workspaces/${slug}/billing/payment-methods`,fetcher,+ {+ keepPreviousData: true,+ },);return {- paymentMethods,+ paymentMethods: data?.paymentMethods,+ defaultPaymentMethodId: data?.defaultPaymentMethodId ?? null,error,loading: isLoading,};diff --git a/packages/ui/src/menu-item.tsx b/packages/ui/src/menu-item.tsxindex 712bebc73a..cc922ae3f0 100644--- a/packages/ui/src/menu-item.tsx+++ b/packages/ui/src/menu-item.tsx@@ -7,14 +7,14 @@ import {PropsWithChildren,ReactNode,} from "react";-import { Icon } from "./icons";+import { Icon, LoadingSpinner } from "./icons";import { DynamicTooltipWrapper } from "./tooltip";export const menuItemVariants = cva(["flex h-9 w-full rounded-md px-2 items-center justify-center gap-2 transition-colors cursor-pointer","whitespace-nowrap text-sm font-medium text-content-default transition-colors",- "disabled:opacity-50 disabled:cursor-default",+ "disabled:opacity-50 disabled:cursor-not-allowed",],{variants: {@@ -23,7 +23,7 @@ export const menuItemVariants = cva(danger: "text-content-error hover:bg-red-50 dark:hover:bg-red-950/20",},disabled: {- true: "opacity-50 cursor-default text-content-disabled hover:bg-bg-default",+ true: "opacity-50 cursor-not-allowed text-content-disabled hover:bg-bg-default",},},},@@ -37,6 +37,7 @@ type MenuItemProps<T extends ElementType> = PropsWithChildren<variant?: "default" | "danger";icon?: Icon | ReactNode;shortcut?: string;+ loading?: boolean;disabledTooltip?: string | ReactNode;};@@ -47,40 +48,52 @@ export function MenuItem<T extends ElementType>({icon: Icon,shortcut,className,+ loading,disabledTooltip,...rest}: MenuItemProps<T>) {const Component = as || "button";+ const isDisabled = !!disabledTooltip || loading;return (<DynamicTooltipWrapper- tooltipProps={{- content: disabledTooltip,- }}+ tooltipProps={+ disabledTooltip+ ? {+ content: disabledTooltip,+ }+ : undefined+ }>- <Component- {...(as === "button" ? { type: "button" } : {})}- className={cn(- menuItemVariants({ variant, disabled: !!disabledTooltip }),- className,- )}- disabled={disabledTooltip ? true : rest.disabled}- {...rest}- >- <div className="flex grow items-center gap-2">- {Icon && (isReactNode(Icon) ? Icon : <Icon className="size-4" />)}- {children}- </div>- {shortcut && (- <kbd- className={cn(- "bg-bg-inverted/5 group-hover:bg-bg-inverted/10 hidden rounded px-2 py-0.5 text-xs font-light transition-all duration-75 md:block",+ <div>+ <Component+ {...(as === "button" ? { type: "button" } : {})}+ className={cn(+ menuItemVariants({ variant, disabled: isDisabled }),+ className,+ )}+ disabled={isDisabled ? true : rest.disabled}+ {...rest}+ >+ <div className="flex grow items-center gap-2">+ {loading ? (+ <LoadingSpinner className="size-4" />+ ) : (+ Icon && (isReactNode(Icon) ? Icon : <Icon className="size-4" />))}- >- {shortcut}- </kbd>- )}- </Component>+ {children}+ </div>+ {shortcut && (+ <kbd+ className={cn(+ "bg-bg-inverted/5 group-hover:bg-bg-inverted/10 hidden rounded px-2 py-0.5 text-xs font-light transition-all duration-75 md:block",+ )}+ >+ {shortcut}+ </kbd>+ )}+ </Component>+ </div></DynamicTooltipWrapper>);}