The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
import { convertCurrency } from "@/lib/analytics/convert-currency";
import { isFirstConversion } from "@/lib/analytics/is-first-conversion";
import { createId } from "@/lib/api/create-id";
import { getOrCreateCustomer } from "@/lib/api/customers/get-or-create-customer";
import { includeTags } from "@/lib/api/links/include-tags";
import { getNormalizedEmail } from "@/lib/email/normalize-email";
import { queueGoogleAdsConversionUpload } from "@/lib/integrations/google-ads/upload-conversion";
import { prisma } from "@/lib/prisma";
import {
getClickEvent,
getLeadEvent,
recordLead,
recordSale,
} from "@/lib/tinybird";
import { ClickEventTB, LeadEventTB } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformSaleEventData } from "@/lib/webhook/transform";
import { nanoid } from "@dub/utils";
import { Customer } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
import { WebhookHandlerInput, WebhookHandlerResponse } from "./types";
import { getConnectedCustomer } from "./utils/get-connected-customer";
import { getDubCustomerExternalIdFromMetadata } from "./utils/get-dub-customer-external-id-from-metadata";
import { incrementLinkLeads } from "./utils/increment-link-leads";
import { updateCustomerWithStripeCustomerId } from "./utils/update-customer-with-stripe-customer-id";
// Handle event "checkout.session.completed"
export async function checkoutSessionCompleted({
event,
mode,
workspace,
}: WebhookHandlerInput<Stripe.CheckoutSessionCompletedEvent>): Promise<WebhookHandlerResponse> {
let checkoutSession = event.data.object;
let dubCustomerExternalId = getDubCustomerExternalIdFromMetadata(
checkoutSession.metadata,
);
const clientReferenceId = checkoutSession.client_reference_id;
const stripeAccountId = event.account as string;
const stripeCustomerId = checkoutSession.customer as string;
const stripeCustomerName = checkoutSession.customer_details?.name;
const stripeCustomerEmail = checkoutSession.customer_details?.email;
const invoiceId = checkoutSession.invoice as string;
let customer: Customer | null = null;
let clickEvent: ClickEventTB | null = null;
let leadEvent: LeadEventTB | undefined;
let linkId: string | undefined;
/*
for stripe checkout links:
- if client_reference_id is a dub_id, we find the click event
- the click event will be used to create a lead event + customer
- the lead event will then be passed to the remaining logic to record a sale
*/
if (clientReferenceId?.startsWith("dub_id_")) {
const dubClickId = clientReferenceId.split("dub_id_")[1];
clickEvent = await getClickEvent({ clickId: dubClickId });
if (!clickEvent) {
return {
response: `Click event with dub_id ${dubClickId} not found, skipping...`,
};
}
if (clickEvent.workspace_id !== workspace.id) {
return {
response: `Link "${clickEvent.link_id}" for click event "${dubClickId}" does not belong to workspace ${workspace.id}, skipping...`,
};
}
const payload = {
name: stripeCustomerName,
email: stripeCustomerEmail,
...(stripeCustomerEmail !== undefined && {
normalizedEmail: getNormalizedEmail(stripeCustomerEmail),
}),
// stripeCustomerId can potentially be null, so we use email as fallback
externalId: stripeCustomerId || stripeCustomerEmail,
projectId: workspace.id,
projectConnectId: stripeAccountId,
stripeCustomerId,
clickId: clickEvent.click_id,
linkId: clickEvent.link_id,
country: clickEvent.country,
clickedAt: new Date(clickEvent.timestamp + "Z"),
};
const { customer: existingOrNewCustomer, created } =
await getOrCreateCustomer({
findMode: "first",
where: {
OR: [
{
projectId: workspace.id,
externalId: clickEvent.click_id,
},
...(stripeCustomerEmail
? [
{
projectId: workspace.id,
externalId: stripeCustomerEmail,
},
]
: []),
// include create unique keys so concurrent P2002 fallbacks can find
// the customer that won the insert (externalId / stripeCustomerId)
...(payload.externalId
? [
{
projectId: workspace.id,
externalId: payload.externalId,
},
]
: []),
...(stripeCustomerId
? [
{
stripeCustomerId,
},
]
: []),
],
},
create: {
id: createId({ prefix: "cus_" }),
...payload,
},
});
if (created) {
customer = existingOrNewCustomer;
} else {
customer = await prisma.customer.update({
where: {
id: existingOrNewCustomer.id,
},
data: payload,
});
}
// remove timestamp from clickEvent
const { timestamp, ...rest } = clickEvent;
leadEvent = {
...rest,
workspace_id: clickEvent.workspace_id || customer.projectId, // in case for some reason the click event doesn't have workspace_id
event_id: nanoid(16),
event_name: "Sign up",
customer_id: customer.id,
metadata: "",
};
// if the customer was created, we record the lead event and increment the link leads
if (created) {
await recordLead(leadEvent);
waitUntil(incrementLinkLeads(clickEvent.link_id));
}
linkId = clickEvent.link_id;
} else if (stripeCustomerId) {
/*
for regular stripe checkout setup (provided stripeCustomerId is present):
- if dubCustomerExternalId is provided:
- we try to update the customer with the stripe customerId (for future events)
- if the customer is not found, we skip the event
- else:
- we first try to see if the customer with the Stripe ID already exists in Dub
- if it does, great, we can use the customer found on Dub
- if it doesn't, we try to find the customer on the connected account
- if present:
- we update the customer with the stripe customerId
- we then find the lead event using the customer's unique ID on Dub
- the lead event will then be passed to the remaining logic to record a sale
- if not present, or if the customer is not found on Dub, we skip the event
*/
if (dubCustomerExternalId) {
customer = await updateCustomerWithStripeCustomerId({
workspaceId: workspace.id,
dubCustomerExternalId,
stripeCustomerId,
});
if (!customer) {
return {
response: `dubCustomerExternalId was provided but customer with dubCustomerExternalId ${dubCustomerExternalId} not found on Dub, skipping...`,
};
}
} else {
// find customer by stripeCustomerId or email
const existingCustomer = await prisma.customer.findFirst({
where: {
OR: [
{
stripeCustomerId,
},
...(stripeCustomerEmail
? [
{
projectId: workspace.id,
email: stripeCustomerEmail,
},
]
: []),
],
},
});
if (existingCustomer) {
dubCustomerExternalId = existingCustomer.externalId ?? stripeCustomerId;
customer = existingCustomer;
} else {
const connectedCustomer = await getConnectedCustomer({
stripeCustomerId,
stripeAccountId,
mode,
});
const connectedCustomerDubCustomerExternalId =
getDubCustomerExternalIdFromMetadata(connectedCustomer?.metadata);
if (connectedCustomerDubCustomerExternalId) {
dubCustomerExternalId = connectedCustomerDubCustomerExternalId;
customer = await updateCustomerWithStripeCustomerId({
workspaceId: workspace.id,
dubCustomerExternalId,
stripeCustomerId,
});
}
if (!customer) {
if (connectedCustomerDubCustomerExternalId) {
return {
response: `dubCustomerExternalId was found on the connected customer ${stripeCustomerId} but customer with dubCustomerExternalId ${dubCustomerExternalId} not found on Dub, skipping...`,
};
} else {
return {
response: `dubCustomerExternalId not found in Stripe checkout session metadata (nor is it available on the connected customer ${stripeCustomerId}), and client_reference_id is not a dub_id, skipping...`,
};
}
}
}
}
// if leadEvent is not defined yet, we need to pull it from Tinybird
if (!leadEvent) {
const leadEventData = await getLeadEvent({ customerId: customer.id });
if (!leadEventData) {
return {
response: `No lead event found for customer ${customer.id}, skipping...`,
};
}
leadEvent = {
...leadEventData,
workspace_id: leadEventData.workspace_id || customer.projectId, // in case for some reason the lead event doesn't have workspace_id
};
linkId = leadEvent.link_id;
}
} else {
return {
response: `No stripeCustomerId or dubCustomerExternalId found in Stripe checkout session metadata, skipping...`,
};
}
let checkoutSessionAmountTotal =
(checkoutSession.amount_total ?? 0) -
(checkoutSession.total_details?.amount_tax ?? 0);
// should never be below 0, but just in case
if (checkoutSessionAmountTotal <= 0) {
return {
response: `Checkout session completed for Stripe customer ${stripeCustomerId} but amount is 0, skipping...`,
};
}
if (checkoutSession.mode === "setup") {
return {
response: `Checkout session completed for Stripe customer ${stripeCustomerId} but mode is "setup", skipping...`,
};
}
if (checkoutSession.payment_status !== "paid") {
return {
response: `Checkout session completed for Stripe customer ${stripeCustomerId} but payment_status is not "paid", skipping...`,
};
}
if (invoiceId) {
// Skip if invoice id is already processed
const ok = await redis.set(
`trackSale:stripe:invoiceId:${invoiceId}`, // here we assume that Stripe's invoice ID is unique across all customers
{
timestamp: new Date().toISOString(),
dubCustomerExternalId,
stripeCustomerId,
stripeAccountId,
invoiceId,
customerId: customer.id,
workspaceId: customer.projectId,
amount: checkoutSessionAmountTotal,
currency: checkoutSession.currency,
},
{
ex: 60 * 60 * 24 * 7,
nx: true,
},
);
if (!ok) {
console.info(
"[checkout.session.completed] Skipping already processed invoice.",
invoiceId,
);
return {
response: `Invoice with ID ${invoiceId} already processed, skipping...`,
};
}
}
if (
checkoutSession.currency &&
checkoutSession.currency !== "usd" &&
checkoutSessionAmountTotal
) {
// support for Stripe Adaptive Pricing: https://docs.stripe.com/payments/checkout/adaptive-pricing
if (checkoutSession.currency_conversion) {
checkoutSession.currency =
checkoutSession.currency_conversion.source_currency;
checkoutSessionAmountTotal =
checkoutSession.currency_conversion.amount_total;
// if Stripe Adaptive Pricing is not enabled, we convert the amount to USD based on the current FX rate
// TODO: allow custom "defaultCurrency" on workspace table in the future
} else {
const { currency: convertedCurrency, amount: convertedAmount } =
await convertCurrency({
currency: checkoutSession.currency,
amount: checkoutSessionAmountTotal,
});
checkoutSession.currency = convertedCurrency;
checkoutSessionAmountTotal = convertedAmount;
}
}
const saleData = {
...leadEvent,
workspace_id: leadEvent.workspace_id || customer.projectId, // in case for some reason the lead event doesn't have workspace_id
event_id: nanoid(16),
// if the checkoutSession is a one-time payment, we set the event name to "Purchase"
event_name:
checkoutSession.mode === "payment" ? "Purchase" : "Subscription creation",
payment_processor: "stripe",
amount: checkoutSessionAmountTotal,
currency: checkoutSession.currency!,
invoice_id: invoiceId || "",
metadata: JSON.stringify({
checkoutSession,
}),
};
const link = await prisma.link.findUnique({
where: {
id: linkId,
},
});
const firstConversionFlag = isFirstConversion({
customer,
linkId,
});
const [_sale, linkUpdated] = await Promise.all([
recordSale(saleData),
// update link stats
link &&
prisma.link.update({
where: {
id: link.id,
},
data: {
...(firstConversionFlag && {
conversions: {
increment: 1,
},
lastConversionAt: new Date(),
}),
sales: {
increment: 1,
},
saleAmount: {
increment: checkoutSessionAmountTotal,
},
},
include: includeTags,
}),
// update workspace usage
prisma.project.update({
where: {
id: customer.projectId,
},
data: {
usage: {
increment: 1,
},
},
}),
// update customer stats
prisma.customer.update({
where: {
id: customer.id,
},
data: {
sales: {
increment: 1,
},
saleAmount: {
increment: checkoutSessionAmountTotal,
},
firstSaleAt: customer.firstSaleAt ? undefined : new Date(),
subscriptionCanceledAt: null,
...(!customer?.stripeCustomerId &&
stripeCustomerId && {
stripeCustomerId,
}),
},
}),
]);
waitUntil(
Promise.allSettled([
sendWorkspaceWebhook({
trigger: "sale.created",
workspace,
data: transformSaleEventData({
...saleData,
clickedAt: customer.clickedAt || customer.createdAt,
link: linkUpdated,
customer,
metadata: null,
}),
}),
queueGoogleAdsConversionUpload({
workspaceId: workspace.id,
eventType: "sale",
eventName: saleData.event_name,
conversionDateTime: new Date().toISOString(),
eventId: saleData.event_id,
conversionValue: saleData.amount,
currencyCode: saleData.currency,
click: {
id: saleData.click_id,
url: saleData.url,
},
}),
]),
);
return {
response: `Checkout session completed for customer with external ID ${dubCustomerExternalId} and invoice ID ${invoiceId}`,
};
}