Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: improve dub discount

Marc Seitze4db98e88ba0
diff --git a/lib/dub.ts b/lib/dub.ts
index 59acf19b..c0e172a0 100644
--- a/lib/dub.ts
+++ b/lib/dub.ts
@@ -3,3 +3,22 @@ import { Dub } from "dub";
export const dub = new Dub({
token: process.env.DUB_API_KEY,
});
+
+export async function getDubDiscountForExternalUserId(externalId: string) {
+ try {
+ const customers = await dub.customers.list({
+ externalId,
+ includeExpandedFields: true,
+ });
+ const first = customers[0];
+ const couponId =
+ process.env.NODE_ENV !== "production" && first?.discount?.couponTestId
+ ? first.discount.couponTestId
+ : first?.discount?.couponId;
+
+ return couponId ? { discounts: [{ coupon: couponId }] } : null;
+ } catch (err) {
+ console.warn("Skipping Dub discount due to API error", err);
+ return null; // degrade gracefully; don't block checkout
+ }
+}
diff --git a/pages/api/teams/[teamId]/billing/upgrade.ts b/pages/api/teams/[teamId]/billing/upgrade.ts
index 10f3bc61..db2e97dd 100644
--- a/pages/api/teams/[teamId]/billing/upgrade.ts
+++ b/pages/api/teams/[teamId]/billing/upgrade.ts
@@ -6,7 +6,7 @@ import { waitUntil } from "@vercel/functions";
import { getServerSession } from "next-auth/next";
import { identifyUser, trackAnalytics } from "@/lib/analytics";
-import { dub } from "@/lib/dub";
+import { dub, getDubDiscountForExternalUserId } from "@/lib/dub";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
@@ -77,10 +77,7 @@ export default async function handle(
}),
};
- const customer = await dub.customers.list({
- externalId: userId, // their user ID within your app
- includeExpandedFields: true,
- });
+ const dubDiscount = await getDubDiscountForExternalUserId(userId);
const stripe = stripeInstance(oldAccount);
if (team.stripeId) {
@@ -119,18 +116,7 @@ export default async function handle(
mode: "subscription",
allow_promotion_codes: true,
client_reference_id: teamId,
- ...(customer.length > 0 &&
- customer[0].discount?.couponId && {
- discounts: [
- {
- coupon:
- process.env.NODE_ENV !== "production" &&
- customer[0].discount.couponTestId
- ? customer[0].discount.couponTestId
- : customer[0].discount.couponId,
- },
- ],
- }),
+ ...dubDiscount,
metadata: {
dubCustomerId: userId,
},