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.

some stripe magic

Steven Tey6aa0a9bf6694
diff --git a/apps/web/app/api/callback/stripe/route.ts b/apps/web/app/api/callback/stripe/route.ts
index 4190bbcba9..7bf82a13c4 100644
--- a/apps/web/app/api/callback/stripe/route.ts
+++ b/apps/web/app/api/callback/stripe/route.ts
@@ -55,7 +55,7 @@ export const POST = async (req: Request) => {
if (!plan) {
await log({
- message: "Invalid price ID in checkout.session.completed event",
+ message: `Invalid price ID in checkout.session.completed event: ${priceId}`,
type: "errors",
});
return;
@@ -127,7 +127,7 @@ export const POST = async (req: Request) => {
if (!plan) {
await log({
- message: "Invalid price ID in customer.subscription.updated event",
+ message: `Invalid price ID in customer.subscription.updated event: ${priceId}`,
type: "errors",
});
return;
diff --git a/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts b/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts
index 037be7daaa..a979853c37 100644
--- a/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts
+++ b/apps/web/app/api/projects/[slug]/billing/upgrade/route.ts
@@ -3,34 +3,61 @@ import { stripe } from "@/lib/stripe";
import { APP_DOMAIN } from "@dub/utils";
import { NextResponse } from "next/server";
-export const POST = withAuth(async ({ searchParams, project, session }) => {
- const { plan } = searchParams;
+export const POST = withAuth(async ({ req, project, session }) => {
+ let { plan, period, baseUrl } = await req.json();
- if (!plan) {
- return new Response("Missing plan lookup key", { status: 400 });
+ if (!plan || !period) {
+ return new Response("Invalid plan or period", { status: 400 });
}
+ plan = plan.replace(" ", "+");
+
const prices = await stripe.prices.list({
- lookup_keys: [plan],
+ lookup_keys: [`${plan}_${period}`],
});
- const stripeSession = await stripe.checkout.sessions.create({
- customer_email: session.user.email,
- billing_address_collection: "required",
- success_url: `${APP_DOMAIN}/${project.slug}/settings/billing?success=true`,
- cancel_url: `${APP_DOMAIN}/${project.slug}/settings/billing?upgrade=${
- plan.split("_")[0]
- }`,
- line_items: [{ price: prices.data[0].id, quantity: 1 }],
- automatic_tax: {
- enabled: true,
- },
- tax_id_collection: {
- enabled: true,
- },
- mode: "subscription",
- allow_promotion_codes: true,
- client_reference_id: project.id,
- });
- return NextResponse.json(stripeSession);
+ if (project.stripeId) {
+ const subscription = await stripe.subscriptions.list({
+ customer: project.stripeId,
+ status: "active",
+ });
+
+ const { url } = await stripe.billingPortal.sessions.create({
+ customer: project.stripeId,
+ return_url: `${baseUrl}?upgrade=${plan}`,
+ flow_data: {
+ type: "subscription_update_confirm",
+ subscription_update_confirm: {
+ subscription: subscription.data[0].id,
+ items: [
+ {
+ id: subscription.data[0].items.data[0].id,
+ quantity: 1,
+ price: prices.data[0].id,
+ },
+ ],
+ },
+ },
+ });
+ return NextResponse.json(url);
+ } else {
+ const stripeSession = await stripe.checkout.sessions.create({
+ customer_email: session.user.email,
+ billing_address_collection: "required",
+ success_url: `${APP_DOMAIN}/${project.slug}/settings/billing?success=true`,
+ cancel_url: `${baseUrl}?upgrade=${plan}`,
+ line_items: [{ price: prices.data[0].id, quantity: 1 }],
+ automatic_tax: {
+ enabled: true,
+ },
+ tax_id_collection: {
+ enabled: true,
+ },
+ mode: "subscription",
+ allow_promotion_codes: true,
+ client_reference_id: project.id,
+ });
+
+ return NextResponse.json(stripeSession);
+ }
});
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx
index 1690ce05f2..500e756641 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/billing/page-client.tsx
@@ -7,7 +7,13 @@ import PlanBadge from "@/ui/projects/plan-badge";
import { Divider } from "@/ui/shared/icons";
import ProgressBar from "@/ui/shared/progress-bar";
import { Button, InfoTooltip, NumberTooltip, useRouterStuff } from "@dub/ui";
-import { HOME_DOMAIN, PLANS, getFirstAndLastDay, nFormatter } from "@dub/utils";
+import {
+ HOME_DOMAIN,
+ PLANS,
+ getFirstAndLastDay,
+ getNextPlan,
+ nFormatter,
+} from "@dub/utils";
import va from "@vercel/analytics";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useMemo, useState } from "react";
@@ -72,8 +78,7 @@ export default function ProjectBillingClient() {
}
}, [searchParams, plan]);
- const nextPlan =
- PLANS[PLANS.findIndex((p) => p.name.toLowerCase() === plan) + 1];
+ const nextPlan = getNextPlan(plan as string);
return (
<>
diff --git a/apps/web/emails/clicks-exceeded.tsx b/apps/web/emails/clicks-exceeded.tsx
index da83849eb9..341f271d70 100644
--- a/apps/web/emails/clicks-exceeded.tsx
+++ b/apps/web/emails/clicks-exceeded.tsx
@@ -1,4 +1,10 @@
-import { DUB_LOGO, PLANS, capitalize, nFormatter } from "@dub/utils";
+import {
+ DUB_LOGO,
+ PLANS,
+ capitalize,
+ getNextPlan,
+ nFormatter,
+} from "@dub/utils";
import {
Body,
Container,
@@ -32,8 +38,7 @@ export default function ClicksExceeded({
type: "first" | "second";
}) {
const { slug, name, usage, usageLimit, plan } = project;
- const nextPlan =
- PLANS[PLANS.findIndex((p) => p.name.toLowerCase() === plan) + 1];
+ const nextPlan = getNextPlan(plan as string);
return (
<Html>
@@ -88,9 +93,7 @@ export default function ClicksExceeded({
<Section className="my-8 text-center">
<Link
className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
- href={`https://app.dub.co/${slug}?upgrade=${
- plan === "free" ? "pro" : "business"
- }}`}
+ href={`https://app.dub.co/${slug}?upgrade=${nextPlan.name.toLowerCase()}}`}
>
Upgrade my plan
</Link>
diff --git a/apps/web/emails/links-limit.tsx b/apps/web/emails/links-limit.tsx
index c58789596b..39a98b2598 100644
--- a/apps/web/emails/links-limit.tsx
+++ b/apps/web/emails/links-limit.tsx
@@ -1,4 +1,10 @@
-import { DUB_LOGO, PLANS, capitalize, nFormatter } from "@dub/utils";
+import {
+ DUB_LOGO,
+ PLANS,
+ capitalize,
+ getNextPlan,
+ nFormatter,
+} from "@dub/utils";
import {
Body,
Container,
@@ -37,8 +43,7 @@ export default function LinksLimitAlert({
plan: string;
};
const percentage = Math.round((linksUsage / linksLimit) * 100);
- const nextPlan =
- PLANS[PLANS.findIndex((p) => p.name.toLowerCase() === plan) + 1];
+ const nextPlan = getNextPlan(plan as string);
return (
<Html>
@@ -113,11 +118,7 @@ export default function LinksLimitAlert({
<Section className="mb-8 text-center">
<Link
className="rounded-full bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
- href={
- plan === "free"
- ? `https://app.dub.co/${slug}?upgrade=pro`
- : `https://app.dub.co/${slug}/settings/billing`
- }
+ href={`https://app.dub.co/${slug}?upgrade=${nextPlan.name.toLowerCase()}}`}
>
Upgrade my plan
</Link>
diff --git a/apps/web/ui/modals/upgrade-plan-modal.tsx b/apps/web/ui/modals/upgrade-plan-modal.tsx
index 8b25b63b33..b11df12b02 100644
--- a/apps/web/ui/modals/upgrade-plan-modal.tsx
+++ b/apps/web/ui/modals/upgrade-plan-modal.tsx
@@ -1,4 +1,5 @@
import { getStripe } from "@/lib/stripe/client";
+import useProject from "@/lib/swr/use-project";
import { CheckCircleFill } from "@/ui/shared/icons";
import {
Badge,
@@ -11,6 +12,7 @@ import {
useRouterStuff,
} from "@dub/ui";
import {
+ APP_DOMAIN,
HOME_DOMAIN,
SELF_SERVE_PAID_PLANS,
STAGGER_CHILD_VARIANTS,
@@ -52,8 +54,9 @@ function UpgradePlanModal({
const welcomeFlow = pathname === "/welcome";
const slug = welcomeFlow ? searchParams?.get("slug") : params.slug;
+ const { plan: currentPlan } = useProject();
const plan = searchParams.get("upgrade") ?? "pro";
- const currentPlan =
+ const selectedPlan =
SELF_SERVE_PAID_PLANS.find((p) => p.name.toLowerCase() === plan) ??
SELF_SERVE_PAID_PLANS[0];
const [openPlanSelector, setOpenPlanSelector] = useState(false);
@@ -99,14 +102,14 @@ function UpgradePlanModal({
className="text-lg font-medium"
variants={STAGGER_CHILD_VARIANTS}
>
- Upgrade to {currentPlan.name}
+ Upgrade to {selectedPlan.name}
</motion.h3>
<motion.p
className="text-center text-sm text-gray-500"
variants={STAGGER_CHILD_VARIANTS}
>
Enjoy higher limits and extra features <br /> with Dub.co{" "}
- {currentPlan.name}
+ {selectedPlan.name}
</motion.p>
</motion.div>
<div className="bg-gray-50 px-4 py-6 text-left sm:px-16">
@@ -150,12 +153,12 @@ function UpgradePlanModal({
className="mr-2 flex w-56 items-center justify-between space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-[98%]"
>
<IconMenu
- text={currentPlan.name}
+ text={selectedPlan.name}
icon={
<div
className={cn(
"h-2 w-2 rounded-full",
- currentPlan.colors.bg,
+ selectedPlan.colors.bg,
)}
/>
}
@@ -220,13 +223,13 @@ function UpgradePlanModal({
<div className="flex items-center justify-between">
<div className="flex items-center space-x-2">
<h4 className="font-medium text-gray-900">
- {currentPlan.name} {capitalize(period)}
+ {selectedPlan.name} {capitalize(period)}
</h4>
<Badge
variant="neutral"
className="text-sm font-normal normal-case"
>
- ${currentPlan.price[period].toString()}
+ ${selectedPlan.price[period].toString()}
/mo
<span className="hidden sm:inline-block">
, billed {period}
@@ -246,7 +249,7 @@ function UpgradePlanModal({
animate="show"
className="my-4 flex flex-col space-y-2"
>
- {currentPlan.features.map(({ text }, i) => (
+ {selectedPlan.features.map(({ text }, i) => (
<motion.div
key={i}
variants={STAGGER_CHILD_VARIANTS}
@@ -258,21 +261,31 @@ function UpgradePlanModal({
))}
</motion.div>
<Button
- text={`Upgrade to ${currentPlan.name} ${capitalize(period)}`}
+ text={`Upgrade to ${selectedPlan.name} ${capitalize(period)}`}
loading={clicked}
onClick={() => {
setClicked(true);
- fetch(
- `/api/projects/${slug}/billing/upgrade?plan=${plan}_${period}`,
- {
- method: "POST",
+ fetch(`/api/projects/${slug}/billing/upgrade`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
},
- )
+ body: JSON.stringify({
+ plan,
+ period,
+ baseUrl: `${APP_DOMAIN}/${pathname}`,
+ }),
+ })
.then(async (res) => {
- const data = await res.json();
- const { id: sessionId } = data;
- const stripe = await getStripe();
- stripe?.redirectToCheckout({ sessionId });
+ if (currentPlan === "free") {
+ const data = await res.json();
+ const { id: sessionId } = data;
+ const stripe = await getStripe();
+ stripe?.redirectToCheckout({ sessionId });
+ } else {
+ const url = await res.json();
+ router.push(url);
+ }
})
.catch((err) => {
alert(err);
diff --git a/apps/web/ui/projects/project-exceeded-clicks.tsx b/apps/web/ui/projects/project-exceeded-clicks.tsx
index c1a564e429..1a4f3374e2 100644
--- a/apps/web/ui/projects/project-exceeded-clicks.tsx
+++ b/apps/web/ui/projects/project-exceeded-clicks.tsx
@@ -2,11 +2,13 @@
import useProject from "@/lib/swr/use-project";
import { MaxWidthWrapper, useRouterStuff } from "@dub/ui";
+import { getNextPlan } from "@dub/utils";
import { Lock } from "lucide-react";
export default function ProjectExceededClicks() {
const { plan } = useProject();
const { queryParams } = useRouterStuff();
+ const nextPlan = getNextPlan(plan as string);
return (
<MaxWidthWrapper>
@@ -32,13 +34,13 @@ export default function ProjectExceededClicks() {
onClick={() =>
queryParams({
set: {
- upgrade: plan === "free" ? "pro" : "business",
+ upgrade: nextPlan.name.toLowerCase(),
},
})
}
className="z-10 rounded-md border border-black bg-black px-10 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black"
>
- Upgrade now
+ Upgrade to {nextPlan.name}
</button>
</div>
</MaxWidthWrapper>
diff --git a/packages/utils/src/constants/pricing.tsx b/packages/utils/src/constants/pricing.tsx
index 5d90c9e40e..30bd3d7cb6 100644
--- a/packages/utils/src/constants/pricing.tsx
+++ b/packages/utils/src/constants/pricing.tsx
@@ -6,6 +6,9 @@ const BUSINESS_PLAN = ({
yearly = 39,
links = 5000,
clicks = 150000,
+ domains = 40,
+ tags = 150,
+ users = 15,
ids = [],
}: {
name: string;
@@ -13,6 +16,9 @@ const BUSINESS_PLAN = ({
yearly: number;
links: number;
clicks: number;
+ domains: number;
+ users: number;
+ tags: number;
ids: string[];
}) => ({
name,
@@ -26,9 +32,9 @@ const BUSINESS_PLAN = ({
limits: {
links,
clicks,
- domains: 20,
- tags: 150,
- users: 15,
+ domains,
+ tags,
+ users,
},
colors: {
bg: "bg-sky-900",
@@ -47,8 +53,9 @@ const BUSINESS_PLAN = ({
text: `${nFormatter(clicks)} tracked clicks/mo`,
},
{ text: "2-year analytics retention" },
- { text: "20 custom domains" },
- { text: "15 users" },
+ { text: `${domains} custom domains` },
+ { text: `${nFormatter(tags, { full: true })} tags` },
+ { text: `${users} users` },
{ text: "Elevated support", footnote: "Email and chat support." },
{
text: "Custom branding",
@@ -59,10 +66,6 @@ const BUSINESS_PLAN = ({
href: "https://dub.co/help/article/custom-qr-codes",
},
},
- {
- text: "Event callbacks (Beta)",
- footnote: "Get notified when someone clicks on your links.",
- },
],
});
@@ -178,6 +181,9 @@ export const PLANS = [
yearly: 39,
links: 5000,
clicks: 150000,
+ domains: 40,
+ tags: 150,
+ users: 15,
ids: [
"price_1LodLoAlJJEpqkPVJdwv5zrG", // old yearly
"price_1LoyrCAlJJEpqkPVZ32BV3wm", // new monthly (test)
@@ -190,9 +196,15 @@ export const PLANS = [
name: "Business Plus",
monthly: 119,
yearly: 99,
- links: 10000,
+ links: 15000,
clicks: 400000,
- ids: [],
+ domains: 100,
+ tags: 300,
+ users: 40,
+ ids: [
+ "price_1OnWu0AlJJEpqkPVWk4144ZG", // monthly (test)
+ "price_1OnWu0AlJJEpqkPVkDWVriAB", // yearly (test)
+ ],
}),
BUSINESS_PLAN({
name: "Business Extra",
@@ -200,7 +212,13 @@ export const PLANS = [
yearly: 199,
links: 40000,
clicks: 1000000,
- ids: [],
+ domains: 250,
+ tags: 500,
+ users: 100,
+ ids: [
+ "price_1OnWvCAlJJEpqkPVLzLHx5QD", // monthly (test)
+ "price_1OnWvCAlJJEpqkPVHhCCvIOq", // yearly (test)
+ ],
}),
BUSINESS_PLAN({
name: "Business Max",
@@ -208,7 +226,13 @@ export const PLANS = [
yearly: 399,
links: 100000,
clicks: 2500000,
- ids: [],
+ domains: 500,
+ tags: 1000,
+ users: 250,
+ ids: [
+ "price_1OnWwLAlJJEpqkPVXtJyPqLk", // monthly (test)
+ "price_1OnWwLAlJJEpqkPV4eMbOkNh", // yearly (test)
+ ],
}),
{
name: "Enterprise",
@@ -255,3 +279,11 @@ export const SELF_SERVE_PAID_PLANS = PLANS.filter(
);
export const FREE_PROJECTS_LIMIT = 2;
+
+export const getPlanFromPriceId = (priceId: string) => {
+ return PLANS.find((plan) => plan.price.ids?.includes(priceId)) || null;
+};
+
+export const getNextPlan = (plan: string) => {
+ return PLANS[PLANS.findIndex((p) => p.name.toLowerCase() === plan) + 1];
+};
diff --git a/packages/utils/src/functions/misc.ts b/packages/utils/src/functions/misc.ts
deleted file mode 100644
index ea3528207f..0000000000
--- a/packages/utils/src/functions/misc.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { PLANS } from "../constants";
-
-export const getPlanFromPriceId = (priceId: string) => {
- return PLANS.find((plan) => plan.price.ids?.includes(priceId)) || null;
-};