The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Attribute partner discount codes on Stripe invoice.paid (#3970)
Pedro Ladeira6f9b008563db
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 1627cd2477..c601cc7b12 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@@ -5,7 +5,6 @@ import { detectAndRecordFraudEvent } from "@/lib/api/fraud/detect-record-fraud-eimport { includeTags } from "@/lib/api/links/include-tags";import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";-import { generateRandomName } from "@/lib/names";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";import {@@ -14,22 +13,19 @@ import {recordLead,recordSale,} from "@/lib/tinybird";-import { recordFakeClick } from "@/lib/tinybird/record-fake-click";import { ClickEventTB, LeadEventTB, StripeMode } from "@/lib/types";import { redis } from "@/lib/upstash";import { sendWorkspaceWebhook } from "@/lib/webhook/publish";-import {- transformLeadEventData,- transformSaleEventData,-} from "@/lib/webhook/transform";+import { transformSaleEventData } from "@/lib/webhook/transform";import { prisma } from "@dub/prisma";-import { Customer, Project } from "@dub/prisma/client";-import { COUNTRIES_TO_CONTINENTS, nanoid, pick } from "@dub/utils";+import { Customer } from "@dub/prisma/client";+import { nanoid, pick } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";+import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";import { getCheckoutSessionProductId } from "./utils/get-checkout-session-product-id";import { getConnectedCustomer } from "./utils/get-connected-customer";-import { getPromotionCode } from "./utils/get-promotion-code";+import { incrementLinkLeads } from "./utils/increment-link-leads";import { updateCustomerWithStripeCustomerId } from "./utils/update-customer-with-stripe-customer-id";// Handle event "checkout.session.completed"@@ -194,12 +190,17 @@ export async function checkoutSessionCompleted(if (!customer) {if (promotionCodeId) {- const promoCodeResponse = await attributeViaPromoCode({+ const promoCodeResponse = await attributeViaPromotionCodeId({promotionCodeId,stripeAccountId,workspace,mode,- charge,+ stripeCustomerId,+ customerDetails: {+ name: charge.customer_details?.name,+ email: charge.customer_details?.email,+ address: charge.customer_details?.address,+ },});if (promoCodeResponse) {({ linkId, customer, clickEvent, leadEvent } = promoCodeResponse);@@ -264,12 +265,17 @@ export async function checkoutSessionCompleted(};}} else if (promotionCodeId) {- const promoCodeResponse = await attributeViaPromoCode({+ const promoCodeResponse = await attributeViaPromotionCodeId({promotionCodeId,stripeAccountId,workspace,mode,- charge,+ stripeCustomerId,+ customerDetails: {+ name: charge.customer_details?.name,+ email: charge.customer_details?.email,+ address: charge.customer_details?.address,+ },});if (promoCodeResponse) {({ linkId, customer, clickEvent, leadEvent } = promoCodeResponse);@@ -592,212 +598,3 @@ export async function checkoutSessionCompleted(workspaceId: workspace.id,};}--async function attributeViaPromoCode({- promotionCodeId,- stripeAccountId,- workspace,- mode,- charge,-}: {- promotionCodeId: string;- stripeAccountId: string;- workspace: Pick<- Project,- "id" | "defaultProgramId" | "stripeConnectId" | "webhookEnabled"- >;- mode: StripeMode;- charge: Stripe.Checkout.Session;-}) {- // Find the promotion code for the promotion code id- const promotionCode = await getPromotionCode({- promotionCodeId,- stripeAccountId,- mode,- });-- if (!promotionCode) {- console.log(- `Promotion code ${promotionCodeId} not found in connected account ${stripeAccountId}, 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 ?? "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,- stripeCustomerId: charge.customer as string,- 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,- 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: "Checkout with discount code",- customer_id: customer.id,- metadata: "",- };-- await recordLead(leadEvent);-- // record lead side effects (link stats, partner commissions, workflows, workspace webhook)- waitUntil(- (async () => {- const linkUpdated = await incrementLinkLeads(link.id);-- let createdCommission:- | Awaited<ReturnType<typeof createPartnerCommission>>- | undefined = undefined;-- if (link.programId && link.partnerId) {- createdCommission = await createPartnerCommission({- event: "lead",- programId: link.programId,- partnerId: link.partnerId,- linkId: link.id,- eventId: leadEvent.event_id,- customerId: customer.id,- quantity: 1,- context: {- customer: {- country: customer.country,- },- },- });-- await Promise.allSettled([- executeWorkflows({- trigger: "partnerMetricsUpdated",- reason: "lead",- identity: {- workspaceId: workspace.id,- programId: link.programId,- partnerId: link.partnerId,- },- metrics: {- current: {- leads: 1,- },- },- }),-- syncPartnerLinksStats({- partnerId: link.partnerId,- programId: link.programId,- eventType: "lead",- }),- ]);- }-- await Promise.allSettled([- sendWorkspaceWebhook({- trigger: "lead.created",- workspace,- data: transformLeadEventData({- ...leadEvent,- eventName: "Checkout session completed",- link: linkUpdated,- customer,- partner: createdCommission?.webhookPartner,- metadata: null,- }),- }),-- ...(link.partnerId- ? [- sendPartnerPostback({- partnerId: link.partnerId,- event: "lead.created",- data: {- ...leadEvent,- eventName: "Checkout session completed",- link: linkUpdated,- customer,- },- }),- ]- : []),- ]);- })(),- );-- return {- linkId,- customer,- clickEvent,- leadEvent,- };-}--async function incrementLinkLeads(linkId: string) {- return prisma.link.update({- where: {- id: linkId,- },- data: {- leads: {- increment: 1,- },- lastLeadAt: new Date(),- },- include: includeTags,- });-}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 64bf076b01..cafdb9d842 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@@ -6,6 +6,7 @@ import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-staimport { executeWorkflows } from "@/lib/api/workflows/execute-workflows";import { createPartnerCommission } from "@/lib/partners/create-partner-commission";import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";+import { stripeAppClient } from "@/lib/stripe";import { getLeadEvent, recordSale } from "@/lib/tinybird";import { StripeMode } from "@/lib/types";import { redis } from "@/lib/upstash";@@ -15,6 +16,7 @@ import { prisma } from "@dub/prisma";import { nanoid, pick } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";+import { attributeViaPromotionCodeId } from "./utils/attribute-via-promotion-code-id";import { getConnectedCustomer } from "./utils/get-connected-customer";// Handle event "invoice.paid"@@ -24,9 +26,21 @@ export async function invoicePaid() {const invoice = event.data.object;const stripeAccountId = event.account as string;- const stripeCustomerId = invoice.customer as string;+ const stripeCustomerId = invoice.customer as string | null;const invoiceId = invoice.id;+ if (!invoiceId) {+ return {+ response: "Invoice ID not found, skipping...",+ };+ }++ if (!stripeCustomerId) {+ return {+ response: "Stripe customer ID not found on invoice, skipping...",+ };+ }+// Find customer using stripeCustomerIdlet customer = await prisma.customer.findUnique({where: {@@ -69,11 +83,71 @@ export async function invoicePaid(}}- // if customer is still not found, we skip the event+ // if customer is still not found, try to attribute via partner discount on the invoiceif (!customer) {- return {- response: `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub (nor does the connected customer ${stripeCustomerId} have a valid dubCustomerExternalId), skipping...`,- };+ const workspace = await prisma.project.findUnique({+ where: {+ stripeConnectId: stripeAccountId,+ },+ select: {+ id: true,+ defaultProgramId: true,+ stripeConnectId: true,+ webhookEnabled: true,+ },+ });++ if (!workspace) {+ return {+ response: `Workspace not found for Stripe account ${stripeAccountId}, skipping...`,+ };+ }++ if (!workspace.defaultProgramId) {+ return {+ response: `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub and workspace has no default program, skipping...`,+ workspaceId: workspace.id,+ };+ }++ const { promotionCodeId, error } = await resolvePromotionCodeIdFromInvoice({+ invoiceId,+ stripeAccountId,+ mode,+ });++ if (error) {+ return {+ response: `Failed to resolve promotion code from invoice ${invoiceId}: ${error}`,+ workspaceId: workspace.id,+ };+ }++ if (promotionCodeId) {+ const promoCodeResponse = await attributeViaPromotionCodeId({+ promotionCodeId,+ stripeAccountId,+ workspace,+ mode,+ stripeCustomerId,+ customerDetails: {+ name: invoice.customer_name,+ email: invoice.customer_email,+ address: invoice.customer_address,+ },+ });++ if (promoCodeResponse) {+ customer = promoCodeResponse.customer;+ }+ }++ if (!customer) {+ return {+ response: `Customer with stripeCustomerId ${stripeCustomerId} not found on Dub (nor does the connected customer ${stripeCustomerId} have a valid dubCustomerExternalId or partner discount code on the invoice), skipping...`,+ workspaceId: workspace.id,+ };+ }}// Sale amount excluding tax: use total_excluding_tax only when invoice was paid in full@@ -347,3 +421,57 @@ export async function invoicePaid(workspaceId: customer.projectId,};}++async function resolvePromotionCodeIdFromInvoice({+ invoiceId,+ stripeAccountId,+ mode,+}: {+ invoiceId: string;+ stripeAccountId: string;+ mode: StripeMode;+}): Promise<+ | {+ promotionCodeId: string;+ error: null;+ }+ | {+ promotionCodeId: null;+ error: string;+ }+> {+ const stripe = stripeAppClient({ mode });++ const expandedInvoice = (await stripe.invoices.retrieve(+ invoiceId,+ {+ expand: ["discounts", "discounts.promotion_code"],+ },+ {+ stripeAccount: stripeAccountId,+ },+ )) as Stripe.Invoice & {+ discounts: {+ promotion_code: Stripe.PromotionCode;+ }[];+ };++ if (!expandedInvoice) {+ return {+ promotionCodeId: null,+ error: "Invoice not found", // should never happen, but just in case+ };+ }++ if (!expandedInvoice.discounts || expandedInvoice.discounts.length === 0) {+ return {+ promotionCodeId: null,+ error: "No discounts found on invoice",+ };+ }++ return {+ promotionCodeId: expandedInvoice.discounts[0].promotion_code.id,+ error: null,+ };+}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.tsnew file mode 100644index 0000000000..eb66275a8d--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/attribute-via-promotion-code-id.ts@@ -0,0 +1,236 @@+import { createId } from "@/lib/api/create-id";+import { syncPartnerLinksStats } from "@/lib/api/partners/sync-partner-links-stats";+import { executeWorkflows } from "@/lib/api/workflows/execute-workflows";+import { generateRandomName } from "@/lib/names";+import { createPartnerCommission } from "@/lib/partners/create-partner-commission";+import { sendPartnerPostback } from "@/lib/postback/send-partner-postback";+import { recordLead } from "@/lib/tinybird";+import { recordFakeClick } from "@/lib/tinybird/record-fake-click";+import { StripeMode } from "@/lib/types";+import { redis } from "@/lib/upstash";+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";+import { transformLeadEventData } from "@/lib/webhook/transform";+import { prisma } from "@dub/prisma";+import { Project } from "@dub/prisma/client";+import { COUNTRIES_TO_CONTINENTS, nanoid } from "@dub/utils";+import { waitUntil } from "@vercel/functions";+import type Stripe from "stripe";+import { getPromotionCode } from "./get-promotion-code";+import { incrementLinkLeads } from "./increment-link-leads";++export type PromoCodeCustomerDetails = {+ name?: string | null;+ email?: string | null;+ address?: Pick<Stripe.Address, "country" | "state"> | null;+};++export async function attributeViaPromotionCodeId({+ promotionCodeId,+ stripeAccountId,+ workspace,+ mode,+ stripeCustomerId,+ customerDetails,+}: {+ promotionCodeId: string; // must be Stripe's promotion code ID `promo_xxx`, not the actual promo code+ stripeAccountId: string;+ workspace: Pick<+ Project,+ "id" | "defaultProgramId" | "stripeConnectId" | "webhookEnabled"+ >;+ mode: StripeMode;+ stripeCustomerId: string;+ customerDetails: PromoCodeCustomerDetails;+}) {+ // Find the promotion code for the promotion code id+ const promotionCode = await getPromotionCode({+ promotionCodeId,+ stripeAccountId,+ mode,+ });++ if (!promotionCode) {+ console.log(+ `Promotion code ${promotionCodeId} not found in connected account ${stripeAccountId}, 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;+ const customerAddress = customerDetails.address;+ const customerCountry = customerAddress?.country?.toUpperCase();++ // Record a fake click for this event+ const clickEvent = await recordFakeClick({+ link,+ customer: {+ continent: customerCountry+ ? COUNTRIES_TO_CONTINENTS[customerCountry] ?? "Unknown"+ : "Unknown",+ country: customerCountry ?? "Unknown",+ region: customerAddress?.state ?? "Unknown",+ },+ });++ let customer: Awaited<ReturnType<typeof prisma.customer.create>>;+ try {+ customer = await prisma.customer.create({+ data: {+ id: createId({ prefix: "cus_" }),+ name:+ customerDetails.name || customerDetails.email || generateRandomName(),+ email: customerDetails.email,+ externalId: clickEvent.click_id,+ stripeCustomerId,+ linkId: clickEvent.link_id,+ clickId: clickEvent.click_id,+ clickedAt: new Date(clickEvent.timestamp + "Z"),+ country: customerAddress?.country,+ projectId: workspace.id,+ projectConnectId: workspace.stripeConnectId,+ },+ });+ } catch (error) {+ // a concurrent webhook may have created the customer first (unique stripeCustomerId)+ if (error.code === "P2002") {+ console.log(+ `Customer with stripeCustomerId ${stripeCustomerId} was created concurrently, skipping promo code attribution...`,+ );+ return null;+ }+ throw error;+ }++ // Prepare the payload for the lead event+ const { timestamp, ...rest } = clickEvent;++ const leadEvent = {+ ...rest,+ workspace_id: clickEvent.workspace_id || customer.projectId,+ event_id: nanoid(16),+ event_name: "Attributed via discount code",+ customer_id: customer.id,+ metadata: "",+ };++ await recordLead(leadEvent);++ // cache lead event in Redis because the ingested event is not available immediately on Tinybird+ // (the sale recording right after this relies on reading the lead event back)+ await redis.set(`leadCache:${customer.id}`, leadEvent, {+ ex: 60 * 5,+ });++ // record lead side effects (link stats, partner commissions, workflows, workspace webhook)+ waitUntil(+ (async () => {+ const linkUpdated = await incrementLinkLeads(link.id);++ let createdCommission:+ | Awaited<ReturnType<typeof createPartnerCommission>>+ | undefined = undefined;++ if (link.programId && link.partnerId) {+ createdCommission = await createPartnerCommission({+ event: "lead",+ programId: link.programId,+ partnerId: link.partnerId,+ linkId: link.id,+ eventId: leadEvent.event_id,+ customerId: customer.id,+ quantity: 1,+ context: {+ customer: {+ country: customer.country,+ },+ },+ });++ await Promise.allSettled([+ executeWorkflows({+ trigger: "partnerMetricsUpdated",+ reason: "lead",+ identity: {+ workspaceId: workspace.id,+ programId: link.programId,+ partnerId: link.partnerId,+ },+ metrics: {+ current: {+ leads: 1,+ },+ },+ }),++ syncPartnerLinksStats({+ partnerId: link.partnerId,+ programId: link.programId,+ eventType: "lead",+ }),+ ]);+ }++ await Promise.allSettled([+ sendWorkspaceWebhook({+ trigger: "lead.created",+ workspace,+ data: transformLeadEventData({+ ...leadEvent,+ link: linkUpdated,+ customer,+ partner: createdCommission?.webhookPartner,+ metadata: null,+ }),+ }),++ ...(link.partnerId+ ? [+ sendPartnerPostback({+ partnerId: link.partnerId,+ event: "lead.created",+ data: {+ ...leadEvent,+ link: linkUpdated,+ customer,+ },+ }),+ ]+ : []),+ ]);+ })(),+ );++ return {+ linkId,+ customer,+ clickEvent,+ leadEvent,+ };+}diff --git a/apps/web/app/(ee)/api/stripe/integration/webhook/utils/increment-link-leads.ts b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/increment-link-leads.tsnew file mode 100644index 0000000000..2d8d54f07b--- /dev/null+++ b/apps/web/app/(ee)/api/stripe/integration/webhook/utils/increment-link-leads.ts@@ -0,0 +1,17 @@+import { includeTags } from "@/lib/api/links/include-tags";+import { prisma } from "@dub/prisma";++export async function incrementLinkLeads(linkId: string) {+ return prisma.link.update({+ where: {+ id: linkId,+ },+ data: {+ leads: {+ increment: 1,+ },+ lastLeadAt: new Date(),+ },+ include: includeTags,+ });+}diff --git a/apps/web/lib/actions/partners/create-manual-commission.ts b/apps/web/lib/actions/partners/create-manual-commission.tsindex 1fe49257ee..120690ca81 100644--- a/apps/web/lib/actions/partners/create-manual-commission.ts+++ b/apps/web/lib/actions/partners/create-manual-commission.ts@@ -208,6 +208,8 @@ export const createManualCommissionAction = authActionClientclickId = nanoid(16);clickedAt = new Date(lastLeadAt.getTime() - 5 * 60 * 1000);+ const customerCountry = customer.country?.toUpperCase();+const generatedClickEvent = recordClickZodSchema.parse({timestamp: clickedAt.toISOString(),identity_hash: customer.externalId || customer.id,@@ -215,9 +217,10 @@ export const createManualCommissionAction = authActionClientlink_id: link.id,url: link.url,ip: "127.0.0.1",- continent: customer.country- ? COUNTRIES_TO_CONTINENTS[customer.country.toUpperCase()] || ""- : "",+ country: customerCountry ?? "Unknown",+ continent: customerCountry+ ? COUNTRIES_TO_CONTINENTS[customerCountry] ?? "Unknown"+ : "Unknown",});tbEventsToRecord.push(() => recordClickZod(generatedClickEvent));diff --git a/apps/web/lib/integrations/shopify/process-order.ts b/apps/web/lib/integrations/shopify/process-order.tsindex c7ed6f81d3..80dc1e7ddf 100644--- a/apps/web/lib/integrations/shopify/process-order.ts+++ b/apps/web/lib/integrations/shopify/process-order.ts@@ -88,14 +88,15 @@ export async function attributeViaDiscountCode({const { customer: orderCustomer, billing_address: billingAddress } =orderSchema.parse(event);+ const billingAddressCountry = billingAddress?.country_code?.toUpperCase();// Record a fake click for this eventconst clickEvent = await recordFakeClick({link,customer: {- continent: billingAddress?.country_code- ? COUNTRIES_TO_CONTINENTS[billingAddress.country_code]+ continent: billingAddressCountry+ ? COUNTRIES_TO_CONTINENTS[billingAddressCountry] ?? "Unknown": "Unknown",- country: billingAddress?.country_code ?? "Unknown",+ country: billingAddressCountry ?? "Unknown",region: billingAddress?.province ?? "Unknown",},});