The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
wip handle coupon in checkoutSessionCompleted
Kiran K1815f7334ca0
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 caae0481bf..836e83e2a5 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@@ -20,7 +20,7 @@ import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";import { prisma } from "@dub/prisma";import { Customer } from "@dub/prisma/client";-import { nanoid } from "@dub/utils";+import { linkConstructorSimple, nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";import {@@ -200,6 +200,78 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {);linkId = leadEvent.link_id;+ } else if (charge.discounts && charge.discounts.length > 0) {+ // Handle promotion code tracking for coupon-based attribution+ // When a charge has discounts, we can attribute the sale to a partner+ // based on the promotion code used during checkout++ const workspace = await prisma.project.findUnique({+ where: {+ stripeConnectId: stripeAccountId,+ },+ select: {+ defaultProgram: {+ select: {+ domain: true,+ couponCodeTrackingEnabledAt: true,+ },+ },+ },+ });++ if (!workspace) {+ return `Workspace with stripeConnectId ${stripeAccountId} not found, skipping...`;+ }++ if (!workspace.defaultProgram) {+ return `Workspace with stripeConnectId ${stripeAccountId} has no program, skipping...`;+ }++ const { defaultProgram: program } = workspace;++ if (!program.couponCodeTrackingEnabledAt) {+ return `Workspace with stripeConnectId ${stripeAccountId} has no coupon code tracking enabled, skipping...`;+ }++ if (!program.domain) {+ return `Workspace with stripeConnectId ${stripeAccountId} has no domain for program, skipping...`;+ }++ const promotionCodes = charge.discounts.map(+ ({ promotion_code }) => promotion_code,+ );++ if (promotionCodes.length === 0) {+ return "No promotion codes found in Stripe checkout session, skipping...";+ }++ const promotionCode = promotionCodes[0] as Stripe.PromotionCode;++ const link = await prisma.link.findUnique({+ where: {+ domain_key: {+ domain: program.domain,+ key: promotionCode.code,+ },+ },+ select: {+ id: true,+ },+ });++ if (!link) {+ return `Link ${linkConstructorSimple({+ domain: program.domain,+ key: promotionCode.code,+ })} not found, skipping...`;+ }++ linkId = link.id;++ // let customer: Customer | null = null;+ // let existingCustomer: Customer | null = null;+ // let clickEvent: z.infer<typeof clickEventSchemaTB> | null = null;+ // let leadEvent: z.infer<typeof leadEventSchemaTB>;} else {return "No dubCustomerId or stripeCustomerId found in Stripe checkout session metadata, skipping...";}diff --git a/apps/web/lib/stripe/create-promotion-code.ts b/apps/web/lib/stripe/create-promotion-code.tsnew file mode 100644index 0000000000..30fa85e60a--- /dev/null+++ b/apps/web/lib/stripe/create-promotion-code.ts@@ -0,0 +1,40 @@+import { Link } from "@prisma/client";+import { stripeAppClient } from ".";++export async function createPromotionCode({+ couponId,+ link,+ stripeAccount,+}: {+ couponId: string;+ link: Pick<Link, "key" | "partnerId">;+ stripeAccount: string;+}) {+ const stripe = stripeAppClient({+ livemode: process.env.NODE_ENV === "production",+ });++ try {+ const promotionCode = await stripe.promotionCodes.create(+ {+ coupon: couponId,+ code: link.key,+ metadata: {+ partnerId: link.partnerId,+ },+ },+ {+ stripeAccount,+ },+ );++ console.log(+ `Promotion code ${promotionCode.id} created for link ${link.key} for account ${stripeAccount}`,+ );++ return promotionCode;+ } catch (error) {+ console.error("Failed to create promotion code", error);+ throw error;+ }+}diff --git a/apps/web/lib/zod/schemas/programs.ts b/apps/web/lib/zod/schemas/programs.tsindex 5785823c5d..e2802df3ba 100644--- a/apps/web/lib/zod/schemas/programs.ts+++ b/apps/web/lib/zod/schemas/programs.ts@@ -27,6 +27,7 @@ export const ProgramSchema = z.object({linkParameter: z.string().nullish(),landerPublishedAt: z.date().nullish(),autoApprovePartnersEnabledAt: z.date().nullish(),+ couponCodeTrackingEnabledAt: z.date().nullish(),rewards: z.array(RewardSchema).nullish(),discounts: z.array(DiscountSchema).nullish(),defaultFolderId: z.string().nullable(),diff --git a/apps/web/scripts/stripe/coupon.ts b/apps/web/scripts/stripe/coupon.tsnew file mode 100644index 0000000000..0f0eef6c98--- /dev/null+++ b/apps/web/scripts/stripe/coupon.ts@@ -0,0 +1,58 @@+import { stripeAppClient } from "@/lib/stripe";+import "dotenv-flow/config";++// Just for testing purposes+async function main() {+ const stripeApp = stripeAppClient({+ livemode: false,+ });++ const stripeAccount = "acct_1QVcu12ULJbggj84";++ // Create a coupon+ const coupon = await stripeApp.coupons.create(+ {+ name: "Coupon 1",+ percent_off: 30,+ duration: "repeating",+ duration_in_months: 12,+ },+ {+ stripeAccount,+ },+ );++ console.log(coupon);++ // List all coupons+ const coupons = await stripeApp.coupons.list({+ stripeAccount,+ });++ console.log(coupons);++ // Create a promotion code+ const promotionCode = await stripeApp.promotionCodes.create(+ {+ coupon: "eL9nAqZy",+ code: "TEST_CODE",+ metadata: {+ partnerId: "123",+ },+ },+ {+ stripeAccount,+ },+ );++ console.log(promotionCode);++ // List all promotion codes+ const promotionCodes = await stripeApp.promotionCodes.list({+ stripeAccount,+ });++ console.log(promotionCodes);+}++main();diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prismaindex 89602ade06..6f13347cbc 100644--- a/packages/prisma/schema/program.prisma+++ b/packages/prisma/schema/program.prisma@@ -48,11 +48,13 @@ model Program {linkStructure LinkStructure @default(short)linkParameter String? // null for SHORT, "via" for QUERY, "refer" for PATHautoApprovePartnersEnabledAt DateTime?+ couponCodeTrackingEnabledAt DateTime?createdAt DateTime @default(now())updatedAt DateTime @updatedAtworkspace Project @relation(fields: [workspaceId], references: [id])primaryDomain Domain? @relation(fields: [domain], references: [slug], onUpdate: Cascade)+ defaultFor Project? @relation("defaultProgram")partners ProgramEnrollment[]payouts Payout[]invoices Invoice[]diff --git a/packages/prisma/schema/workspace.prisma b/packages/prisma/schema/workspace.prismaindex 78ae32bb7a..7073e394dc 100644--- a/packages/prisma/schema/workspace.prisma+++ b/packages/prisma/schema/workspace.prisma@@ -57,6 +57,7 @@ model Project {domains Domain[]tags Tag[]programs Program[]+ defaultProgram Program? @relation("defaultProgram", fields: [defaultProgramId], references: [id], onDelete: NoAction, onUpdate: NoAction)invoices Invoice[]customers Customer[]defaultDomains DefaultDomains[]