The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Import customers from Stripe
Steven Teyd0874d96eb42
diff --git a/apps/web/app/(ee)/api/customers/search-stripe/route.ts b/apps/web/app/(ee)/api/customers/search-stripe/route.tsnew file mode 100644index 0000000000..1a0df5c5a7--- /dev/null+++ b/apps/web/app/(ee)/api/customers/search-stripe/route.ts@@ -0,0 +1,65 @@+import { DubApiError } from "@/lib/api/errors";+import { withWorkspace } from "@/lib/auth";+import { stripeAppClient } from "@/lib/stripe";+import { StripeCustomerSchema } from "@/lib/zod/schemas/customers";+import { prisma } from "@dub/prisma";+import { NextResponse } from "next/server";+import * as z from "zod/v4";++const stripe = stripeAppClient({+ ...(process.env.VERCEL_ENV && { mode: "live" }),+});++export const GET = withWorkspace(async ({ workspace, searchParams }) => {+ const { search } = z+ .object({+ search: z.string(),+ })+ .parse(searchParams);++ if (!workspace.stripeConnectId) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "Your workspace isn't connected to Stripe yet. Please install the Stripe integration under /settings/integrations/stripe to proceed.",+ });+ }++ const { data } = await stripe.customers.search(+ {+ query: `email~"${search}"`,+ expand: ["data.subscriptions"],+ },+ {+ stripeAccount: workspace.stripeConnectId,+ },+ );++ const existingCustomers = await prisma.customer.findMany({+ where: {+ stripeCustomerId: {+ in: data.map((customer) => customer.id),+ },+ projectId: workspace.id,+ },+ select: {+ id: true,+ stripeCustomerId: true,+ },+ });++ const stripeCustomers = StripeCustomerSchema.array().parse(+ data.map((customer) => ({+ id: customer.id,+ email: customer.email,+ name: customer.name,+ country: customer.address?.country ?? null,+ subscriptions: customer.subscriptions?.data.length ?? 0,+ dubCustomerId:+ existingCustomers.find((c) => c.stripeCustomerId === customer.id)?.id ??+ null,+ })),+ );++ return NextResponse.json(stripeCustomers);+});diff --git a/apps/web/app/(ee)/api/discount-codes/route.ts b/apps/web/app/(ee)/api/discount-codes/route.tsindex f9f0bd4aad..c917252f98 100644--- a/apps/web/app/(ee)/api/discount-codes/route.ts+++ b/apps/web/app/(ee)/api/discount-codes/route.ts@@ -60,7 +60,7 @@ export const POST = withWorkspace(throw new DubApiError({code: "bad_request",message:- "Your workspace isn't connected to Stripe yet. Please install the Dub Stripe app in settings to create discount codes.",+ "Your workspace isn't connected to Stripe yet. Please install the Stripe integration under /settings/integrations/stripe to proceed.",});}diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex 3abc7daaed..e6e5cc34e0 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -185,3 +185,12 @@ export const CustomerEnrichedSchema = CustomerSchema.extend({autoProvisionEnabledAt: true,}).nullish(),});++export const StripeCustomerSchema = z.object({+ id: z.string(),+ email: z.string().nullable(),+ name: z.string().nullable(),+ country: z.string().nullable(),+ subscriptions: z.number(),+ dubCustomerId: z.string().nullable(),+});diff --git a/apps/web/ui/modals/add-customer-modal.tsx b/apps/web/ui/modals/add-customer-modal.tsxindex 3be4ad3395..c55b74be87 100644--- a/apps/web/ui/modals/add-customer-modal.tsx+++ b/apps/web/ui/modals/add-customer-modal.tsx@@ -1,8 +1,21 @@import useWorkspace from "@/lib/swr/use-workspace";import { CustomerProps } from "@/lib/types";-import { createCustomerBodySchema } from "@/lib/zod/schemas/customers";+import {+ createCustomerBodySchema,+ StripeCustomerSchema,+} from "@/lib/zod/schemas/customers";import { CountryCombobox } from "@/ui/partners/country-combobox";-import { Button, Modal, useMediaQuery } from "@dub/ui";+import {+ AnimatedSizeContainer,+ ArrowUpRight,+ Button,+ Modal,+ StripeIcon,+ Switch,+ useMediaQuery,+} from "@dub/ui";+import { cn } from "@dub/utils";+import { useParams } from "next/navigation";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useForm } from "react-hook-form";import { toast } from "sonner";@@ -17,6 +30,21 @@ interface AddCustomerModalProps {}type FormData = z.infer<typeof createCustomerBodySchema>;+type StripeCustomer = z.infer<typeof StripeCustomerSchema>;++const STRIPE_DASHBOARD_CUSTOMER_URL = "https://dashboard.stripe.com/customers";++function getCustomerInitials(customer: StripeCustomer): string {+ const raw = customer.name || customer.email || customer.id;+ const parts = raw+ .trim()+ .split(/[\s,]+/)+ .filter(Boolean);+ if (parts.length >= 2) {+ return (parts[0][0] + parts[1][0]).toUpperCase();+ }+ return raw.slice(0, 2).toUpperCase();+}export const AddCustomerModal = ({showModal,@@ -26,6 +54,18 @@ export const AddCustomerModal = ({}: AddCustomerModalProps) => {const { id: workspaceId } = useWorkspace();const { isMobile } = useMediaQuery();+ const params = useParams();+ const slug = params?.slug as string | undefined;+ const [hasStripeCustomerId, setHasStripeCustomerId] = useState(false);+ const [showStripeImport, setShowStripeImport] = useState(false);+ const [stripeSearchEmail, setStripeSearchEmail] = useState("");+ const [stripeSearchResults, setStripeSearchResults] = useState<+ StripeCustomer[] | null+ >(null);+ const [stripeSearchLoading, setStripeSearchLoading] = useState(false);+ const [stripeSearchError, setStripeSearchError] = useState<string | null>(+ null,+ );const {register,@@ -49,6 +89,11 @@ export const AddCustomerModal = ({useEffect(() => {// Only reset when the modal opens (transitions from false to true)if (showModal && !prevShowModal.current) {+ setHasStripeCustomerId(false);+ setShowStripeImport(false);+ setStripeSearchEmail("");+ setStripeSearchResults(null);+ setStripeSearchError(null);reset({name: initialName || null,email: null,@@ -60,6 +105,63 @@ export const AddCustomerModal = ({prevShowModal.current = showModal;}, [showModal, initialName, reset]);+ useEffect(() => {+ if (!hasStripeCustomerId) {+ setValue("stripeCustomerId", null);+ }+ }, [hasStripeCustomerId, setValue]);++ const onSearchStripe = useCallback(async () => {+ const email = stripeSearchEmail.trim();+ if (!email) {+ setStripeSearchError("Enter an email to search.");+ return;+ }+ setStripeSearchError(null);+ setStripeSearchResults(null);+ setStripeSearchLoading(true);+ try {+ const response = await fetch(+ `/api/customers/search-stripe?workspaceId=${workspaceId}&search=${encodeURIComponent(email)}`,+ );+ if (!response.ok) {+ const { error } = await response.json();+ throw new Error(error?.message || "Search failed.");+ }+ const data = await response.json();+ setStripeSearchResults(data);+ if (data.length === 0) {+ setStripeSearchError("No Stripe customers found for this email.");+ }+ } catch (err) {+ setStripeSearchError(+ err instanceof Error ? err.message : "Something went wrong.",+ );+ setStripeSearchResults([]);+ } finally {+ setStripeSearchLoading(false);+ }+ }, [workspaceId, stripeSearchEmail]);++ const onSelectStripeCustomer = useCallback(+ (customer: StripeCustomer) => {+ setValue("name", customer.name ?? null, { shouldValidate: true });+ setValue("email", customer.email ?? null, { shouldValidate: true });+ setValue("externalId", customer.email ?? customer.id, {+ shouldValidate: true,+ });+ setValue("stripeCustomerId", customer.id, { shouldValidate: true });+ setValue("country", customer.country ?? "US", { shouldValidate: true });+ setHasStripeCustomerId(true);+ setShowStripeImport(false);+ setStripeSearchResults(null);+ setStripeSearchEmail("");+ setStripeSearchError(null);+ toast.success("Customer details filled from Stripe.");+ },+ [setValue],+ );+const onSubmit = async (data: FormData) => {try {const response = await fetch(@@ -95,8 +197,22 @@ export const AddCustomerModal = ({return (<Modal showModal={showModal} setShowModal={setShowModal}>- <div className="space-y-2 border-b border-neutral-200 px-4 py-4 sm:px-6">+ <div className="flex items-center justify-between gap-2 border-b border-neutral-200 px-4 py-4 sm:px-6"><h3 className="text-lg font-medium">Create new customer</h3>+ {!showStripeImport && (+ <Button+ type="button"+ variant="secondary"+ className="h-9 w-fit"+ icon={<StripeIcon className="size-4" />}+ text="Import from Stripe"+ onClick={() => {+ setShowStripeImport(true);+ setStripeSearchResults(null);+ setStripeSearchError(null);+ }}+ />+ )}</div><div className="bg-neutral-50">@@ -106,111 +222,269 @@ export const AddCustomerModal = ({return handleSubmit(onSubmit)(e);}}>- <div className="flex flex-col gap-4 px-4 py-6 text-left sm:px-6">- <div>- <label className="text-sm font-normal text-neutral-500">- External ID (Required)- </label>- <input- type="text"- required- autoComplete="off"- className="mt-2 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"- placeholder="cus_GWGrkftJdYlZD2mq"- autoFocus={!isMobile}- {...register("externalId", { required: true })}- />- <p className="mt-2 text-xs text-neutral-500">- The customer's unique ID in your database (can also be their- email)- </p>- </div>+ <AnimatedSizeContainer+ height+ className="flex flex-col"+ transition={{ type: "spring", stiffness: 400, damping: 35 }}+ >+ {showStripeImport ? (+ <div className="flex flex-col gap-5 px-4 py-6 sm:px-6">+ <button+ type="button"+ onClick={() => {+ setShowStripeImport(false);+ setStripeSearchResults(null);+ setStripeSearchError(null);+ }}+ className="-ml-1 flex w-fit items-center gap-1 text-xs text-neutral-500 transition-colors hover:text-neutral-700"+ >+ <span className="text-neutral-400">←</span>+ Back to manual input+ </button>+ <div className="flex flex-col gap-3">+ <p className="text-sm text-neutral-500">+ Search by email in your connected Stripe account to pull in+ customer details.+ </p>+ <div className="flex gap-2">+ <input+ type="email"+ autoComplete="off"+ placeholder="[email protected]"+ value={stripeSearchEmail}+ onChange={(e) => setStripeSearchEmail(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ onSearchStripe();+ }+ }}+ className="flex-1 rounded-lg border border-neutral-200 bg-white px-3 py-2.5 text-sm text-neutral-900 placeholder-neutral-400 shadow-sm transition-colors focus:border-neutral-400 focus:outline-none focus:ring-2 focus:ring-neutral-200"+ />+ <Button+ type="button"+ text="Search"+ className="h-10 w-fit"+ loading={stripeSearchLoading}+ disabled={!stripeSearchEmail.trim()}+ onClick={onSearchStripe}+ />+ </div>+ {stripeSearchError && (+ <p className="ml-1 text-xs text-red-600">+ {stripeSearchError}+ </p>+ )}+ </div>+ {stripeSearchResults && stripeSearchResults.length > 0 && (+ <div className="overflow-hidden rounded-lg border border-neutral-200 bg-white shadow-sm">+ <div className="border-b border-neutral-100 bg-neutral-50/80 px-3 py-2">+ <p className="text-xs font-medium text-neutral-500">+ Search results+ </p>+ </div>+ <ul className="max-h-52 overflow-y-auto p-1.5">+ {stripeSearchResults.map((customer) => {+ const displayName =+ customer.name || customer.email || customer.id;+ const initials = getCustomerInitials(customer);+ const stripeUrl = `${STRIPE_DASHBOARD_CUSTOMER_URL}/${customer.id}`;- <div>- <label className="text-sm font-normal text-neutral-500">- Name- </label>- <input- type="text"- autoComplete="off"- className="mt-2 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"- placeholder="John Doe"- {...register("name", {- setValueAs: (value) => (value === "" ? null : value),- })}- />- </div>+ return (+ <li key={customer.id}>+ <button+ type="button"+ disabled={!!customer.dubCustomerId}+ onClick={() => onSelectStripeCustomer(customer)}+ className={cn(+ "flex w-full items-center gap-3 rounded-md px-2.5 py-2.5 text-left",+ customer.dubCustomerId+ ? "cursor-not-allowed opacity-60"+ : "transition-colors hover:bg-neutral-100",+ )}+ >+ <div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-neutral-200 text-xs font-medium text-neutral-600">+ {initials}+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5">+ <span className="font-medium text-neutral-800">+ {displayName}+ </span>+ {customer.email && customer.name && (+ <span className="truncate text-xs text-neutral-500">+ {customer.email}+ </span>+ )}+ </div>+ <div className="mt-1 flex flex-wrap items-center gap-x-2 text-xs text-neutral-500">+ <a+ href={stripeUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center gap-0.5 font-mono hover:text-neutral-700"+ onClick={(e) => e.stopPropagation()}+ >+ {customer.id}+ <ArrowUpRight className="size-3 shrink-0" />+ </a>+ {customer.subscriptions > 0 && (+ <span>{customer.subscriptions} sub</span>+ )}+ {customer.dubCustomerId && (+ <a+ href={`/${slug}/program/customers/${customer.dubCustomerId}`}+ target="_blank"+ className="rounded bg-neutral-200/80 px-1.5 py-0.5 text-neutral-500 hover:bg-neutral-200 hover:text-neutral-900"+ >+ Already on Dub+ </a>+ )}+ </div>+ </div>+ </button>+ </li>+ );+ })}+ </ul>+ </div>+ )}+ </div>+ ) : (+ <div className="flex flex-col gap-6 px-4 py-6 text-left sm:px-6">+ <div>+ <label className="text-sm font-medium text-neutral-600">+ Name+ </label>+ <input+ type="text"+ autoComplete="off"+ className="mt-1.5 block w-full rounded-lg border border-neutral-200 bg-white px-3 py-2.5 text-sm text-neutral-900 placeholder-neutral-400 shadow-sm transition-colors focus:border-neutral-400 focus:outline-none focus:ring-2 focus:ring-neutral-200"+ placeholder="John Doe"+ autoFocus={!isMobile}+ {...register("name", {+ setValueAs: (value) => (value === "" ? null : value),+ })}+ />+ </div>- <div>- <label className="text-sm font-normal text-neutral-500">- </label>- <input- type="email"- autoComplete="off"- className="mt-2 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"- placeholder="[email protected]"- {...register("email", {- setValueAs: (value) => (value === "" ? null : value),- })}- />- </div>+ <div>+ <label className="text-sm font-medium text-neutral-600">+ </label>+ <input+ type="email"+ autoComplete="off"+ className="mt-1.5 block w-full rounded-lg border border-neutral-200 bg-white px-3 py-2.5 text-sm text-neutral-900 placeholder-neutral-400 shadow-sm transition-colors focus:border-neutral-400 focus:outline-none focus:ring-2 focus:ring-neutral-200"+ placeholder="[email protected]"+ {...register("email", {+ setValueAs: (value) => (value === "" ? null : value),+ })}+ />+ </div>- <div>- <label className="text-sm font-normal text-neutral-500">- Stripe Customer ID- </label>- <input- type="text"- autoComplete="off"- className="mt-2 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"- placeholder="cus_NffrFeUfNV2Hib"- {...register("stripeCustomerId", {- setValueAs: (value) => (value === "" ? null : value),- })}- />- <p className="mt-2 text-xs text-neutral-500">- The customer's Stripe customer ID (optional)- </p>- </div>+ <div>+ <label className="text-sm font-medium text-neutral-600">+ Country <span className="text-neutral-400">(required)</span>+ </label>+ <CountryCombobox+ value={country || "US"}+ onChange={(value) =>+ setValue("country", value, { shouldValidate: true })+ }+ error={!!errors.country}+ className="mt-1.5"+ />+ <input+ type="hidden"+ {...register("country", { required: true })}+ />+ <p className="mt-1.5 text-xs text-neutral-500">+ Used in analytics and country-specific rewards.+ </p>+ </div>- <div>- <label className="text-sm font-normal text-neutral-500">- Country (Required)- </label>- <CountryCombobox- value={country || "US"}- onChange={(value) =>- setValue("country", value, { shouldValidate: true })- }- error={!!errors.country}- className="mt-2"- />- <input- type="hidden"- {...register("country", { required: true })}- />- </div>- </div>+ <div>+ <label className="text-sm font-medium text-neutral-600">+ External ID{" "}+ <span className="text-neutral-400">(required)</span>+ </label>+ <input+ type="text"+ required+ autoComplete="off"+ className="mt-1.5 block w-full rounded-lg border border-neutral-200 bg-white px-3 py-2.5 text-sm text-neutral-900 placeholder-neutral-400 shadow-sm transition-colors focus:border-neutral-400 focus:outline-none focus:ring-2 focus:ring-neutral-200"+ placeholder="e.g. cus_xxx or [email protected]"+ {...register("externalId", { required: true })}+ />+ <p className="mt-1.5 text-xs text-neutral-500">+ Your unique ID for this customer (e.g. database ID or+ email).+ </p>+ </div>++ <div className="rounded-lg border border-neutral-200 bg-white p-4 shadow-sm">+ <div className="flex items-center gap-4">+ <Switch+ fn={setHasStripeCustomerId}+ checked={hasStripeCustomerId}+ trackDimensions="w-8 h-4"+ thumbDimensions="w-3 h-3"+ thumbTranslate="translate-x-4"+ />+ <div className="flex flex-wrap items-center gap-1.5">+ <span className="text-sm font-medium text-neutral-700">+ Add+ </span>+ <span className="rounded border border-neutral-200 bg-neutral-50 px-1.5 py-0.5 font-mono text-xs text-neutral-500">+ stripeCustomerId+ </span>+ </div>+ </div>+ {hasStripeCustomerId && (+ <div className="mt-4">+ <label+ htmlFor="stripeCustomerId"+ className="text-sm font-medium text-neutral-600"+ >+ Stripe Customer ID+ </label>+ <input+ type="text"+ id="stripeCustomerId"+ autoComplete="off"+ className="mt-1.5 block w-full rounded-lg border border-neutral-200 bg-white px-3 py-2.5 text-sm text-neutral-900 placeholder-neutral-400 shadow-sm transition-colors focus:border-neutral-400 focus:outline-none focus:ring-2 focus:ring-neutral-200"+ placeholder="cus_NffrFeUfNV2Hib"+ {...register("stripeCustomerId", {+ setValueAs: (value) => (value === "" ? null : value),+ })}+ />+ <p className="mt-1.5 text-xs text-neutral-500">+ Optional. Used to attribute recurring sales to partners.+ </p>+ </div>+ )}+ </div>+ </div>+ )}+ </AnimatedSizeContainer>- <div className="flex items-center justify-end border-t border-neutral-200 px-4 py-4 sm:px-6">- <div className="flex gap-2">- <Button- type="button"- variant="secondary"- text="Cancel"- className="h-9 w-fit"- onClick={() => setShowModal(false)}- disabled={isSubmitting}- />- <Button- type="submit"- text="Create customer"- className="h-9 w-fit"- loading={isSubmitting}- disabled={!externalId || !country}- />- </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"+ text="Cancel"+ className="h-9 w-fit"+ onClick={() => setShowModal(false)}+ disabled={isSubmitting}+ />+ <Button+ type="submit"+ text="Create customer"+ className="h-9 w-fit"+ loading={isSubmitting}+ disabled={showStripeImport || !externalId || !country}+ /></div></form></div>