Skip to content

Commit

Permalink
Fix customer.created webhook race condition
Browse files Browse the repository at this point in the history
  • Loading branch information
steven-tey committed Jan 16, 2025
1 parent df7284c commit ffb1cb3
Showing 1 changed file with 32 additions and 18 deletions.
50 changes: 32 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,40 @@ export async function customerCreated(event: Stripe.Event) {
},
});

let customer: Customer;

if (customerFound) {
return `Customer with external ID ${externalId} already exists, skipping...`;
// if customer exists, update it
customer = await prisma.customer.update({
where: {
id: customerFound.id,
},
data: {
name: stripeCustomer.name,
email: stripeCustomer.email,
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 ffb1cb3

Please sign in to comment.