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.

update stripe customers

Kiran K2d3341f21760
diff --git a/apps/web/app/(ee)/api/cron/import/tolt/route.ts b/apps/web/app/(ee)/api/cron/import/tolt/route.ts
index 56d1015d2f..53f7339d91 100644
--- a/apps/web/app/(ee)/api/cron/import/tolt/route.ts
+++ b/apps/web/app/(ee)/api/cron/import/tolt/route.ts
@@ -5,6 +5,7 @@ import { importCommissions } from "@/lib/tolt/import-commissions";
import { importLinks } from "@/lib/tolt/import-links";
import { importReferrals } from "@/lib/tolt/import-referrals";
import { importSteps } from "@/lib/tolt/importer";
+import { updateStripeCustomers } from "@/lib/tolt/update-stripe-customers";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -14,6 +15,7 @@ const schema = z.object({
action: importSteps,
programId: z.string(),
startingAfter: z.string().optional(),
+ page: z.number().optional(),
});
export async function POST(req: Request) {
@@ -37,6 +39,9 @@ export async function POST(req: Request) {
case "import-referrals":
await importReferrals(payload);
break;
+ case "update-stripe-customers":
+ await updateStripeCustomers(payload);
+ break;
case "import-commissions":
await importCommissions(payload);
break;
diff --git a/apps/web/lib/tolt/importer.ts b/apps/web/lib/tolt/importer.ts
index 001ce7432c..b2f6238cd7 100644
--- a/apps/web/lib/tolt/importer.ts
+++ b/apps/web/lib/tolt/importer.ts
@@ -13,6 +13,7 @@ export const importSteps = z.enum([
"import-links",
"import-referrals",
"import-commissions",
+ "update-stripe-customers",
]);
class ToltImporter {
diff --git a/apps/web/lib/tolt/update-stripe-customers.ts b/apps/web/lib/tolt/update-stripe-customers.ts
new file mode 100644
index 0000000000..7700dcd827
--- /dev/null
+++ b/apps/web/lib/tolt/update-stripe-customers.ts
@@ -0,0 +1,146 @@
+import { prisma } from "@dub/prisma";
+import { Customer, Project } from "@dub/prisma/client";
+import { log } from "@dub/utils";
+import { stripeAppClient } from "../stripe";
+import { MAX_BATCHES, toltImporter } from "./importer";
+
+// Stripe API have a default limit of 25 requests per second
+const CUSTOMERS_PER_BATCH = 25;
+
+const stripe = stripeAppClient({
+ ...(process.env.VERCEL_ENV && { livemode: true }),
+});
+
+// Tolt API doesn't return the Stripe customer ID,
+// so we'll search for Stripe customers by email and update the customer record with the Stripe customer ID, if found.
+export async function updateStripeCustomers({
+ programId,
+ startingAfter,
+}: {
+ programId: string;
+ startingAfter?: string;
+}) {
+ const { workspace } = await prisma.program.findUniqueOrThrow({
+ where: {
+ id: programId,
+ },
+ select: {
+ workspace: {
+ select: {
+ id: true,
+ slug: true,
+ stripeConnectId: true,
+ },
+ },
+ },
+ });
+
+ if (!workspace.stripeConnectId) {
+ console.error(
+ `Workspace ${workspace.id} has no stripeConnectId. Skipping...`,
+ );
+ return;
+ }
+
+ let hasMore = true;
+ let processedBatches = 0;
+
+ while (hasMore && processedBatches < MAX_BATCHES) {
+ const customers = await prisma.customer.findMany({
+ where: {
+ projectId: workspace.id,
+ stripeCustomerId: null,
+ },
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ orderBy: {
+ createdAt: "asc",
+ },
+ take: CUSTOMERS_PER_BATCH,
+ skip: startingAfter ? 1 : 0,
+ ...(startingAfter && {
+ cursor: {
+ id: startingAfter,
+ },
+ }),
+ });
+
+ if (customers.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ await Promise.all(
+ customers.map((customer) =>
+ searchStripeCustomer({
+ workspace,
+ customer,
+ }),
+ ),
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+
+ processedBatches++;
+ startingAfter = customers[customers.length - 1].id;
+ }
+
+ if (hasMore) {
+ await toltImporter.queue({
+ programId,
+ action: "update-stripe-customers",
+ startingAfter,
+ });
+
+ return;
+ }
+}
+
+async function searchStripeCustomer({
+ workspace,
+ customer,
+}: {
+ workspace: Pick<Project, "id" | "slug" | "stripeConnectId">;
+ customer: Pick<Customer, "id" | "email">;
+}) {
+ const stripeCustomers = await stripe.customers.search(
+ {
+ query: `email:'${customer.email}'`,
+ },
+ {
+ stripeAccount: workspace.stripeConnectId!,
+ },
+ );
+
+ if (stripeCustomers.data.length === 0) {
+ console.error(`Stripe search returned no customer for ${customer.email}`);
+ return null;
+ }
+
+ if (stripeCustomers.data.length > 1) {
+ await log({
+ message: `Stripe search returned multiple customers for ${customer.email} for workspace ${workspace.slug}`,
+ type: "errors",
+ });
+
+ console.error(
+ `Stripe search returned multiple customers for ${customer.email}`,
+ );
+
+ return null;
+ }
+
+ const stripeCustomer = stripeCustomers.data[0];
+
+ await prisma.customer.update({
+ where: {
+ id: customer.id,
+ },
+ data: {
+ stripeCustomerId: stripeCustomer.id,
+ },
+ });
+}