Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add support for link-based coupon codes with Stripe integration

Kiran K7c87ce81963d
diff --git a/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts b/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
index b34f601adc..0ee4495212 100644
--- a/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
+++ b/apps/web/app/(ee)/api/cron/links/invalidate-for-discounts/route.ts
@@ -8,9 +8,15 @@ import { z } from "zod";
export const dynamic = "force-dynamic";
const schema = z.object({
- programId: z.string(),
discountId: z.string(),
- isDefault: z.boolean(),
+ programId: z
+ .string()
+ .optional()
+ .describe("Must be passed for discount-deleted action"),
+ isDefault: z
+ .boolean()
+ .optional()
+ .describe("Must be passed for discount-deleted action"),
action: z.enum(["discount-created", "discount-updated", "discount-deleted"]),
});
diff --git a/apps/web/lib/actions/partners/create-discount.ts b/apps/web/lib/actions/partners/create-discount.ts
index 44bbca3348..f259635044 100644
--- a/apps/web/lib/actions/partners/create-discount.ts
+++ b/apps/web/lib/actions/partners/create-discount.ts
@@ -5,10 +5,12 @@ import { createId } from "@/lib/api/create-id";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { qstash } from "@/lib/cron";
+import { createStripeCoupon } from "@/lib/stripe/create-coupon";
import { createDiscountSchema } from "@/lib/zod/schemas/discount";
import { prisma } from "@dub/prisma";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
+import Stripe from "stripe";
import { authActionClient } from "../safe-action";
export const createDiscountAction = authActionClient
@@ -24,6 +26,7 @@ export const createDiscountAction = authActionClient
isDefault,
includedPartnerIds,
excludedPartnerIds,
+ provider,
} = parsedInput;
includedPartnerIds = includedPartnerIds || [];
@@ -81,6 +84,32 @@ export const createDiscountAction = authActionClient
}
}
+ // Create Stripe coupon for link-based coupon codes
+ let stripeCoupon: Stripe.Coupon | null = null;
+
+ if (provider === "stripe") {
+ if (!workspace.stripeConnectId) {
+ throw new Error(
+ "Make sure you have connected your Stripe account to your workspace to create a coupon.",
+ );
+ }
+
+ const response = await createStripeCoupon({
+ coupon: {
+ amount,
+ type,
+ maxDuration: maxDuration ?? null,
+ },
+ stripeConnectId: workspace.stripeConnectId,
+ });
+
+ if (!response) {
+ throw new Error("Failed to create a coupon on Stripe.");
+ }
+
+ stripeCoupon = response;
+ }
+
const discount = await prisma.discount.create({
data: {
id: createId({ prefix: "disc_" }),
@@ -88,9 +117,10 @@ export const createDiscountAction = authActionClient
amount,
type,
maxDuration,
- couponId,
+ couponId: stripeCoupon?.id ?? couponId,
couponTestId,
default: isDefault,
+ provider,
},
});
@@ -123,9 +153,7 @@ export const createDiscountAction = authActionClient
qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
body: {
- programId,
discountId: discount.id,
- isDefault,
action: "discount-created",
},
}),
diff --git a/apps/web/lib/actions/partners/delete-discount.ts b/apps/web/lib/actions/partners/delete-discount.ts
index 99099c846a..4ded83f04c 100644
--- a/apps/web/lib/actions/partners/delete-discount.ts
+++ b/apps/web/lib/actions/partners/delete-discount.ts
@@ -5,6 +5,7 @@ import { getDiscountOrThrow } from "@/lib/api/partners/get-discount-or-throw";
import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";
import { getProgramOrThrow } from "@/lib/api/programs/get-program-or-throw";
import { qstash } from "@/lib/cron";
+import { deleteStripeCoupon } from "@/lib/stripe/delete-coupon";
import { redis } from "@/lib/upstash";
import { prisma } from "@dub/prisma";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
@@ -25,7 +26,7 @@ export const deleteDiscountAction = authActionClient
const programId = getDefaultProgramIdOrThrow(workspace);
- const program = await getProgramOrThrow({
+ await getProgramOrThrow({
workspaceId: workspace.id,
programId,
});
@@ -127,6 +128,14 @@ export const deleteDiscountAction = authActionClient
},
],
}),
+
+ // Remove the Stripe coupon if it exists
+ discount.provider === "stripe"
+ ? deleteStripeCoupon({
+ coupon: discount,
+ stripeConnectId: workspace.stripeConnectId,
+ })
+ : Promise.resolve(),
]),
);
}
diff --git a/apps/web/lib/actions/partners/update-discount.ts b/apps/web/lib/actions/partners/update-discount.ts
index 3c2f388cc6..31460f090f 100644
--- a/apps/web/lib/actions/partners/update-discount.ts
+++ b/apps/web/lib/actions/partners/update-discount.ts
@@ -62,55 +62,64 @@ export const updateDiscountAction = authActionClient
}
}
- const updatedDiscount = await prisma.discount.update({
- where: {
- id: discountId,
- },
- data: {
- amount,
- type,
- maxDuration,
- couponId,
- couponTestId,
- },
- });
+ let updatedDiscount: Discount | undefined = undefined;
+
+ // Stripe doesn't support updating the standard coupon fields
+ if (discount.provider !== "stripe") {
+ updatedDiscount = await prisma.discount.update({
+ where: {
+ id: discountId,
+ },
+ data: {
+ amount,
+ type,
+ maxDuration,
+ couponId,
+ couponTestId,
+ },
+ });
+ }
// Update partners associated with the discount
- if (updatedDiscount.default) {
+ if (discount.default) {
await updateDefaultDiscountPartners({
- discount: updatedDiscount,
+ discountId,
+ programId,
partnerIds: excludedPartnerIds,
});
} else {
await updateNonDefaultDiscountPartners({
- discount: updatedDiscount,
+ discountId,
+ programId,
partnerIds: includedPartnerIds,
});
}
waitUntil(
(async () => {
- const shouldExpireCache = !deepEqual(
- {
- amount: discount.amount,
- type: discount.type,
- maxDuration: discount.maxDuration,
- },
- {
- amount: updatedDiscount.amount,
- type: updatedDiscount.type,
- maxDuration: updatedDiscount.maxDuration,
- },
- );
+ let shouldExpireCache = false;
+
+ if (updatedDiscount) {
+ shouldExpireCache = !deepEqual(
+ {
+ amount: discount.amount,
+ type: discount.type,
+ maxDuration: discount.maxDuration,
+ },
+ {
+ amount: updatedDiscount.amount,
+ type: updatedDiscount.type,
+ maxDuration: updatedDiscount.maxDuration,
+ },
+ );
+ }
await Promise.allSettled([
shouldExpireCache
? qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/invalidate-for-discounts`,
body: {
- programId,
discountId,
- isDefault: updatedDiscount.default,
action: "discount-updated",
},
})
@@ -137,15 +146,17 @@ export const updateDiscountAction = authActionClient
// Update default discount
const updateDefaultDiscountPartners = async ({
- discount,
+ discountId,
+ programId,
partnerIds,
}: {
- discount: Discount;
+ discountId: string;
+ programId: string;
partnerIds: string[]; // Excluded partners
}) => {
const existingPartners = await prisma.programEnrollment.findMany({
where: {
- programId: discount.programId,
+ programId,
discountId: null,
},
select: {
@@ -167,7 +178,7 @@ const updateDefaultDiscountPartners = async ({
if (excludedPartnerIds.length > 0) {
await prisma.programEnrollment.updateMany({
where: {
- programId: discount.programId,
+ programId,
partnerId: {
in: excludedPartnerIds,
},
@@ -182,14 +193,14 @@ const updateDefaultDiscountPartners = async ({
if (includedPartnerIds.length > 0) {
await prisma.programEnrollment.updateMany({
where: {
- programId: discount.programId,
+ programId,
discountId: null,
partnerId: {
in: includedPartnerIds,
},
},
data: {
- discountId: discount.id,
+ discountId,
},
});
}
@@ -197,16 +208,18 @@ const updateDefaultDiscountPartners = async ({
// Update non-default discount
const updateNonDefaultDiscountPartners = async ({
- discount,
+ discountId,
+ programId,
partnerIds,
}: {
- discount: Discount;
+ discountId: string;
+ programId: string;
partnerIds: string[]; // Included partners
}) => {
const existingPartners = await prisma.programEnrollment.findMany({
where: {
- programId: discount.programId,
- discountId: discount.id,
+ programId,
+ discountId,
},
select: {
partnerId: true,
@@ -227,13 +240,13 @@ const updateNonDefaultDiscountPartners = async ({
if (includedPartnerIds.length > 0) {
await prisma.programEnrollment.updateMany({
where: {
- programId: discount.programId,
+ programId,
partnerId: {
in: includedPartnerIds,
},
},
data: {
- discountId: discount.id,
+ discountId,
},
});
}
@@ -242,15 +255,15 @@ const updateNonDefaultDiscountPartners = async ({
if (excludedPartnerIds.length > 0) {
const defaultDiscount = await prisma.discount.findFirst({
where: {
- programId: discount.programId,
+ programId,
default: true,
},
});
await prisma.programEnrollment.updateMany({
where: {
- programId: discount.programId,
- discountId: discount.id,
+ programId,
+ discountId,
partnerId: {
in: excludedPartnerIds,
},
diff --git a/apps/web/lib/api/audit-logs/schemas.ts b/apps/web/lib/api/audit-logs/schemas.ts
index 116324f82f..460125cde0 100644
--- a/apps/web/lib/api/audit-logs/schemas.ts
+++ b/apps/web/lib/api/audit-logs/schemas.ts
@@ -105,7 +105,7 @@ export const auditLogTarget = z.union([
amount: true,
maxDuration: true,
couponId: true,
- }),
+ }).optional(),
}),
z.object({
diff --git a/apps/web/lib/stripe/create-coupon.ts b/apps/web/lib/stripe/create-coupon.ts
new file mode 100644
index 0000000000..97e5f3a6b5
--- /dev/null
+++ b/apps/web/lib/stripe/create-coupon.ts
@@ -0,0 +1,50 @@
+import { Discount } from "@prisma/client";
+import { stripeAppClient } from ".";
+
+// Create a coupon on Stripe for connected accounts
+export async function createStripeCoupon({
+ coupon,
+ stripeConnectId,
+}: {
+ coupon: Pick<Discount, "amount" | "type" | "maxDuration">;
+ stripeConnectId: string | null;
+}) {
+ if (!stripeConnectId) {
+ console.error(
+ "stripeConnectId not found for the workspace. Stripe coupon creation skipped.",
+ );
+ return;
+ }
+
+ const stripe = stripeAppClient({
+ livemode: process.env.NODE_ENV === "production",
+ });
+
+ const { type, amount, maxDuration } = coupon;
+
+ const duration =
+ maxDuration === null ? "forever" : maxDuration === 1 ? "once" : "repeating";
+
+ try {
+ return await stripe.coupons.create(
+ {
+ currency: "usd",
+ duration,
+ ...(duration === "repeating" && {
+ duration_in_months: maxDuration!,
+ }),
+ ...(type === "percentage"
+ ? { percent_off: amount }
+ : { amount_off: amount }),
+ },
+ {
+ stripeAccount: stripeConnectId,
+ },
+ );
+ } catch (error) {
+ console.error(
+ `Failed to create Stripe coupon for ${stripeConnectId}: ${error}`,
+ );
+ return null;
+ }
+}
diff --git a/apps/web/lib/stripe/delete-coupon.ts b/apps/web/lib/stripe/delete-coupon.ts
new file mode 100644
index 0000000000..413d566474
--- /dev/null
+++ b/apps/web/lib/stripe/delete-coupon.ts
@@ -0,0 +1,42 @@
+import { Discount } from "@prisma/client";
+import { stripeAppClient } from ".";
+
+// Delete a coupon on Stripe for connected accounts
+export async function deleteStripeCoupon({
+ coupon,
+ stripeConnectId,
+}: {
+ coupon: Pick<Discount, "couponId">;
+ stripeConnectId: string | null;
+}) {
+ if (!stripeConnectId) {
+ console.error(
+ "stripeConnectId not found for the workspace. Stripe coupon creation skipped.",
+ );
+ return;
+ }
+
+ const { couponId } = coupon;
+
+ if (!couponId) {
+ console.error(
+ "couponId not found for the discount. Stripe coupon deletion skipped.",
+ );
+ return;
+ }
+
+ const stripe = stripeAppClient({
+ livemode: process.env.NODE_ENV === "production",
+ });
+
+ try {
+ return await stripe.coupons.del(couponId, {
+ stripeAccount: stripeConnectId,
+ });
+ } catch (error) {
+ console.error(
+ `Failed to delete Stripe coupon for ${stripeConnectId}: ${error}`,
+ );
+ return null;
+ }
+}
diff --git a/apps/web/lib/zod/schemas/discount.ts b/apps/web/lib/zod/schemas/discount.ts
index bb3fabc8d4..b793240d3c 100644
--- a/apps/web/lib/zod/schemas/discount.ts
+++ b/apps/web/lib/zod/schemas/discount.ts
@@ -7,11 +7,12 @@ export const DiscountSchema = z.object({
amount: z.number(),
type: z.nativeEnum(RewardStructure),
maxDuration: z.number().nullable(),
- description: z.string().nullish(),
couponId: z.string().nullable(),
couponTestId: z.string().nullable(),
- partnersCount: z.number().nullish(),
default: z.boolean(),
+ provider: z.enum(["stripe"]).nullable(),
+ description: z.string().nullish(),
+ partnersCount: z.number().nullish(),
});
export const DiscountSchemaWithDeprecatedFields = DiscountSchema.extend({
@@ -38,6 +39,7 @@ export const createDiscountSchema = z.object({
.array(z.string())
.nullish()
.describe("Only applicable for default discounts"),
+ provider: z.enum(["stripe"]).nullish(),
});
export const updateDiscountSchema = createDiscountSchema.extend({
diff --git a/packages/prisma/schema/discount.prisma b/packages/prisma/schema/discount.prisma
index c0b38b896e..25bacaddc8 100644
--- a/packages/prisma/schema/discount.prisma
+++ b/packages/prisma/schema/discount.prisma
@@ -6,13 +6,14 @@ model Discount {
maxDuration Int? // in months (0 -> not recurring, null -> lifetime)
description String?
couponId String?
- couponTestId String?
+ couponTestId String?
default Boolean @default(false)
+ provider String? // coupon provider for link-based coupon code tracking
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
programEnrollments ProgramEnrollment[]
program Program @relation("ProgramDiscounts", fields: [programId], references: [id], onDelete: Cascade, onUpdate: Cascade)
-
+
@@index(programId)
}
diff --git a/packages/prisma/schema/program.prisma b/packages/prisma/schema/program.prisma
index 6f13347cbc..391f01c6b8 100644
--- a/packages/prisma/schema/program.prisma
+++ b/packages/prisma/schema/program.prisma
@@ -77,6 +77,7 @@ model ProgramEnrollment {
clickRewardId String?
leadRewardId String?
saleRewardId String?
+ couponId String? // Stripe coupon ID for link-based coupon code tracking
applicationId String? @unique
status ProgramEnrollmentStatus @default(pending)
totalCommissions Int @default(0) // total commissions earned by the partner (in cents)
diff --git a/packages/stripe-app/stripe-app.json b/packages/stripe-app/stripe-app.json
index 88cb33baf1..5fc6843c93 100644
--- a/packages/stripe-app/stripe-app.json
+++ b/packages/stripe-app/stripe-app.json
@@ -40,6 +40,14 @@
"permission": "secret_write",
"purpose": "Allows storing Dub access tokens in Stripe for an account."
},
+ {
+ "permission": "coupon_write",
+ "purpose": "Allows Dub to create coupons for an account."
+ },
+ {
+ "permission": "coupon_read",
+ "purpose": "Allows Dub to read coupons for an account."
+ },
{
"permission": "promotion_code_write",
"purpose": "Allows Dub to create promotion codes for an account."
@@ -77,4 +85,4 @@
],
"stripe_api_access_type": "oauth",
"distribution_type": "public"
-}
\ No newline at end of file
+}