Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set referral discount via Dub Customer object #1829

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
18 changes: 17 additions & 1 deletion apps/web/app/api/workspaces/[idOrSlug]/billing/upgrade/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { withWorkspace } from "@/lib/auth";
import { getDubCustomer } from "@/lib/dub";
import { stripe } from "@/lib/stripe";
import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
Expand Down Expand Up @@ -46,6 +47,10 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
});
return NextResponse.json({ url });
} else {
const customer = await getDubCustomer(session.user.id);
const isReferral =
customer?.link?.programId === "prog_d8pl69xXCv4AoHNT281pHQdo";

// For both new users and users with canceled subscriptions
const stripeSession = await stripe.checkout.sessions.create({
...(workspace.stripeId
Expand All @@ -64,7 +69,18 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
success_url: `${APP_DOMAIN}/${workspace.slug}?${onboarding ? "onboarded" : "upgraded"}=true&plan=${plan}&period=${period}`,
cancel_url: baseUrl,
line_items: [{ price: prices.data[0].id, quantity: 1 }],
allow_promotion_codes: true,
...(isReferral
? {
discounts: [
{
coupon:
process.env.NODE_ENV === "production"
? "pEVpzGQE"
: "k8v8KtqG",
},
],
}
: { allow_promotion_codes: true }),
automatic_tax: {
enabled: true,
},
Expand Down
11 changes: 11 additions & 0 deletions apps/web/lib/dub.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
import { Dub } from "dub";

export const dub = new Dub();

// fetch Dub customer using their external ID (ID in our database)
export const getDubCustomer = async (userId: string) => {
try {
return await dub.customers.get({
id: `ext_${userId}`,
});
} catch (error) {
return null;
}
};
2 changes: 1 addition & 1 deletion apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
"concurrently": "^8.0.1",
"csv-parse": "^5.5.6",
"date-fns": "^3.6.0",
"dub": "^0.46.1",
"dub": "^0.46.8",
"framer-motion": "^10.16.16",
"fuse.js": "^6.6.2",
"geist": "^1.3.1",
Expand Down
12 changes: 4 additions & 8 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading