Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Stripe customer update webhook handler #1942

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 22 additions & 123 deletions apps/web/app/api/stripe/integration/webhook/customer-created.ts
Original file line number Diff line number Diff line change
@@ -1,143 +1,42 @@
import { includeTags } from "@/lib/api/links/include-tags";
import { createId } from "@/lib/api/utils";
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";
import { createNewCustomer } from "./utils";

// Handle event "customer.created"
export async function customerCreated(event: Stripe.Event) {
const stripeCustomer = event.data.object as Stripe.Customer;
const stripeAccountId = event.account as string;
const externalId = stripeCustomer.metadata?.dubCustomerId;
const clickId = stripeCustomer.metadata?.dubClickId;

// The client app should always send dubClickId (dub_id) via metadata
if (!clickId) {
return "Click ID not found in Stripe customer metadata, skipping...";
}

// Find click
const clickEvent = await getClickEvent({ clickId });
if (!clickEvent || clickEvent.data.length === 0) {
return `Click event with ID ${clickId} not found, skipping...`;
}

const clickData = clickEvent.data[0];

// Find link
const linkId = clickData.link_id;
const link = await prisma.link.findUnique({
where: {
id: linkId,
},
});

if (!link || !link.projectId) {
return `Link with ID ${linkId} not found or does not have a project, skipping...`;
}

// Check the customer is not already created
// Find customer using projectConnectId and externalId (the customer's ID in the client app)
const customerFound = await prisma.customer.findUnique({
where: {
projectConnectId_externalId: {
projectConnectId: stripeAccountId,
externalId,
},
},
});

let customer: Customer;

if (customerFound) {
// 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({
if (externalId) {
// Check the customer is not already created
// Find customer using projectConnectId and externalId (the customer's ID in the client app)
const customerFound = await prisma.customer.findUnique({
where: {
id: customerFound.id,
},
data: {
stripeCustomerId: stripeCustomer.id,
projectConnectId: stripeAccountId,
},
});
return `Dub customer with ID ${customer.id} updated with Stripe customer ID ${stripeCustomer.id}`;
} 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,
projectConnectId_externalId: {
projectConnectId: stripeAccountId,
externalId,
},
},
});

const leadData = {
...clickData,
event_id: nanoid(16),
event_name: "New customer",
customer_id: customer.id,
};

const [_lead, linkUpdated, workspace] = await Promise.all([
// Record lead
recordLead(leadData),

// update link leads count
prisma.link.update({
if (customerFound) {
// if customer exists (created via /track/lead)
// update it with the Stripe customer ID (for future reference by invoice.paid)
await prisma.customer.update({
where: {
id: linkId,
id: customerFound.id,
},
data: {
leads: {
increment: 1,
},
stripeCustomerId: stripeCustomer.id,
projectConnectId: stripeAccountId,
},
include: includeTags,
}),
});

// update workspace usage
prisma.project.update({
where: {
id: customer.projectId,
},
data: {
usage: {
increment: 1,
},
},
}),
]);

waitUntil(
sendWorkspaceWebhook({
trigger: "lead.created",
workspace,
data: transformLeadEventData({
...leadData,
link: linkUpdated,
customerId: customer.id,
customerExternalId: customer.externalId,
customerName: customer.name,
customerEmail: customer.email,
customerAvatar: customer.avatar,
customerCreatedAt: customer.createdAt,
}),
}),
);
return `New Dub customer created: ${customer.id}. Lead event recorded: ${leadData.event_id}`;
return `Dub customer with ID ${customerFound.id} updated with Stripe customer ID ${stripeCustomer.id}`;
}
}

// otherwise create a new customer
return await createNewCustomer(event);
}
35 changes: 35 additions & 0 deletions apps/web/app/api/stripe/integration/webhook/customer-updated.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { prisma } from "@dub/prisma";
import type Stripe from "stripe";
import { createNewCustomer } from "./utils";

// Handle event "customer.updated"
export async function customerUpdated(event: Stripe.Event) {
const stripeCustomer = event.data.object as Stripe.Customer;
const stripeCustomerId = stripeCustomer.id;
const externalId = stripeCustomer.metadata?.dubCustomerId;

// Check if an existing Stripe customer exists
const customerFound = await prisma.customer.findUnique({
where: {
stripeCustomerId,
},
});

if (customerFound) {
await prisma.customer.update({
where: {
id: customerFound.id,
},
data: {
name: stripeCustomer.name,
email: stripeCustomer.email,
...(externalId && { externalId }),
},
});

return `Dub customer with ID ${customerFound.id} updated.`;
}

// otherwise create a new customer
return await createNewCustomer(event);
}
5 changes: 5 additions & 0 deletions apps/web/app/api/stripe/integration/webhook/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import Stripe from "stripe";
import { accountApplicationDeauthorized } from "./account-application-deauthorized";
import { checkoutSessionCompleted } from "./checkout-session-completed";
import { customerCreated } from "./customer-created";
import { customerUpdated } from "./customer-updated";
import { invoicePaid } from "./invoice-paid";

const relevantEvents = new Set([
"customer.created",
"customer.updated",
"checkout.session.completed",
"invoice.paid",
"account.application.deauthorized",
Expand Down Expand Up @@ -53,6 +55,9 @@ export const POST = withAxiom(
case "customer.created":
response = await customerCreated(event);
break;
case "customer.updated":
response = await customerUpdated(event);
break;
case "checkout.session.completed":
response = await checkoutSessionCompleted(event);
break;
Expand Down
114 changes: 114 additions & 0 deletions apps/web/app/api/stripe/integration/webhook/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { includeTags } from "@/lib/api/links/include-tags";
import { createId } from "@/lib/api/utils";
import { getClickEvent, recordLead } from "@/lib/tinybird";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
import { prisma } from "@dub/prisma";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";

export async function createNewCustomer(event: Stripe.Event) {
const stripeCustomer = event.data.object as Stripe.Customer;
const stripeAccountId = event.account as string;
const externalId = stripeCustomer.metadata?.dubCustomerId;
const clickId = stripeCustomer.metadata?.dubClickId;

// The client app should always send dubClickId (dub_id) via metadata
if (!clickId) {
return "Click ID not found in Stripe customer metadata, skipping...";
}

// Find click
const clickEvent = await getClickEvent({ clickId });
if (!clickEvent || clickEvent.data.length === 0) {
return `Click event with ID ${clickId} not found, skipping...`;
}

const clickData = clickEvent.data[0];

// Find link
const linkId = clickData.link_id;
const link = await prisma.link.findUnique({
where: {
id: linkId,
},
});

if (!link || !link.projectId) {
return `Link with ID ${linkId} not found or does not have a project, skipping...`;
}

// else create a new 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),
event_name: "New customer",
customer_id: customer.id,
};

const [_lead, linkUpdated, workspace] = await Promise.all([
// Record lead
recordLead(leadData),

// update link leads count
prisma.link.update({
where: {
id: linkId,
},
data: {
leads: {
increment: 1,
},
},
include: includeTags,
}),

// update workspace usage
prisma.project.update({
where: {
id: customer.projectId,
},
data: {
usage: {
increment: 1,
},
},
}),
]);

waitUntil(
sendWorkspaceWebhook({
trigger: "lead.created",
workspace,
data: transformLeadEventData({
...leadData,
link: linkUpdated,
customerId: customer.id,
customerExternalId: customer.externalId,
customerName: customer.name,
customerEmail: customer.email,
customerAvatar: customer.avatar,
customerCreatedAt: customer.createdAt,
}),
}),
);

return `New Dub customer created: ${customer.id}. Lead event recorded: ${leadData.event_id}`;
}
Loading