Skip to content

Commit

Permalink
Merge pull request #1911 from dubinc/fix-customer-created
Browse files Browse the repository at this point in the history
Fix customer.created webhook race condition
  • Loading branch information
steven-tey authored Jan 16, 2025
2 parents df7284c + af4cb9e commit 44ecb9c
Showing 1 changed file with 31 additions and 18 deletions.
49 changes: 31 additions & 18 deletions apps/web/app/api/stripe/integration/webhook/customer-created.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { getClickEvent, recordLead } from "@/lib/tinybird";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
import { prisma } from "@dub/prisma";
import { Customer } from "@dub/prisma/client";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
Expand Down Expand Up @@ -50,27 +51,39 @@ export async function customerCreated(event: Stripe.Event) {
},
});

let customer: Customer;

if (customerFound) {
return `Customer with external ID ${externalId} already exists, skipping...`;
// if customer exists (created via /track/lead)
// update it with the Stripe customer ID (for future reference by invoice.paid)
customer = await prisma.customer.update({
where: {
id: customerFound.id,
},
data: {
stripeCustomerId: stripeCustomer.id,
projectConnectId: stripeAccountId,
},
});
} else {
// else create a new customer
customer = await prisma.customer.create({
data: {
id: createId({ prefix: "cus_" }),
name: stripeCustomer.name,
email: stripeCustomer.email,
stripeCustomerId: stripeCustomer.id,
projectConnectId: stripeAccountId,
externalId,
projectId: link.projectId,
linkId,
clickId,
clickedAt: new Date(clickData.timestamp + "Z"),
country: clickData.country,
},
});
}

// Create customer
const customer = await prisma.customer.create({
data: {
id: createId({ prefix: "cus_" }),
name: stripeCustomer.name,
email: stripeCustomer.email,
stripeCustomerId: stripeCustomer.id,
projectConnectId: stripeAccountId,
externalId,
projectId: link.projectId,
linkId,
clickId,
clickedAt: new Date(clickData.timestamp + "Z"),
country: clickData.country,
},
});

const leadData = {
...clickData,
event_id: nanoid(16),
Expand Down

0 comments on commit 44ecb9c

Please sign in to comment.