The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
completed Stripe integration
Steven Teye876e8a1edec
diff --git a/components/app/custom-domain/edit-domain-modal.tsx b/components/app/custom-domain/edit-domain-modal.tsxindex f42775378d..47ea5b8852 100644--- a/components/app/custom-domain/edit-domain-modal.tsx+++ b/components/app/custom-domain/edit-domain-modal.tsx@@ -77,7 +77,6 @@ function EditDomainModalHelper({body: JSON.stringify(data),}).then(async (res) => {setSaving(false);- console.log("status is ", res.status);if (res.status === 200) {mutate(`/api/projects/${slug}`);setShowEditDomainModal(false);diff --git a/components/app/custom-domain/index.tsx b/components/app/custom-domain/index.tsxindex b7147e220a..f66f519bd7 100644--- a/components/app/custom-domain/index.tsx+++ b/components/app/custom-domain/index.tsx@@ -20,10 +20,14 @@ export default function CustomDomain({ domain }: { domain: string }) {const { data, isValidating } = useSWR<{status: DomainVerificationStatusProps;response: any;- }>(`/api/projects/${slug}/domains/${domain}/verify`, fetcher, {- revalidateOnMount: true,- refreshInterval: 5000,- });+ }>(+ slug && domain && `/api/projects/${slug}/domains/${domain}/verify`,+ fetcher,+ {+ revalidateOnMount: true,+ refreshInterval: 5000,+ }+ );const { setShowEditDomainModal, EditDomainModal } = useEditDomainModal({domain,diff --git a/components/app/links-container.tsx b/components/app/links-container.tsxindex cb7c4021ac..6a118237f1 100644--- a/components/app/links-container.tsx+++ b/components/app/links-container.tsx@@ -5,7 +5,7 @@ import LinkCard from "@/components/app/link-card";import LinkCardPlaceholder from "@/components/app/link-card-placeholder";import MaxWidthWrapper from "@/components/shared/max-width-wrapper";import NoLinksPlaceholder from "@/components/app/no-links-placeholder";-import { ProjectProps, LinkProps } from "@/lib/types";+import { LinkProps } from "@/lib/types";export default function LinksContainer({exceededUsage,diff --git a/components/app/plan-usage.tsx b/components/app/plan-usage.tsxindex 4b640aca7e..ff42538847 100644--- a/components/app/plan-usage.tsx+++ b/components/app/plan-usage.tsx@@ -1,5 +1,5 @@import useSWR from "swr";-import { useState } from "react";+import { useMemo, useState } from "react";import { fetcher, nFormatter } from "@/lib/utils";import { useRouter } from "next/router";import { ProjectProps } from "@/lib/types";@@ -11,7 +11,7 @@ import {LoadingDots,} from "@/components/shared/icons";import { motion } from "framer-motion";-import { getStripe } from "@/lib/stripe";+import { getStripe } from "@/lib/stripe/client";export default function PlanUsage({ project }: { project: ProjectProps }) {const router = useRouter();@@ -27,7 +27,25 @@ export default function PlanUsage({ project }: { project: ProjectProps }) {fetcher);- const [upgrading, setUpgrading] = useState(false);+ const [clicked, setClicked] = useState(false);++ const [billingStart, billingEnd] = useMemo(() => {+ if (project?.lastBilled) {+ const lastBilledDate = new Date(project.lastBilled);+ const start = lastBilledDate.toLocaleDateString("en-us", {+ month: "short",+ day: "numeric",+ });+ const end = new Date(+ lastBilledDate.setDate(lastBilledDate.getDate() + 30)+ ).toLocaleDateString("en-us", {+ month: "short",+ day: "numeric",+ });+ return [start, end];+ }+ return ["", ""];+ }, [project?.lastBilled]);return (<div className="bg-white rounded-lg border border-gray-200">@@ -35,10 +53,34 @@ export default function PlanUsage({ project }: { project: ProjectProps }) {<h2 className="text-xl font-medium">Plan & Usage</h2><p className="text-gray-500 text-sm">You are currently on the{" "}- <span className="capitalize bg-blue-500 text-white rounded-full px-2 py-0.5 text-xs">- {project?.plan}- </span>{" "}+ {project ? (+ <span+ className={`capitalize ${+ project.plan === "enterprise"+ ? "bg-violet-600 border-violet-600 text-white"+ : project.plan === "pro"+ ? "bg-blue-500 border-blue-500 text-white"+ : "bg-black border-black text-white"+ } border rounded-full px-2 py-0.5 text-xs font-medium`}+ >+ {project.plan}+ </span>+ ) : (+ <span className="bg-gray-200 text-gray-200 rounded-full px-2 py-0.5 text-xs">+ load+ </span>+ )}{" "}plan.+ {project?.plan !== "free" && (+ <>+ {" "}+ Current billing cycle:{" "}+ <span className="font-medium text-black">+ {billingStart} - {billingEnd}+ </span>+ .+ </>+ )}</p></div><div className="border-b border-gray-200" />@@ -93,42 +135,88 @@ export default function PlanUsage({ project }: { project: ProjectProps }) {</div><div className="border-b border-gray-200" /><div className="px-10 py-5 flex justify-between items-center">- <p className="text-gray-500 text-sm">- For{" "}- <Tooltip content="1 million link clicks per month">- <span className="font-medium text-gray-700 underline underline-offset-2 cursor-default hover:text-black">- increased limits- </span>- </Tooltip>- , upgrade to the Pro plan.- </p>- <button- onClick={() => {- setUpgrading(true);- fetch(`/api/projects/${slug}/upgrade`, {- method: "POST",- })- .then(async (res) => {- const data = await res.json();- console.log(data);- const { id: sessionId } = data;- const stripe = await getStripe();- stripe.redirectToCheckout({ sessionId });- })- .catch((err) => {- alert(err);- setUpgrading(false);- });- }}- disabled={upgrading}- className={`${- upgrading- ? "cursor-not-allowed bg-gray-100 border-gray-200"- : "bg-blue-500 text-white border-blue-500 hover:text-blue-500 hover:bg-white"- } h-9 w-24 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150`}- >- {upgrading ? <LoadingDots /> : "Upgrade"}- </button>+ {project?.plan === "free" ? (+ <p className="text-gray-500 text-sm">+ For{" "}+ <Tooltip content="1 million link clicks per month">+ <span className="font-medium text-gray-700 underline underline-offset-2 cursor-default hover:text-black">+ increased limits+ </span>+ </Tooltip>+ , upgrade to the Pro plan.+ </p>+ ) : project?.plan === "pro" ? (+ <p className="text-gray-500 text-sm">+ To remove limits, contact us to upgrade to the Enterprise plan.+ </p>+ ) : (+ <div className="h-3 w-28 bg-gray-200 rounded-full animate-pulse" />+ )}+ {project ? (+ project.plan === "free" ? (+ <button+ onClick={() => {+ setClicked(true);+ fetch(`/api/projects/${slug}/upgrade`, {+ method: "POST",+ })+ .then(async (res) => {+ const data = await res.json();+ const { id: sessionId } = data;+ const stripe = await getStripe();+ stripe.redirectToCheckout({ sessionId });+ })+ .catch((err) => {+ alert(err);+ setClicked(false);+ });+ }}+ disabled={clicked}+ className={`${+ clicked+ ? "cursor-not-allowed bg-gray-100 border-gray-200"+ : "bg-blue-500 text-white border-blue-500 hover:text-blue-500 hover:bg-white"+ } h-9 w-24 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150`}+ >+ {clicked ? <LoadingDots /> : "Upgrade"}+ </button>+ ) : project.plan === "pro" ? (+ <div className="flex space-x-3">+ <a+ href="mailto:[email protected]?subject=Upgrade%20to%20Enterprise%20Plan"+ className="flex justify-center items-center bg-violet-600 text-white border-violet-600 hover:text-violet-600 hover:bg-white h-9 w-24 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150"+ >+ Contact Us+ </a>+ <button+ onClick={() => {+ setClicked(true);+ fetch(`/api/projects/${slug}/manage-subscription`, {+ method: "POST",+ })+ .then(async (res) => {+ const url = await res.json();+ router.push(url);+ })+ .catch((err) => {+ alert(err);+ setClicked(false);+ });+ }}+ disabled={clicked}+ className={`${+ clicked+ ? "cursor-not-allowed bg-gray-100 border-gray-200"+ : "bg-black text-white border-black hover:text-black hover:bg-white"+ } h-9 w-40 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150`}+ >+ {clicked ? <LoadingDots /> : "Manage Subscription"}+ </button>+ </div>+ ) : null+ ) : (+ <div className="h-9 w-24 bg-gray-200 rounded-md animate-pulse" />+ )}</div></div>);diff --git a/lib/auth.ts b/lib/auth.tsindex 0c4f03f3ac..ad0955b430 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -21,8 +21,18 @@ export async function getSession(req: NextApiRequest, res: NextApiResponse) {return session;}+import { ProjectProps } from "@/lib/types";++interface CustomNextApiHandler {+ (+ req: NextApiRequest,+ res: NextApiResponse,+ project: ProjectProps+ ): Promise<void>;+}+const withProjectAuth =- (handler: NextApiHandler, isWriteEditLink?: boolean) =>+ (handler: CustomNextApiHandler, isWriteEditLink?: boolean) =>// TODO - fix `handler` type when we figure it out// `isWriteEditLink` is only true when it's a POST or PUT request for links// (you can't add/edit a link when domain is not configured)@@ -37,7 +47,7 @@ const withProjectAuth =.json({ error: "Missing or misconfigured project slug" });}- const project = await prisma.project.findFirst({+ const project = (await prisma.project.findFirst({where: {slug,users: {@@ -46,7 +56,17 @@ const withProjectAuth =},},},- });+ select: {+ name: true,+ slug: true,+ domain: true,+ domainVerified: true,+ plan: true,+ usageLimit: true,+ stripeId: true,+ lastBilled: true,+ },+ })) as ProjectProps;if (!project) return res.status(401).end("Unauthorized");@@ -69,7 +89,7 @@ const withProjectAuth =}}- return handler(req, res);+ return handler(req, res, project);};export { withProjectAuth };diff --git a/lib/stripe.ts b/lib/stripe/client.tssimilarity index 61%rename from lib/stripe.tsrename to lib/stripe/client.tsindex 139504b378..83039b6425 100644--- a/lib/stripe.ts+++ b/lib/stripe/client.ts@@ -1,16 +1,3 @@-import Stripe from "stripe";--export const stripe = new Stripe(- process.env.STRIPE_SECRET_KEY_LIVE ?? process.env.STRIPE_SECRET_KEY ?? "",- {- apiVersion: "2022-08-01",- appInfo: {- name: "Dub.sh",- version: "0.1.0",- },- }-);-// Stripe Client SDKimport { loadStripe, Stripe as StripeProps } from "@stripe/stripe-js";diff --git a/lib/stripe/index.ts b/lib/stripe/index.tsnew file mode 100644index 0000000000..594c7567db--- /dev/null+++ b/lib/stripe/index.ts@@ -0,0 +1,12 @@+import Stripe from "stripe";++export const stripe = new Stripe(+ process.env.STRIPE_SECRET_KEY_LIVE ?? process.env.STRIPE_SECRET_KEY ?? "",+ {+ apiVersion: "2022-08-01",+ appInfo: {+ name: "Dub.sh",+ version: "0.1.0",+ },+ }+);diff --git a/lib/types.ts b/lib/types.tsindex 3564bb428a..0d4d39a998 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -12,7 +12,8 @@ export interface ProjectProps {domainVerified: boolean;plan: string;usageLimit: number;- links: LinkProps[];+ stripeId?: string;+ lastBilled: Date;}export type DomainVerificationStatusProps =diff --git a/lib/upstash.ts b/lib/upstash.tsindex 858b453c2d..06a3d8c43c 100644--- a/lib/upstash.ts+++ b/lib/upstash.ts@@ -207,15 +207,24 @@ export async function editLink(}}-export async function getUsage(hostname: string) {+export async function getUsage(hostname: string, billingCycleStart?: Date) {const cachedUsage = await redis.get(`usage:${hostname}`);if (cachedUsage) {return cachedUsage;}console.log("no cached usage found. computing from scratch...");- var date = new Date();- var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);- var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);++ let firstDay;+ let lastDay;++ if (billingCycleStart) {+ firstDay = new Date(billingCycleStart).getTime();+ lastDay = Date.now();+ } else {+ var date = new Date();+ firstDay = new Date(date.getFullYear(), date.getMonth(), 1).getTime();+ lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getTime();+ }const links = await redis.zrange(`${hostname}:links:timestamps`, 0, -1);let results: number[] = [];@@ -223,11 +232,7 @@ export async function getUsage(hostname: string) {if (links.length > 0) {const pipeline = redis.pipeline();links.forEach((link) => {- pipeline.zcount(- `${hostname}:clicks:${link}`,- firstDay.getTime(),- lastDay.getTime()- );+ pipeline.zcount(`${hostname}:clicks:${link}`, firstDay, lastDay);});results = await pipeline.exec();}diff --git a/lib/utils.ts b/lib/utils.tsindex 1cf3d419f8..f43776f5c3 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -120,3 +120,7 @@ export const generateSlugFromName = (name: string) => {return `${shortestString}.sh`;};++export const domainRegex = new RegExp(+ "^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$"+);diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.tsindex 92ecfa5d77..406631d143 100644--- a/pages/api/projects/[slug]/domains/[domain]/index.ts+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts@@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";import prisma from "@/lib/prisma";import { withProjectAuth } from "@/lib/auth";import { changeDomain } from "@/lib/upstash";+import { domainRegex } from "@/lib/utils";export default withProjectAuth(async (req: NextApiRequest, res: NextApiResponse) => {@@ -9,12 +10,10 @@ export default withProjectAuth(const { slug, domain } = req.query as { slug: string; domain: string }; // slug is the domainconst newDomain = req.body;- const domainError = newDomain.includes(" ")- ? "Domain cannot contain spaces"- : null;- if (domainError) {+ const validDomain = domainRegex.test(newDomain);+ if (!validDomain) {return res.status(422).json({- domainError,+ domainError: "Invalid domain",});}diff --git a/pages/api/projects/[slug]/domains/[domain]/usage.ts b/pages/api/projects/[slug]/domains/[domain]/usage.tsindex d727598d6e..cdd55432f5 100644--- a/pages/api/projects/[slug]/domains/[domain]/usage.ts+++ b/pages/api/projects/[slug]/domains/[domain]/usage.ts@@ -1,13 +1,17 @@import { NextApiRequest, NextApiResponse } from "next";import { withProjectAuth } from "@/lib/auth";import { getUsage } from "@/lib/upstash";+import { ProjectProps } from "@/lib/types";export default withProjectAuth(- async (req: NextApiRequest, res: NextApiResponse) => {+ async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {// GET /api/projects/[slug]/domains/[domain]/usage – get project usageif (req.method === "GET") {const { domain } = req.query as { domain: string };- const usage = await getUsage(domain);+ const usage = await getUsage(+ domain,+ project.plan !== "free" ? project.lastBilled : null+ );return res.status(200).json(usage);} else {res.setHeader("Allow", ["GET"]);diff --git a/pages/api/projects/[slug]/domains/[domain]/verify.ts b/pages/api/projects/[slug]/domains/[domain]/verify.tsindex f9c6258d22..b0a96e4f1b 100644--- a/pages/api/projects/[slug]/domains/[domain]/verify.ts+++ b/pages/api/projects/[slug]/domains/[domain]/verify.ts@@ -5,102 +5,109 @@ import prisma from "@/lib/prisma";export default withProjectAuth(async (req: NextApiRequest, res: NextApiResponse) => {- const { slug, domain } = req.query as { slug: string; domain: string };- let status: DomainVerificationStatusProps = "Valid Configuration";+ if (req.method === "GET") {+ const { slug, domain } = req.query as { slug: string; domain: string };+ let status: DomainVerificationStatusProps = "Valid Configuration";- const [domainResponse, configResponse] = await Promise.all([- fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,- {- method: "GET",- headers: {- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,- "Content-Type": "application/json",- },- }- ),- fetch(- `https://api.vercel.com/v6/domains/${domain}/config?teamId=${process.env.VERCEL_TEAM_ID}`,- {- method: "GET",- headers: {- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,- "Content-Type": "application/json",- },- }- ),- ]);+ const [domainResponse, configResponse] = await Promise.all([+ fetch(+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ }+ ),+ fetch(+ `https://api.vercel.com/v6/domains/${domain}/config?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ }+ ),+ ]);- const domainJson = await domainResponse.json();- const configJson = await configResponse.json();- if (domainResponse.status !== 200) {- // domain not found on Vercel project- status = "Domain Not Found";- return res- .status(200)- .json({ status, response: { configJson, domainJson } });- }+ const domainJson = await domainResponse.json();+ const configJson = await configResponse.json();+ if (domainResponse.status !== 200) {+ // domain not found on Vercel project+ status = "Domain Not Found";+ return res+ .status(200)+ .json({ status, response: { configJson, domainJson } });+ }- /**- * If domain is not verified, we try to verify now- */- let verificationResponse = null;- if (!domainJson.verified) {- status = "Pending Verification";- const verificationRes = await fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}/verify?teamId=${process.env.VERCEL_TEAM_ID}`,- {- method: "POST",- headers: {- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,- "Content-Type": "application/json",- },+ /**+ * If domain is not verified, we try to verify now+ */+ let verificationResponse = null;+ if (!domainJson.verified) {+ status = "Pending Verification";+ const verificationRes = await fetch(+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}/verify?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ }+ );+ verificationResponse = await verificationRes.json();++ if (verificationResponse && verificationResponse.verified) {+ /**+ * Domain was just verified+ */+ status = "Valid Configuration";}- );- verificationResponse = await verificationRes.json();- if (verificationResponse && verificationResponse.verified) {- /**- * Domain was just verified- */- status = "Valid Configuration";+ return res.status(200).json({+ status,+ response: {+ configJson,+ domainJson,+ verificationResponse,+ },+ });+ }++ let prismaResponse = null;+ if (!configJson.misconfigured) {+ prismaResponse = await prisma.project.update({+ where: {+ slug,+ },+ data: {+ domainVerified: true,+ },+ });+ } else {+ status = "Invalid Configuration";+ prismaResponse = await prisma.project.update({+ where: {+ slug,+ },+ data: {+ domainVerified: false,+ },+ });}return res.status(200).json({status,- response: {- configJson,- domainJson,- verificationResponse,- },- });- }-- let prismaResponse = null;- if (!configJson.misconfigured) {- prismaResponse = await prisma.project.update({- where: {- slug,- },- data: {- domainVerified: true,- },+ response: { configJson, domainJson, prismaResponse },});} else {- status = "Invalid Configuration";- prismaResponse = await prisma.project.update({- where: {- slug,- },- data: {- domainVerified: false,- },- });+ res.setHeader("Allow", ["GET"]);+ return res+ .status(405)+ .json({ error: `Method ${req.method} Not Allowed` });}-- return res.status(200).json({- status,- response: { configJson, domainJson, prismaResponse },- });});diff --git a/pages/api/projects/[slug]/manage-subscription.ts b/pages/api/projects/[slug]/manage-subscription.tsnew file mode 100644index 0000000000..61c375bc2d--- /dev/null+++ b/pages/api/projects/[slug]/manage-subscription.ts@@ -0,0 +1,27 @@+import { NextApiRequest, NextApiResponse } from "next";+import { withProjectAuth } from "@/lib/auth";+import { stripe } from "@/lib/stripe";+import { ProjectProps } from "@/lib/types";++export default withProjectAuth(+ async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {+ // POST /api/projects/[slug]/upgrade – upgrade a project+ if (req.method === "POST") {+ const { slug } = req.query as { slug: string };+ const { url } = await stripe.billingPortal.sessions.create({+ customer: project.stripeId,+ return_url: `${+ process.env.VERCEL === "1"+ ? "https://app.dub.sh"+ : "http://app.localhost:3000"+ }/${slug}/settings`,+ });+ return res.status(200).json(url);+ } else {+ res.setHeader("Allow", ["POST"]);+ return res+ .status(405)+ .json({ error: `Method ${req.method} Not Allowed` });+ }+ }+);diff --git a/pages/api/projects/[slug]/upgrade.ts b/pages/api/projects/[slug]/upgrade.tsindex aa1a6ccc6c..3c07c14fa0 100644--- a/pages/api/projects/[slug]/upgrade.ts+++ b/pages/api/projects/[slug]/upgrade.ts@@ -4,7 +4,7 @@ import { stripe } from "@/lib/stripe";export default withProjectAuth(async (req: NextApiRequest, res: NextApiResponse) => {- // GET /api/projects/[slug]/upgrade – upgrade a project+ // POST /api/projects/[slug]/upgrade – upgrade a projectif (req.method === "POST") {const { slug } = req.query as { slug: string };const session = await stripe.checkout.sessions.create({@@ -22,10 +22,11 @@ export default withProjectAuth(}/${slug}/settings`,line_items: [{ price: "price_1Lis30AlJJEpqkPVAuSVxbT1", quantity: 1 }],mode: "subscription",+ client_reference_id: slug,});return res.status(200).json(session);} else {- res.setHeader("Allow", ["GET"]);+ res.setHeader("Allow", ["POST"]);return res.status(405).json({ error: `Method ${req.method} Not Allowed` });diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.tsindex d271d1f04d..d07fec250a 100644--- a/pages/api/projects/index.ts+++ b/pages/api/projects/index.ts@@ -1,6 +1,7 @@import { NextApiRequest, NextApiResponse } from "next";import { getSession } from "@/lib/auth";import prisma from "@/lib/prisma";+import { domainRegex } from "@/lib/utils";export default async function handler(req: NextApiRequest,@@ -32,13 +33,11 @@ export default async function handler(slug.includes(" ") || slug.includes(".")? "Slug cannot contain spaces or periods": null;- const domainError = domain.includes(" ")- ? "Domain cannot contain spaces"- : null;- if (slugError || domainError) {+ const validDomain = domainRegex.test(domain);+ if (slugError || !validDomain) {return res.status(422).json({slugError,- domainError,+ domainError: validDomain ? null : "Invalid domain",});}try {diff --git a/pages/api/projects/stripe/webhook.ts b/pages/api/projects/stripe/webhook.tsnew file mode 100644index 0000000000..cf1c6ee596--- /dev/null+++ b/pages/api/projects/stripe/webhook.ts@@ -0,0 +1,111 @@+import { NextApiRequest, NextApiResponse } from "next";+import Stripe from "stripe";+import { stripe } from "@/lib/stripe";+import { Readable } from "node:stream";+import prisma from "@/lib/prisma";++// Stripe requires the raw body to construct the event.+export const config = {+ api: {+ bodyParser: false,+ },+};++async function buffer(readable: Readable) {+ const chunks = [];+ for await (const chunk of readable) {+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);+ }+ return Buffer.concat(chunks);+}++const relevantEvents = new Set([+ "checkout.session.completed",+ "invoice.paid",+ "invoice.payment_failed",+ "customer.subscription.deleted",+]);++export default async function webhookHandler(+ req: NextApiRequest,+ res: NextApiResponse+) {+ // POST /api/projects/[slug]/upgrade/webhook – listen to Stripe webhooks+ if (req.method === "POST") {+ const buf = await buffer(req);+ const sig = req.headers["stripe-signature"];+ const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;+ let event: Stripe.Event;+ try {+ if (!sig || !webhookSecret) return;+ event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);+ } catch (err: any) {+ console.log(`❌ Error message: ${err.message}`);+ return res.status(400).send(`Webhook Error: ${err.message}`);+ }+ if (relevantEvents.has(event.type)) {+ try {+ switch (event.type) {+ case "checkout.session.completed":+ const checkoutSession = event.data+ .object as Stripe.Checkout.Session;++ await prisma.project.update({+ where: {+ slug: checkoutSession.client_reference_id,+ },+ data: {+ plan: "pro",+ usageLimit: 1000000,+ stripeId: checkoutSession.customer.toString(),+ lastBilled: new Date(),+ },+ });+ break;+ case "invoice.paid":+ const invoicePaid = event.data.object as Stripe.Invoice;+ console.log("invoice paid", invoicePaid);+ await prisma.project.update({+ where: {+ stripeId: invoicePaid.customer.toString(),+ },+ data: {+ lastBilled: new Date(),+ },+ });+ break;+ case "invoice.payment_failed":+ const invoiceFailed = event.data.object as Stripe.Invoice;+ console.log("invoice failed", invoiceFailed);+ // TODO - send email to user+ break;+ case "customer.subscription.deleted":+ const subscription = event.data.object as Stripe.Subscription;+ console.log("subscription deleted", subscription);+ await prisma.project.update({+ where: {+ stripeId: subscription.customer.toString(),+ },+ data: {+ plan: "free",+ usageLimit: 1000,+ },+ });+ break;+ default:+ throw new Error("Unhandled relevant event!");+ }+ } catch (error) {+ console.log(error);+ return res+ .status(400)+ .send('Webhook error: "Webhook handler failed. View logs."');+ }+ }++ res.json({ received: true });+ } else {+ res.setHeader("Allow", ["POST"]);+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });+ }+}diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 71e127c4b0..318dc93615 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -66,7 +66,8 @@ model Project {domainVerified Boolean @default(false)plan String @default("free")usageLimit Int @default(1000)- stripeId String? @unique+ stripeId String? @unique // Stripe customer ID+ lastBilled DateTime?createdAt DateTime @default(now())updatedAt DateTime @updatedAtusers ProjectUsers[]