The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add Stripe customer update webhook handler
Kiran K3cc5c795e334
diff --git a/apps/web/app/api/stripe/integration/webhook/customer-created.ts b/apps/web/app/api/stripe/integration/webhook/customer-created.tsindex 8bb9e16526..f48f705dd8 100644--- a/apps/web/app/api/stripe/integration/webhook/customer-created.ts+++ b/apps/web/app/api/stripe/integration/webhook/customer-created.ts@@ -1,141 +1,7 @@-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({- 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,- },- });-- const leadData = {- ...clickData,- event_id: nanoid(16),- event_name: "New customer",- customer_id: customer.id,- };-- const [_lead, _link, workspace] = await Promise.all([- // Record lead- recordLead(leadData),-- // update link leads count- prisma.link.update({- where: {- id: linkId,- },- data: {- leads: {- increment: 1,- },- },- }),-- // update workspace usage- prisma.project.update({- where: {- id: customer.projectId,- },- data: {- usage: {- increment: 1,- },- },- }),- ]);-- waitUntil(- sendWorkspaceWebhook({- trigger: "lead.created",- workspace,- data: transformLeadEventData({- ...leadData,- link,- 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 await createNewCustomer(event);}diff --git a/apps/web/app/api/stripe/integration/webhook/customer-updated.ts b/apps/web/app/api/stripe/integration/webhook/customer-updated.tsnew file mode 100644index 0000000000..8f4fed00b0--- /dev/null+++ b/apps/web/app/api/stripe/integration/webhook/customer-updated.ts@@ -0,0 +1,34 @@+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;++ // An existing customer found with valid stripeCustomerId+ const customerFound = await prisma.customer.findUnique({+ where: {+ stripeCustomerId,+ },+ });++ // update the customer+ if (customerFound) {+ await prisma.customer.update({+ where: {+ id: customerFound.id,+ },+ data: {+ name: stripeCustomer.name,+ email: stripeCustomer.email,+ },+ });++ return `Dub customer with ID ${customerFound.id} updated.`;+ }++ // Let's check if the metadata has the dubClickId and dubCustomerId if it does, we can create a new customer+ return await createNewCustomer(event);+}diff --git a/apps/web/app/api/stripe/integration/webhook/route.ts b/apps/web/app/api/stripe/integration/webhook/route.tsindex 28b7f869ac..5b47d9a6d7 100644--- a/apps/web/app/api/stripe/integration/webhook/route.ts+++ b/apps/web/app/api/stripe/integration/webhook/route.ts@@ -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",@@ -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;diff --git a/apps/web/app/api/stripe/integration/webhook/utils.ts b/apps/web/app/api/stripe/integration/webhook/utils.tsnew file mode 100644index 0000000000..850686ea89--- /dev/null+++ b/apps/web/app/api/stripe/integration/webhook/utils.ts@@ -0,0 +1,140 @@+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";++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...`;+ }++ // 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({+ 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,+ },+ });++ const leadData = {+ ...clickData,+ event_id: nanoid(16),+ event_name: "New customer",+ customer_id: customer.id,+ };++ const [_lead, _link, workspace] = await Promise.all([+ // Record lead+ recordLead(leadData),++ // update link leads count+ prisma.link.update({+ where: {+ id: linkId,+ },+ data: {+ leads: {+ increment: 1,+ },+ },+ }),++ // update workspace usage+ prisma.project.update({+ where: {+ id: customer.projectId,+ },+ data: {+ usage: {+ increment: 1,+ },+ },+ }),+ ]);++ waitUntil(+ sendWorkspaceWebhook({+ trigger: "lead.created",+ workspace,+ data: transformLeadEventData({+ ...leadData,+ link,+ 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}`;+ }+}