The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
finalize checkout.session.completed webhook
Steven Tey29752820d360
diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.tsindex 2a530f0dda..fb7ee7a901 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/checkout-session-completed.ts@@ -22,19 +22,18 @@ import {import { prisma } from "@dub/prisma";import { Customer, WorkflowTrigger } from "@dub/prisma/client";import { COUNTRIES_TO_CONTINENTS, nanoid } from "@dub/utils";+import { REGION_CODE_LOOKUP } from "@dub/utils/src/constants/regions";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";-import {- getConnectedCustomer,- getPromotionCode,- getSubscriptionProductId,- updateCustomerWithStripeCustomerId,-} from "./utils";+import { getConnectedCustomer } from "./utils/get-connected-customer";+import { getPromotionCode } from "./utils/get-promotion-code";+import { getSubscriptionProductId } from "./utils/get-subscription-product-id";+import { updateCustomerWithStripeCustomerId } from "./utils/update-customer-with-stripe-customer-id";// Handle event "checkout.session.completed"export async function checkoutSessionCompleted(event: Stripe.Event) {let charge = event.data.object as Stripe.Checkout.Session;- let dubCustomerId = charge.metadata?.dubCustomerId;+ let dubCustomerExternalId = charge.metadata?.dubCustomerId; // TODO: need to update to dubCustomerExternalId in the future for consistencyconst clientReferenceId = charge.client_reference_id;const stripeAccountId = event.account as string;const stripeCustomerId = charge.customer as string;@@ -46,8 +45,8 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {let customer: Customer | null = null;let existingCustomer: Customer | null = null;let clickEvent: ClickEventTB | null = null;- let leadEvent: LeadEventTB;- let linkId: string;+ let leadEvent: LeadEventTB | undefined;+ let linkId: string | undefined;let shouldSendLeadWebhook = true;/*@@ -144,7 +143,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {} else if (stripeCustomerId) {/*for regular stripe checkout setup (provided stripeCustomerId is present):- - if dubCustomerId is provided:+ - if dubCustomerExternalId is provided:- we update the customer with the stripe customerId (for future events)- else:- we first try to see if the customer with the Stripe ID already exists in Dub@@ -154,17 +153,25 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {- 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, we skip the event+ - if not present:+ - we check if a promotion code was used in the checkout+ - if a promotion code is present, we try to attribute via the promotion code:+ - confirm the promotion code exists in Stripe+ - find the associated discount code and link in Dub+ - record a fake click event for attribution+ - create a new customer and lead event+ - proceed with sale recording+ - if no promotion code or attribution fails, we skip the event*/- if (dubCustomerId) {+ if (dubCustomerExternalId) {customer = await updateCustomerWithStripeCustomerId({stripeAccountId,- dubCustomerId,+ dubCustomerExternalId,stripeCustomerId,});if (!customer) {- return `dubCustomerId was provided but customer with dubCustomerId ${dubCustomerId} not found on Dub, skipping...`;+ return `dubCustomerExternalId was provided but customer with dubCustomerExternalId ${dubCustomerExternalId} not found on Dub, skipping...`;}} else {existingCustomer = await prisma.customer.findUnique({@@ -174,7 +181,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {});if (existingCustomer) {- dubCustomerId = existingCustomer.externalId ?? stripeCustomerId;+ dubCustomerExternalId = existingCustomer.externalId ?? stripeCustomerId;customer = existingCustomer;} else {const connectedCustomer = await getConnectedCustomer({@@ -183,126 +190,48 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {livemode: event.livemode,});- if (!connectedCustomer || !connectedCustomer.metadata.dubCustomerId) {- return `dubCustomerId not found in Stripe checkout session metadata (nor is it available in Dub, or on the connected customer ${stripeCustomerId}) and client_reference_id is not a dub_id, skipping...`;- }-- dubCustomerId = connectedCustomer.metadata.dubCustomerId;- customer = await updateCustomerWithStripeCustomerId({- stripeAccountId,- dubCustomerId,- stripeCustomerId,- });- if (!customer) {- return `dubCustomerId was found on the connected customer ${stripeCustomerId} but customer with dubCustomerId ${dubCustomerId} not found on Dub, skipping...`;+ if (connectedCustomer?.metadata.dubCustomerId) {+ dubCustomerExternalId = connectedCustomer.metadata.dubCustomerId; // TODO: need to update to dubCustomerExternalId in the future for consistency+ customer = await updateCustomerWithStripeCustomerId({+ stripeAccountId,+ dubCustomerExternalId,+ stripeCustomerId,+ });+ if (!customer) {+ return `dubCustomerExternalId was found on the connected customer ${stripeCustomerId} but customer with dubCustomerExternalId ${dubCustomerExternalId} not found on Dub, skipping...`;+ }+ } else if (promotionCodeId) {+ const promoCodeResponse = await attributeViaPromoCode({+ promotionCodeId,+ stripeAccountId,+ livemode: event.livemode,+ charge,+ });+ if (promoCodeResponse) {+ ({ linkId, customer, clickEvent, leadEvent } = promoCodeResponse);+ shouldSendLeadWebhook = false;+ } else {+ return `Failed to attribute via promotion code ${promotionCodeId}, skipping...`;+ }+ } else {+ return `dubCustomerExternalId not found in Stripe checkout session metadata (nor is it available on the connected customer ${stripeCustomerId}), client_reference_id is not a dub_id, and promotion code is not provided, skipping...`;}}}- // Find lead- leadEvent = await getLeadEvent({ customerId: customer.id }).then(- (res) => res.data[0],- );-- linkId = leadEvent.link_id;- } else if (promotionCodeId) {- // Find the promotion code for the promotion code id- const promotionCode = await getPromotionCode({- promotionCodeId,- stripeAccountId,- livemode: event.livemode,- });-- if (!promotionCode) {- return `Promotion code ${promotionCodeId} not found in connected account ${stripeAccountId}, skipping...`;- }-- // Find the workspace- const workspace = await prisma.project.findUnique({- where: {- stripeConnectId: stripeAccountId,- },- select: {- id: true,- stripeConnectId: true,- defaultProgramId: true,- },- });-- if (!workspace) {- return `Workspace with stripeConnectId ${stripeAccountId} not found, skipping...`;- }-- if (!workspace.defaultProgramId) {- return `Workspace with stripeConnectId ${stripeAccountId} has no default program, skipping...`;- }-- const discountCode = await prisma.discountCode.findUnique({- where: {- programId_code: {- programId: workspace.defaultProgramId,- code: promotionCode.code,- },- },- select: {- link: true,- },- });+ // if leadEvent is not defined yet, we need to pull it from Tinybird+ if (!leadEvent) {+ leadEvent = await getLeadEvent({ customerId: customer.id }).then(+ (res) => res.data[0],+ );+ if (!leadEvent) {+ return `No lead event found for customer ${customer.id}, skipping...`;+ }- if (!discountCode) {- return `Couldn't find link associated with promotion code ${promotionCode.code}, skipping...`;+ linkId = leadEvent.link_id as string;}-- const link = discountCode.link;- linkId = link.id;-- // Record a fake click for this event- const customerDetails = charge.customer_details;- const customerAddress = customerDetails?.address;-- clickEvent = await recordFakeClick({- link,- customer: {- continent: customerAddress?.country- ? COUNTRIES_TO_CONTINENTS[customerAddress.country]- : "NA",- country: customerAddress?.country ?? "US",- region: customerAddress?.state ?? "CA",- },- });-- customer = await prisma.customer.create({- data: {- id: createId({ prefix: "cus_" }),- name:- customerDetails?.name ||- customerDetails?.email ||- generateRandomName(),- email: customerDetails?.email,- externalId: clickEvent.click_id,- linkId: clickEvent.link_id,- clickId: clickEvent.click_id,- clickedAt: new Date(clickEvent.timestamp + "Z"),- country: customerAddress?.country,- projectId: workspace.id,- projectConnectId: workspace.stripeConnectId,- },- });-- // Prepare the payload for the lead event- const { timestamp, ...rest } = clickEvent;-- leadEvent = {- ...rest,- event_id: nanoid(16),- event_name: "Sign up",- customer_id: customer.id,- metadata: "",- };-- shouldSendLeadWebhook = false;} else {- return "No dubCustomerId or stripeCustomerId found in Stripe checkout session metadata, skipping...";+ return "No stripeCustomerId or dubCustomerExternalId found in Stripe checkout session metadata, skipping...";}if (charge.amount_total === 0) {@@ -319,7 +248,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {`trackSale:stripe:invoiceId:${invoiceId}`, // here we assume that Stripe's invoice ID is unique across all customers{timestamp: new Date().toISOString(),- dubCustomerId,+ dubCustomerExternalId,stripeCustomerId,stripeAccountId,invoiceId,@@ -549,5 +478,130 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {})(),);- return `Checkout session completed for customer with external ID ${dubCustomerId} and invoice ID ${invoiceId}`;+ return `Checkout session completed for customer with external ID ${dubCustomerExternalId} and invoice ID ${invoiceId}`;+}++async function attributeViaPromoCode({+ promotionCodeId,+ stripeAccountId,+ livemode,+ charge,+}: {+ promotionCodeId: string;+ stripeAccountId: string;+ livemode: boolean;+ charge: Stripe.Checkout.Session;+}) {+ // Find the promotion code for the promotion code id+ const promotionCode = await getPromotionCode({+ promotionCodeId,+ stripeAccountId,+ livemode,+ });++ if (!promotionCode) {+ console.log(+ `Promotion code ${promotionCodeId} not found in connected account ${stripeAccountId}, skipping...`,+ );+ return null;+ }++ // Find the workspace+ const workspace = await prisma.project.findUnique({+ where: {+ stripeConnectId: stripeAccountId,+ },+ select: {+ id: true,+ stripeConnectId: true,+ defaultProgramId: true,+ },+ });++ if (!workspace) {+ console.log(+ `Workspace with stripeConnectId ${stripeAccountId} not found, skipping...`,+ );+ return null;+ }++ if (!workspace.defaultProgramId) {+ console.log(+ `Workspace with stripeConnectId ${stripeAccountId} has no default program, skipping...`,+ );+ return null;+ }++ const discountCode = await prisma.discountCode.findUnique({+ where: {+ programId_code: {+ programId: workspace.defaultProgramId,+ code: promotionCode.code,+ },+ },+ select: {+ link: true,+ },+ });++ if (!discountCode) {+ console.log(+ `Couldn't find link associated with promotion code ${promotionCode.code}, skipping...`,+ );+ return null;+ }++ const link = discountCode.link;+ const linkId = link.id;++ // Record a fake click for this event+ const customerDetails = charge.customer_details;+ const customerAddress = customerDetails?.address;++ const clickEvent = await recordFakeClick({+ link,+ customer: {+ continent: customerAddress?.country+ ? COUNTRIES_TO_CONTINENTS[customerAddress.country]+ : "Unknown",+ country: customerAddress?.country ?? "Unknown",+ region: customerAddress?.state+ ? REGION_CODE_LOOKUP[customerAddress.state]+ : "Unknown",+ },+ });++ const customer = await prisma.customer.create({+ data: {+ id: createId({ prefix: "cus_" }),+ name:+ customerDetails?.name || customerDetails?.email || generateRandomName(),+ email: customerDetails?.email,+ externalId: clickEvent.click_id,+ linkId: clickEvent.link_id,+ clickId: clickEvent.click_id,+ clickedAt: new Date(clickEvent.timestamp + "Z"),+ country: customerAddress?.country,+ projectId: workspace.id,+ projectConnectId: workspace.stripeConnectId,+ },+ });++ // Prepare the payload for the lead event+ const { timestamp, ...rest } = clickEvent;++ const leadEvent = {+ ...rest,+ event_id: nanoid(16),+ event_name: "Sign up",+ customer_id: customer.id,+ metadata: "",+ };++ return {+ linkId,+ customer,+ clickEvent,+ leadEvent,+ };}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.tsindex 7439c9c4f0..4a330a7120 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-created.ts@@ -1,12 +1,12 @@import { prisma } from "@dub/prisma";import type Stripe from "stripe";-import { createNewCustomer } from "./utils";+import { createNewCustomer } from "./utils/create-new-customer";// 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 dubCustomerExternalId = stripeCustomer.metadata?.dubCustomerId;+ const dubCustomerExternalId = stripeCustomer.metadata?.dubCustomerId; // TODO: need to update to dubCustomerExternalId in the future for consistencyif (!dubCustomerExternalId) {return "External ID not found in Stripe customer metadata, skipping...";diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.tsindex 9335dcc73a..36a97b0afd 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/customer-updated.ts@@ -1,12 +1,12 @@import { prisma } from "@dub/prisma";import type Stripe from "stripe";-import { createNewCustomer } from "./utils";+import { createNewCustomer } from "./utils/create-new-customer";// Handle event "customer.updated"export async function customerUpdated(event: Stripe.Event) {const stripeCustomer = event.data.object as Stripe.Customer;const stripeAccountId = event.account as string;- const dubCustomerExternalId = stripeCustomer.metadata?.dubCustomerId;+ const dubCustomerExternalId = stripeCustomer.metadata?.dubCustomerId; // TODO: need to update to dubCustomerExternalId in the future for consistencyif (!dubCustomerExternalId) {return "External ID not found in Stripe customer metadata, skipping...";diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.tsindex 1f2e41a055..30dfab1362 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/invoice-paid.ts@@ -13,7 +13,7 @@ import { WorkflowTrigger } from "@dub/prisma/client";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";-import { getConnectedCustomer } from "./utils";+import { getConnectedCustomer } from "./utils/get-connected-customer";// Handle event "invoice.paid"export async function invoicePaid(event: Stripe.Event) {@@ -29,7 +29,7 @@ export async function invoicePaid(event: Stripe.Event) {},});- // if customer is not found, we check if the connected customer has a dubCustomerId+ // if customer is not found, we check if the connected customer has a dubCustomerExternalIdif (!customer) {const connectedCustomer = await getConnectedCustomer({stripeCustomerId,@@ -37,16 +37,16 @@ export async function invoicePaid(event: Stripe.Event) {livemode: event.livemode,});- const dubCustomerId = connectedCustomer?.metadata.dubCustomerId;+ const dubCustomerExternalId = connectedCustomer?.metadata.dubCustomerId; // TODO: need to update to dubCustomerExternalId in the future for consistency- if (dubCustomerId) {+ if (dubCustomerExternalId) {try {// Update customer with stripeCustomerId if exists – for future eventscustomer = await prisma.customer.update({where: {projectConnectId_externalId: {projectConnectId: stripeAccountId,- externalId: dubCustomerId,+ externalId: dubCustomerExternalId,},},data: {@@ -55,14 +55,14 @@ export async function invoicePaid(event: Stripe.Event) {});} catch (error) {console.log(error);- return `Customer with dubCustomerId ${dubCustomerId} not found, skipping...`;+ return `Customer with dubCustomerExternalId ${dubCustomerExternalId} not found, skipping...`;}}}// if customer is still not found, we skip the eventif (!customer) {- return `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub (nor does the connected customer ${stripeCustomerId} have a valid dubCustomerId), skipping...`;+ return `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub (nor does the connected customer ${stripeCustomerId} have a valid dubCustomerExternalId), skipping...`;}// Skip if invoice id is already processed@@ -70,7 +70,7 @@ export async function invoicePaid(event: Stripe.Event) {`trackSale:stripe:invoiceId:${invoiceId}`, // here we assume that Stripe's invoice ID is unique across all customers{timestamp: new Date().toISOString(),- dubCustomerId: customer.externalId,+ dubCustomerExternalId: customer.externalId,stripeCustomerId,stripeAccountId,invoiceId,diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/route.tsindex 2ac7876f2f..8f2d5f41be 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/route.ts@@ -87,5 +87,5 @@ export const POST = withAxiom(async (req: Request) => {break;}- return logAndRespond(response);+ return logAndRespond(`[${event.type}]: ${response}`);});diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.tssimilarity index 60%rename from apps/web/app/(ee)/api/stripe/integration/webhook/utils.tsrename to apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.tsindex 2c6f101564..06ce243137 100644--- a/apps/web/app/(ee)/api/stripe/integration/webhook/utils.ts+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/create-new-customer.ts@@ -3,7 +3,6 @@ import { includeTags } from "@/lib/api/links/include-tags";import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";import { generateRandomName } from "@/lib/names";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";-import { stripeAppClient } from "@/lib/stripe";import { getClickEvent, recordLead } from "@/lib/tinybird";import { WebhookPartner } from "@/lib/types";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";@@ -153,116 +152,3 @@ export async function createNewCustomer(event: Stripe.Event) {return `New Dub customer created: ${customer.id}. Lead event recorded: ${leadData.event_id}`;}--export async function getConnectedCustomer({- stripeCustomerId,- stripeAccountId,- livemode = true,-}: {- stripeCustomerId?: string | null;- stripeAccountId?: string | null;- livemode?: boolean;-}) {- // if stripeCustomerId or stripeAccountId is not provided, return null- if (!stripeCustomerId || !stripeAccountId) {- return null;- }-- const connectedCustomer = await stripeAppClient({- livemode,- }).customers.retrieve(stripeCustomerId, {- stripeAccount: stripeAccountId,- });-- if (connectedCustomer.deleted) {- return null;- }-- return connectedCustomer;-}--export async function updateCustomerWithStripeCustomerId({- stripeAccountId,- dubCustomerId,- stripeCustomerId,-}: {- stripeAccountId?: string | null;- dubCustomerId: string;- stripeCustomerId?: string | null;-}) {- // if stripeCustomerId or stripeAccountId is not provided, return null- // (same logic as in getConnectedCustomer)- if (!stripeCustomerId || !stripeAccountId) {- return null;- }-- try {- // Update customer with stripeCustomerId if exists – for future events- return await prisma.customer.update({- where: {- projectConnectId_externalId: {- projectConnectId: stripeAccountId,- externalId: dubCustomerId,- },- },- data: {- stripeCustomerId,- },- });- } catch (error) {- // Skip if customer not found (not an error, just a case where the customer doesn't exist on Dub yet)- console.log("Failed to update customer with StripeCustomerId:", error);- return null;- }-}--export async function getSubscriptionProductId({- stripeSubscriptionId,- stripeAccountId,- livemode = true,-}: {- stripeSubscriptionId?: string | null;- stripeAccountId?: string | null;- livemode?: boolean;-}) {- if (!stripeAccountId || !stripeSubscriptionId) {- return null;- }-- try {- const subscription = await stripeAppClient({- livemode,- }).subscriptions.retrieve(stripeSubscriptionId, {- stripeAccount: stripeAccountId,- });- return subscription.items.data[0].price.product as string;- } catch (error) {- console.log("Failed to get subscription price ID:", error);- return null;- }-}--export async function getPromotionCode({- promotionCodeId,- stripeAccountId,- livemode = true,-}: {- promotionCodeId?: string | null;- stripeAccountId?: string | null;- livemode?: boolean;-}) {- if (!stripeAccountId || !promotionCodeId) {- return null;- }-- try {- return await stripeAppClient({- livemode,- }).promotionCodes.retrieve(promotionCodeId, {- stripeAccount: stripeAccountId,- });- } catch (error) {- console.log("Failed to get promotion code:", error);- return null;- }-}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-connected-customer.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-connected-customer.tsnew file mode 100644index 0000000000..45e4dded12--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-connected-customer.ts@@ -0,0 +1,28 @@+import { stripeAppClient } from "@/lib/stripe";++export async function getConnectedCustomer({+ stripeCustomerId,+ stripeAccountId,+ livemode = true,+}: {+ stripeCustomerId?: string | null;+ stripeAccountId?: string | null;+ livemode?: boolean;+}) {+ // if stripeCustomerId or stripeAccountId is not provided, return null+ if (!stripeCustomerId || !stripeAccountId) {+ return null;+ }++ const connectedCustomer = await stripeAppClient({+ livemode,+ }).customers.retrieve(stripeCustomerId, {+ stripeAccount: stripeAccountId,+ });++ if (connectedCustomer.deleted) {+ return null;+ }++ return connectedCustomer;+}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-promotion-code.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-promotion-code.tsnew file mode 100644index 0000000000..4bd492b1f7--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-promotion-code.ts@@ -0,0 +1,26 @@+import { stripeAppClient } from "@/lib/stripe";++export async function getPromotionCode({+ promotionCodeId,+ stripeAccountId,+ livemode = true,+}: {+ promotionCodeId?: string | null;+ stripeAccountId?: string | null;+ livemode?: boolean;+}) {+ if (!stripeAccountId || !promotionCodeId) {+ return null;+ }++ try {+ return await stripeAppClient({+ livemode,+ }).promotionCodes.retrieve(promotionCodeId, {+ stripeAccount: stripeAccountId,+ });+ } catch (error) {+ console.log("Failed to get promotion code:", error);+ return null;+ }+}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-subscription-product-id.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-subscription-product-id.tsnew file mode 100644index 0000000000..90bc607792--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/get-subscription-product-id.ts@@ -0,0 +1,27 @@+import { stripeAppClient } from "@/lib/stripe";++export async function getSubscriptionProductId({+ stripeSubscriptionId,+ stripeAccountId,+ livemode = true,+}: {+ stripeSubscriptionId?: string | null;+ stripeAccountId?: string | null;+ livemode?: boolean;+}) {+ if (!stripeAccountId || !stripeSubscriptionId) {+ return null;+ }++ try {+ const subscription = await stripeAppClient({+ livemode,+ }).subscriptions.retrieve(stripeSubscriptionId, {+ stripeAccount: stripeAccountId,+ });+ return subscription.items.data[0].price.product as string;+ } catch (error) {+ console.log("Failed to get subscription price ID:", error);+ return null;+ }+}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/update-customer-with-stripe-customer-id.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/update-customer-with-stripe-customer-id.tsnew file mode 100644index 0000000000..52bfd38ac5--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/update-customer-with-stripe-customer-id.ts@@ -0,0 +1,36 @@+import { prisma } from "@dub/prisma";++export async function updateCustomerWithStripeCustomerId({+ stripeAccountId,+ dubCustomerExternalId,+ stripeCustomerId,+}: {+ stripeAccountId?: string | null;+ dubCustomerExternalId: string;+ stripeCustomerId?: string | null;+}) {+ // if stripeCustomerId or stripeAccountId is not provided, return null+ // (same logic as in getConnectedCustomer)+ if (!stripeCustomerId || !stripeAccountId) {+ return null;+ }++ try {+ // Update customer with stripeCustomerId if exists – for future events+ return await prisma.customer.update({+ where: {+ projectConnectId_externalId: {+ projectConnectId: stripeAccountId,+ externalId: dubCustomerExternalId,+ },+ },+ data: {+ stripeCustomerId,+ },+ });+ } catch (error) {+ // Skip if customer not found (not an error, just a case where the customer doesn't exist on Dub yet)+ console.log("Failed to update customer with StripeCustomerId:", error);+ return null;+ }+}diff --git a/apps/web/lib/analytics/is-first-conversion.ts b/apps/web/lib/analytics/is-first-conversion.tsindex 9c1db221fd..60fc4f32f4 100644--- a/apps/web/lib/analytics/is-first-conversion.ts+++ b/apps/web/lib/analytics/is-first-conversion.ts@@ -5,7 +5,7 @@ export const isFirstConversion = ({linkId,}: {customer: Pick<Customer, "sales" | "linkId">;- linkId: string;+ linkId?: string;}) => {// if this is the first sale for the customer, it's a first conversionif (customer.sales === 0) {diff --git a/packages/utils/src/constants/regions.ts b/packages/utils/src/constants/regions.tsindex 31afcf8808..44c736fb36 100644--- a/packages/utils/src/constants/regions.ts+++ b/packages/utils/src/constants/regions.ts@@ -3485,3 +3485,7 @@ export const REGIONS: { [key: string]: string } = {};export const REGION_CODES = Object.keys(REGIONS) as [string, ...string[]];++export const REGION_CODE_LOOKUP = Object.fromEntries(+ Object.entries(REGIONS).map(([key, value]) => [value, key]),+) as Record<string, string>;