Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add payment and billing
Marc Seitzeced278437b1
diff --git a/components/billing/upgrade-plan-modal.tsx b/components/billing/upgrade-plan-modal.tsxnew file mode 100644index 00000000..11a82fef--- /dev/null+++ b/components/billing/upgrade-plan-modal.tsx@@ -0,0 +1,163 @@+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useMemo,+ useState,+} from "react";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Button } from "@/components/ui/button";+import { useRouter } from "next/router";+import Link from "next/link";+import { motion } from "framer-motion";+import { STAGGER_CHILD_VARIANTS } from "@/lib/constants";+import CheckCircle2 from "@/components/shared/icons/check-cirlce-2";+import { capitalize } from "@/lib/utils";+import { PLANS } from "@/lib/stripe/utils";+import { getStripe } from "@/lib/stripe/client";+import { Badge } from "../ui/badge";+++export function UpgradePlanModal({ children }: { children: React.ReactNode }) {+ const [plan, setPlan] = useState<"Pro">("Pro");+ const [period, setPeriod] = useState<"monthly" | "yearly">("yearly");+ const [clicked, setClicked] = useState<boolean>(false);+ const features = useMemo(() => {+ return [+ "Custom domain",+ "Unlimited link views",+ "Unlimited documents",+ "Unlimited team members (ETA Oct 2023)",+ ];+ }, [plan]);++ return (+ <Dialog>+ <DialogTrigger>{children}</DialogTrigger>+ <DialogContent className="text-foreground bg-background">+ <motion.div+ variants={{+ show: {+ transition: {+ staggerChildren: 0.15,+ },+ },+ }}+ initial="hidden"+ animate="show"+ className="flex flex-col items-center justify-center space-y-3 border-b border-border px-4 py-8 sm:px-16"+ >+ <motion.div variants={STAGGER_CHILD_VARIANTS}>+ <p className="text-2xl font-bold tracking-tighter text-foreground">+ Papermark+ </p>+ </motion.div>+ <motion.h3+ className="text-lg font-medium"+ variants={STAGGER_CHILD_VARIANTS}+ >+ Upgrade to {plan}+ </motion.h3>+ <motion.p+ className="text-center text-sm text-muted-foreground"+ variants={STAGGER_CHILD_VARIANTS}+ >+ Enjoy higher limits and extra features with our {plan} plan.+ </motion.p>+ </motion.div>+ <div className="bg-background px-4 py-8 text-left sm:px-16">+ <motion.div+ className="flex flex-col space-y-3"+ variants={STAGGER_CHILD_VARIANTS}+ initial="hidden"+ animate="show"+ >+ <div className="mb-4">+ <div className="mb-4 flex items-center justify-between">+ <div className="flex items-center space-x-2">+ <h4 className="font-medium text-foreground">+ {plan} {capitalize(period)}+ </h4>+ <Badge+ variant="outline"+ className="text-sm font-normal normal-case"+ >{`$${+ PLANS.find((p) => p.name === plan)!.price[period].amount+ }/${period.replace("ly", "")}`}</Badge>+ </div>+ <button+ onClick={() => {+ setPeriod(period === "monthly" ? "yearly" : "monthly");+ }}+ className="text-xs text-muted-foreground underline underline-offset-4 transition-colors hover:text-gray-800 hover:dark:text-muted-foreground/80"+ >+ {period === "monthly"+ ? "Get 2 months free π"+ : "Switch to monthly"}+ </button>+ </div>+ <motion.div+ variants={{+ show: {+ transition: {+ staggerChildren: 0.08,+ },+ },+ }}+ initial="hidden"+ animate="show"+ className="flex flex-col space-y-2"+ >+ {features.map((feature, i) => (+ <motion.div+ key={i}+ variants={STAGGER_CHILD_VARIANTS}+ className="flex items-center space-x-2 text-sm text-muted-foreground"+ >+ <CheckCircle2 className="h-5 w-5 text-emerald-500" />+ <span>{feature}</span>+ </motion.div>+ ))}+ </motion.div>+ </div>+ <Button+ disabled={clicked}+ onClick={() => {+ setClicked(true);+ fetch(+ `/api/billing/upgrade?priceId=${+ PLANS.find((p) => p.name === plan)!.price[period].priceIds[+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production"+ ? "production"+ : "test"+ ]+ }`,+ {+ 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);+ });+ }}+ >{`Upgrade to ${plan} ${capitalize(period)}`}</Button>+ </motion.div>+ </div>+ </DialogContent>+ </Dialog>+ );+}\ No newline at end of filediff --git a/components/emails/upgrade-plan.tsx b/components/emails/upgrade-plan.tsxnew file mode 100644index 00000000..9625900c--- /dev/null+++ b/components/emails/upgrade-plan.tsx@@ -0,0 +1,101 @@+import React from "react";+import {+ Body,+ Container,+ Head,+ Heading,+ Html,+ Preview,+ Section,+ Text,+ Tailwind,+ Link,+ Hr,+} from "@react-email/components";++interface UpgradePlanEmailProps {+ name: string | null | undefined;+}++const UpgradePlanEmail = ({ name }: UpgradePlanEmailProps) => {+ const previewText = `The document sharing infrastructure for the modern web`;++ return (+ <Html>+ <Head />+ <Preview>{previewText}</Preview>+ <Tailwind>+ <Body className="bg-white my-auto mx-auto font-sans">+ <Container className="my-10 mx-auto p-5 w-[465px]">+ <Heading className="text-2xl font-normal text-center p-0 mt-4 mb-8 mx-0">+ <span className="font-bold tracking-tighter">Papermark</span>+ </Heading>+ <Heading className="text-2xl font-normal text-center p-0 mt-4 mb-8 mx-0">+ Thanks for for upgrading to Papermark Pro!+ </Heading>+ <Text className="text-sm leading-6 text-black">+ Hey{name && ` ${name}`}!+ </Text>+ <Text className="text-sm">+ My name is Marc, and I'm the creator of Papermark. I wanted+ to personally reach out to thank you for upgrading to Papermark Pro!+ </Text>+ <Text className="text-sm leading-6 text-black">+ As you might already know, we are a bootstrapped and{" "}+ <Link+ href="https://github.com/mfts/papermark"+ target="_blank"+ className="font-medium text-emerald-500 no-underline"+ >+ open-source+ </Link>{" "}+ business. Your support means the world to us and helps us continue+ to build and improve Papermark.+ </Text>+ <Text className="text-sm leading-6 text-black">+ On the Pro plan, you now have access to:+ </Text>+ <Text className="ml-1 text-sm leading-4 text-black">+ β Custom domains+ </Text>+ <Text className="ml-1 text-sm leading-4 text-black">+ β Unlimited link views+ </Text>+ <Text className="ml-1 text-sm leading-4 text-black">+ β Unlimited document uploads+ </Text>+ <Text className="ml-1 text-sm leading-4 text-black">+ β Unlimited team members (coming soon)+ </Text>+ <Section className="mt-4">+ <Text className="text-sm">+ Let me know if you have any questions or feedback. I'm+ always happy to help!+ </Text>+ <Text className="text-sm text-gray-400">Marc from Papermark</Text>+ </Section>+ <Hr />+ <Section className="mt-8 text-gray-400">+ <Text className="text-xs">+ Β© {new Date().getFullYear()}{" "}+ <a+ href="https://www.papermark.io"+ className="no-underline text-gray-400 hover:text-gray-400 visited:text-gray-400"+ target="_blank"+ >+ papermark.io+ </a>+ </Text>+ <Text className="text-xs">+ If you have any feedback or questions about this email, simply+ reply to it. I'd love to hear from you!+ </Text>+ </Section>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+};++export default UpgradePlanEmail;diff --git a/components/links/link-sheet/expiration-section.tsx b/components/links/link-sheet/expiration-section.tsxindex 4f638c37..9d5347e2 100644--- a/components/links/link-sheet/expiration-section.tsx+++ b/components/links/link-sheet/expiration-section.tsx@@ -1,7 +1,7 @@import { Dispatch, SetStateAction, useState, useEffect } from "react";import { Switch } from "@/components/ui/switch";import { motion } from "framer-motion";-import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/contants";+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";import { cn, getDateTimeLocal } from "@/lib/utils";import { DEFAULT_LINK_TYPE } from ".";diff --git a/components/links/link-sheet/password-section.tsx b/components/links/link-sheet/password-section.tsxindex b7da5695..5f4d5715 100644--- a/components/links/link-sheet/password-section.tsx+++ b/components/links/link-sheet/password-section.tsx@@ -1,7 +1,7 @@import { Dispatch, SetStateAction, useEffect, useState } from "react";import { Switch } from "@/components/ui/switch";import { motion } from "framer-motion";-import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/contants";+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";import Eye from "@/components/shared/icons/eye"import EyeOff from "@/components/shared/icons/eye-off"import { cn } from "@/lib/utils";diff --git a/components/ui/badge.tsx b/components/ui/badge.tsxnew file mode 100644index 00000000..f000e3ef--- /dev/null+++ b/components/ui/badge.tsx@@ -0,0 +1,36 @@+import * as React from "react"+import { cva, type VariantProps } from "class-variance-authority"++import { cn } from "@/lib/utils"++const badgeVariants = cva(+ "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",+ {+ variants: {+ variant: {+ default:+ "border-transparent bg-primary text-primary-foreground hover:bg-primary/80",+ secondary:+ "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",+ destructive:+ "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",+ outline: "text-foreground",+ },+ },+ defaultVariants: {+ variant: "default",+ },+ }+)++export interface BadgeProps+ extends React.HTMLAttributes<HTMLDivElement>,+ VariantProps<typeof badgeVariants> {}++function Badge({ className, variant, ...props }: BadgeProps) {+ return (+ <div className={cn(badgeVariants({ variant }), className)} {...props} />+ )+}++export { Badge, badgeVariants }diff --git a/components/welcome/intro.tsx b/components/welcome/intro.tsxindex 803eb476..bdb713fc 100644--- a/components/welcome/intro.tsx+++ b/components/welcome/intro.tsx@@ -1,6 +1,6 @@import { useRouter } from "next/router";import { motion } from "framer-motion";-import { STAGGER_CHILD_VARIANTS } from "@/lib/contants"+import { STAGGER_CHILD_VARIANTS } from "@/lib/constants"import { Button } from "../ui/button";export default function Intro() {diff --git a/components/welcome/next.tsx b/components/welcome/next.tsxindex ce1c3f9a..47818ec3 100644--- a/components/welcome/next.tsx+++ b/components/welcome/next.tsx@@ -1,7 +1,7 @@import { useRouter } from "next/router";import { motion } from "framer-motion";import { DocumentIcon, PresentationChartBarIcon } from "@heroicons/react/24/outline";-import { STAGGER_CHILD_VARIANTS } from "@/lib/contants";+import { STAGGER_CHILD_VARIANTS } from "@/lib/constants";export default function Next() {const router = useRouter();diff --git a/components/welcome/upload.tsx b/components/welcome/upload.tsxindex 295da9b8..dec6971e 100644--- a/components/welcome/upload.tsx+++ b/components/welcome/upload.tsx@@ -6,7 +6,7 @@ import DocumentUpload from "@/components/document-upload";import { ArrowRightIcon, DocumentDuplicateIcon } from "@heroicons/react/24/outline";import { toast } from "sonner";import Skeleton from "../Skeleton";-import { STAGGER_CHILD_VARIANTS } from "@/lib/contants";+import { STAGGER_CHILD_VARIANTS } from "@/lib/constants";import { pdfjs } from "react-pdf";import { copyToClipboard, getExtension } from "@/lib/utils";import { Button } from "../ui/button";diff --git a/lib/contants.ts b/lib/constants.tssimilarity index 100%rename from lib/contants.tsrename to lib/constants.tsdiff --git a/lib/emails/send-upgrade-plan.ts b/lib/emails/send-upgrade-plan.tsnew file mode 100644index 00000000..2031acdb--- /dev/null+++ b/lib/emails/send-upgrade-plan.ts@@ -0,0 +1,13 @@+import { sendEmail } from "@/lib/resend";+import UpgradePlanEmail from "@/components/emails/upgrade-plan";+import { CreateUserEmailProps } from "../types";++export const sendUpgradePlanEmail = async (params: CreateUserEmailProps) => {+ const { name, email } = params.user;+ const emailTemplate = UpgradePlanEmail({ name });+ await sendEmail({+ to: email as string,+ subject: "Thank you for upgrading to Papermark Pro!",+ react: emailTemplate,+ });+};diff --git a/lib/emails/send-welcome.ts b/lib/emails/send-welcome.tsindex d6acd3c9..ba7654f4 100644--- a/lib/emails/send-welcome.ts+++ b/lib/emails/send-welcome.ts@@ -10,6 +10,5 @@ export const sendWelcomeEmail = async (params: CreateUserEmailProps) => {to: email as string,subject: "Welcome to Papermark.io!",react: emailTemplate,- reply_to: "[email protected]"});};\ No newline at end of filediff --git a/lib/middleware/domain.ts b/lib/middleware/domain.tsindex 5a9c983e..ef28fd79 100644--- a/lib/middleware/domain.ts+++ b/lib/middleware/domain.ts@@ -1,6 +1,6 @@import { NextRequest, NextResponse } from "next/server";import { getToken } from "next-auth/jwt";-import { PAPERMARK_HEADERS } from "../contants";+import { PAPERMARK_HEADERS } from "../constants";export default async function DomainMiddleware(req: NextRequest) {const path = req.nextUrl.pathname;diff --git a/lib/stripe/client.ts b/lib/stripe/client.tsnew file mode 100644index 00000000..6a0000a6--- /dev/null+++ b/lib/stripe/client.ts@@ -0,0 +1,16 @@+// Stripe Client SDK+import { Stripe as StripeProps, loadStripe } from "@stripe/stripe-js";++let stripePromise: Promise<StripeProps | null>;++export const getStripe = () => {+ if (!stripePromise) {+ stripePromise = loadStripe(+ process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY_LIVE ??+ process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ??+ ""+ );+ }++ return stripePromise;+};diff --git a/lib/stripe/index.ts b/lib/stripe/index.tsnew file mode 100644index 00000000..3ded5b77--- /dev/null+++ b/lib/stripe/index.ts@@ -0,0 +1,35 @@+import Stripe from "stripe";++export const stripe = new Stripe(+ process.env.STRIPE_SECRET_KEY_LIVE ?? process.env.STRIPE_SECRET_KEY ?? "",+ {+ apiVersion: "2023-08-16",+ appInfo: {+ name: "Papermark.io",+ version: "0.1.0",+ },+ }+);+++export async function cancelSubscription(customer?: string) {+ if (!customer) return;++ try {+ const subscriptionId = await stripe.subscriptions+ .list({+ customer,+ })+ .then((res) => res.data[0].id);++ return await stripe.subscriptions.update(subscriptionId, {+ cancel_at_period_end: true,+ cancellation_details: {+ comment: "Customer deleted their Papermark instance.",+ },+ });+ } catch (error) {+ console.log("Error cancelling Stripe subscription", error);+ return;+ }+}diff --git a/lib/stripe/utils.ts b/lib/stripe/utils.tsnew file mode 100644index 00000000..765a21b2--- /dev/null+++ b/lib/stripe/utils.ts@@ -0,0 +1,63 @@+import type Stripe from "stripe";++export function getPlanFromPriceId(priceId: string) {+ const env =+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";+ return PLANS.find(+ (plan) =>+ plan.price.monthly.priceIds[env] === priceId ||+ plan.price.yearly.priceIds[env] === priceId+ )!;+}++// custom type coercion because Stripe's types are wrong+export function isNewCustomer(+ previousAttributes: // Stripe.Event.Data.PreviousAttributes | undefined+ | {+ default_payment_method?: string;+ items?: {+ data?: {+ price?: {+ id?: string;+ }[];+ };+ };+ }+ | undefined+) {+ let isNewCustomer = false;+ try {+ if (+ // if the user is upgrading from free to pro+ previousAttributes?.default_payment_method === null+ ) {+ isNewCustomer = true;+ }+ } catch (error) {+ console.error("An error occurred:", error);+ }+ return isNewCustomer;+}++export const PLANS = [+ {+ name: "Pro",+ slug: "pro",+ price: {+ monthly: {+ amount: 29,+ priceIds: {+ test: "price_1NmHGzFJyGSZ96lhp946ODFI",+ production: "",+ },+ },+ yearly: {+ amount: 290,+ priceIds: {+ test: "price_1NmHHaFJyGSZ96lhXxg2fTr7",+ production: "",+ },+ },+ },+ },+];diff --git a/lib/swr/use-billing.ts b/lib/swr/use-billing.tsnew file mode 100644index 00000000..87af5801--- /dev/null+++ b/lib/swr/use-billing.ts@@ -0,0 +1,32 @@+import { useRouter } from "next/router";+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { useMemo } from "react";++interface BillingProps {+ id: string;+ plan: string;+ startsAt: Date | null;+ endsAt: Date | null;+ subscriptionId: string | null;+ _count: {+ documents: number;+ };+}++export function useBilling() {+ const { data, error } = useSWR<BillingProps>(+ `/api/billing`,+ fetcher,+ {+ dedupingInterval: 30000,+ }+ );+++ return {+ ...data,+ error,+ loading: !data && !error,+ };+}diff --git a/lib/utils.ts b/lib/utils.tsindex ed351412..880ab589 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -193,4 +193,34 @@ export function copyToClipboard(text: string, message: string): void {.catch((error) => {toast.error("Failed to copy. Please try again.")});+}++export const getFirstAndLastDay = (day: number) => {+ const today = new Date();+ const currentDay = today.getDate();+ const currentMonth = today.getMonth();+ const currentYear = today.getFullYear();+ if (currentDay >= day) {+ // if the current day is greater than target day, it means that we just passed it+ return {+ firstDay: new Date(currentYear, currentMonth, day),+ lastDay: new Date(currentYear, currentMonth + 1, day - 1),+ };+ } else {+ // if the current day is less than target day, it means that we haven't passed it yet+ const lastYear = currentMonth === 0 ? currentYear - 1 : currentYear; // if the current month is January, we need to go back a year+ const lastMonth = currentMonth === 0 ? 11 : currentMonth - 1; // if the current month is January, we need to go back to December+ return {+ firstDay: new Date(lastYear, lastMonth, day),+ lastDay: new Date(currentYear, currentMonth, day - 1),+ };+ }+};++export const formattedDate = (date: Date) => {+ return new Date(date).toLocaleDateString("en-US", {+ month: "short",+ day: "2-digit",+ year: "numeric",+ });}\ No newline at end of filediff --git a/package-lock.json b/package-lock.jsonindex 5fbe441f..27b3d2a3 100644--- a/package-lock.json+++ b/package-lock.json@@ -25,6 +25,7 @@"@radix-ui/react-slot": "^1.0.2","@radix-ui/react-switch": "^1.0.3","@react-email/components": "^0.0.7",+ "@stripe/stripe-js": "^2.1.1","@tremor/react": "^3.6.6","@types/node": "^20.5.6","@types/react": "^18.2.21",@@ -55,6 +56,7 @@"react-pdf": "^7.3.3","resend": "^0.17.2","sonner": "^0.6.2",+ "stripe": "^13.4.0","swr": "^2.2.1","tailwind-merge": "^1.14.0","tailwindcss": "^3.3.3",@@ -2492,6 +2494,11 @@"@sinonjs/commons": "^3.0.0"}},+ "node_modules/@stripe/stripe-js": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-2.1.1.tgz",+ "integrity": "sha512-V+0z21/YNbvIX0b2Fo6mE4w5kiihrdytAwVPG66RRWvkAe4COumywRfaWrBTmVQF2aAmxoRpeyTM1LKWbiOK6Q=="+ },"node_modules/@swc/helpers": {"version": "0.5.1","resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.1.tgz",@@ -7958,6 +7965,20 @@"node": ">=6"}},+ "node_modules/qs": {+ "version": "6.11.2",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.2.tgz",+ "integrity": "sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==",+ "dependencies": {+ "side-channel": "^1.0.4"+ },+ "engines": {+ "node": ">=0.6"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/querystringify": {"version": "2.2.0","resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",@@ -9145,6 +9166,18 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/stripe": {+ "version": "13.4.0",+ "resolved": "https://registry.npmjs.org/stripe/-/stripe-13.4.0.tgz",+ "integrity": "sha512-UxvRzu46AJALIueMH3/jn++qJlOoM5s+uoHXagr36xTFOj7Knrh28WFiI73dMDkngBElK68cG3WI+LgRulHw6g==",+ "dependencies": {+ "@types/node": ">=8.1.0",+ "qs": "^6.11.0"+ },+ "engines": {+ "node": ">=12.*"+ }+ },"node_modules/style-to-js": {"version": "1.1.3","resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.3.tgz",@@ -11695,6 +11728,11 @@"@sinonjs/commons": "^3.0.0"}},+ "@stripe/stripe-js": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-2.1.1.tgz",+ "integrity": "sha512-V+0z21/YNbvIX0b2Fo6mE4w5kiihrdytAwVPG66RRWvkAe4COumywRfaWrBTmVQF2aAmxoRpeyTM1LKWbiOK6Q=="+ },"@swc/helpers": {"version": "0.5.1","resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.1.tgz",@@ -15562,6 +15600,14 @@"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz","integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA=="},+ "qs": {+ "version": "6.11.2",+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.2.tgz",+ "integrity": "sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==",+ "requires": {+ "side-channel": "^1.0.4"+ }+ },"querystringify": {"version": "2.2.0","resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",@@ -16393,6 +16439,15 @@"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz","integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig=="},+ "stripe": {+ "version": "13.4.0",+ "resolved": "https://registry.npmjs.org/stripe/-/stripe-13.4.0.tgz",+ "integrity": "sha512-UxvRzu46AJALIueMH3/jn++qJlOoM5s+uoHXagr36xTFOj7Knrh28WFiI73dMDkngBElK68cG3WI+LgRulHw6g==",+ "requires": {+ "@types/node": ">=8.1.0",+ "qs": "^6.11.0"+ }+ },"style-to-js": {"version": "1.1.3","resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.3.tgz",diff --git a/package.json b/package.jsonindex 3b6d6e61..1c046fb0 100644--- a/package.json+++ b/package.json@@ -30,6 +30,7 @@"@radix-ui/react-slot": "^1.0.2","@radix-ui/react-switch": "^1.0.3","@react-email/components": "^0.0.7",+ "@stripe/stripe-js": "^2.1.1","@tremor/react": "^3.6.6","@types/node": "^20.5.6","@types/react": "^18.2.21",@@ -60,6 +61,7 @@"react-pdf": "^7.3.3","resend": "^0.17.2","sonner": "^0.6.2",+ "stripe": "^13.4.0","swr": "^2.2.1","tailwind-merge": "^1.14.0","tailwindcss": "^3.3.3",diff --git a/pages/_app.tsx b/pages/_app.tsxindex f18eb2c4..1e86707d 100644--- a/pages/_app.tsx+++ b/pages/_app.tsx@@ -24,7 +24,7 @@ export default function App({<ThemeProvider attribute="class" defaultTheme="system" enableSystem><PlausibleProviderdomain="papermark.io"- enabled={process.env.VERCEL_ENV == "production"}+ enabled={process.env.NEXT_PUBLIC_VERCEL_ENV === "production"}><main className={inter.className}><Toaster closeButton richColors theme={"system"} />diff --git a/pages/api/billing/index.ts b/pages/api/billing/index.tsnew file mode 100644index 00000000..cec31838--- /dev/null+++ b/pages/api/billing/index.ts@@ -0,0 +1,44 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import { authOptions } from "../auth/[...nextauth]";+import { CustomUser } from "@/lib/types";+import prisma from "@/lib/prisma";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method === "GET") {+ // POST /api/billing/manage β manage a user's subscription+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ const user = await prisma.user.findUnique({+ where: { id: (session.user as CustomUser).id },+ select: {+ id: true,+ subscriptionId: true,+ startsAt: true,+ endsAt: true,+ plan: true,+ _count: {+ select: { documents: true },+ },+ },+ });++ if (!user) {+ return res.status(400).json({ error: "User does not exists" });+ }++ // console.log("user", user);++ return res.status(200).json(user);+ } else {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/billing/manage.ts b/pages/api/billing/manage.tsnew file mode 100644index 00000000..5d41c083--- /dev/null+++ b/pages/api/billing/manage.ts@@ -0,0 +1,41 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import { authOptions } from "../auth/[...nextauth]";+import { CustomUser } from "@/lib/types";+import { stripe } from "@/lib/stripe";+import prisma from "@/lib/prisma";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method === "POST") {+ // POST /api/billing/manage β manage a user's subscription+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ const user = await prisma.user.findUnique({+ where: { id: (session.user as CustomUser).id },+ select: { stripeId: true },+ });++ if (!user) {+ return res.status(400).json({ error: "User does not exists" });+ }+ if (!user.stripeId) {+ return res.status(400).json({ error: "No Stripe customer ID" });+ }++ const { url } = await stripe.billingPortal.sessions.create({+ customer: user.stripeId,+ return_url: `${process.env.NEXTAUTH_URL}/settings/billing`,+ });+ return res.status(200).json(url);+ } else {+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/billing/upgrade.ts b/pages/api/billing/upgrade.tsnew file mode 100644index 00000000..e3be4621--- /dev/null+++ b/pages/api/billing/upgrade.ts@@ -0,0 +1,43 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import { authOptions } from "../auth/[...nextauth]";+import { CustomUser } from "@/lib/types";+import { stripe } from "@/lib/stripe";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method === "POST") {+ // POST /api/billing/upgrade+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ const { priceId } = req.query as { priceId: string };++ const stripeSession = await stripe.checkout.sessions.create({+ customer_email: (session.user as CustomUser).email ?? undefined,+ billing_address_collection: "required",+ success_url: `${process.env.NEXTAUTH_URL}/settings/billing?success=true`,+ cancel_url: `${process.env.NEXTAUTH_URL}/settings/billing`,+ line_items: [{ price: priceId, quantity: 1 }],+ automatic_tax: {+ enabled: true,+ },+ tax_id_collection: {+ enabled: true,+ },+ mode: "subscription",+ allow_promotion_codes: true,+ client_reference_id: (session.user as CustomUser).id,+ });+ return res.status(200).json(stripeSession);+ } else {+ // We only allow POST requests+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.tsnew file mode 100644index 00000000..193ac9ae--- /dev/null+++ b/pages/api/stripe/webhook.ts@@ -0,0 +1,163 @@+import { NextApiRequest, NextApiResponse } from "next";+import { Readable } from "node:stream";+import Stripe from "stripe";+import prisma from "@/lib/prisma";+import { stripe } from "@/lib/stripe";+import { getPlanFromPriceId, isNewCustomer } from "@/lib/stripe/utils";+import { log } from "@/lib/utils";+import { sendUpgradePlanEmail } from "@/lib/emails/send-upgrade-plan";++// Stripe requires the raw body to construct the event.+export const config = {+ api: {+ bodyParser: false,+ },+};++async function buffer(readable: Readable) {+ const chunks: Buffer[] = [];+ 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",+ "customer.subscription.updated",+ "customer.subscription.deleted",+]);++export default async function webhookHandler(+ req: NextApiRequest,+ res: NextApiResponse+) {+ // POST /api/stripe/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 {+ if (event.type === "checkout.session.completed") {+ const checkoutSession = event.data.object as Stripe.Checkout.Session;++ if (+ checkoutSession.client_reference_id === null ||+ checkoutSession.customer === null+ ) {+ await log("Missing items in Stripe webhook callback");+ return;+ }++ // when the project subscribes to a plan, set their stripe customer ID+ // in the database for easy identification in future webhook events++ await prisma.user.update({+ where: {+ id: checkoutSession.client_reference_id,+ },+ data: {+ stripeId: checkoutSession.customer.toString(),+ },+ });++ // for subscription updates+ } else if (event.type === "customer.subscription.updated") {+ const subscriptionUpdated = event.data.object as Stripe.Subscription;+ const priceId = subscriptionUpdated.items.data[0].price.id;+ const newCustomer = isNewCustomer(event.data.previous_attributes);++ const plan = getPlanFromPriceId(priceId);+ const stripeId = subscriptionUpdated.customer.toString();+ const subscriptionId = subscriptionUpdated.id;+ const startsAt = new Date(subscriptionUpdated.current_period_start * 1000);+ const endsAt = new Date(subscriptionUpdated.current_period_end * 1000);++ // If a project upgrades/downgrades their subscription, update their usage limit in the database.+ const user = await prisma.user.update({+ where: {+ stripeId,+ },+ data: {+ plan: plan.slug,+ subscriptionId,+ startsAt,+ endsAt,+ },+ });+ if (!user) {+ await log("User not found in Stripe webhook `customer.subscription.created` callback");+ return;+ }++ // Send thank you email to project owner if they are a new customer+ if (newCustomer) {+ await sendUpgradePlanEmail({user: {email: user.email as string, name: user.name as string}});+ }++ // If project cancels their subscription+ } else if (event.type === "customer.subscription.deleted") {+ const subscriptionDeleted = event.data.object as Stripe.Subscription;++ const stripeId = subscriptionDeleted.customer.toString();++ // If a project deletes their subscription, reset their usage limit in the database to 1000.+ // Also remove the root domain redirect for all their domains from Redis.+ const user = await prisma.user.findUnique({+ where: {+ stripeId,+ },+ select: {+ id: true,+ name: true,+ domains: true,+ },+ });++ if (!user) {+ await log("User not found in Stripe webhook `customer.subscription.deleted` callback");+ return;+ }++ await Promise.all([+ prisma.user.update({+ where: {+ stripeId,+ },+ data: {+ plan: "free",+ subscriptionId: null,+ endsAt: null,+ startsAt: null,+ },+ }),+ log(":cry: User *`" + user.id + "`* deleted their subscription"),+ ]);+ } else {+ throw new Error("Unhandled relevant event!");+ }+ } catch (error) {+ await log(`Stripe webook failed. Error: ${(error as Error).message}`);+ return res+ .status(400)+ .send('Webhook error: "Webhook handler failed. View logs."');+ }+ } else {+ return res.status(400).send(`π€·ββοΈ Unhandled event type: ${event.type}`);+ }++ res.status(200).json({ received: true });+ } else {+ res.setHeader("Allow", ["POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/settings/billing.tsx b/pages/settings/billing.tsxnew file mode 100644index 00000000..dd2466da--- /dev/null+++ b/pages/settings/billing.tsx@@ -0,0 +1,190 @@+import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";+import AppLayout from "@/components/layouts/app";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { useBilling } from "@/lib/swr/use-billing";+import { formattedDate, getFirstAndLastDay } from "@/lib/utils";+import { useRouter } from "next/router";+import { useEffect, useMemo, useState } from "react";+import { toast } from "sonner";++export default function Billing() {+ const router = useRouter();+ const { plan, startsAt, endsAt } = useBilling()+ const [clicked, setClicked] = useState<boolean>(false);++ useEffect(() => {+ if (router.query.success) {+ toast.success("Upgrade success!");+ // setTimeout(() => {+ // mutate(`/api/projects/${slug}`);+ // // track upgrade to pro event+ // va.track("Upgraded Plan", {+ // plan: "pro",+ // });+ // }, 1000);+ }+ }, [router.query.success]);++ return (+ <AppLayout>+ <div className="p-4 sm:p-4 sm:m-4">+ <div className="flex items-center justify-between mb-4 md:mb-8 lg:mb-12">+ <div className="space-y-1">+ <h2 className="text-2xl text-foreground font-semibold tracking-tight">+ Billing+ </h2>+ <p className="text-sm text-muted-foreground">+ Manage your subscription+ </p>+ </div>+ </div>++ <div>+ <div className="rounded-lg border border-border bg-secondary">+ <div className="flex flex-col space-y-3 p-10">+ <h2 className="text-xl font-medium">Plan & Usage</h2>+ <p className="text-sm text-secondary-foreground">+ You are currently on the{" "}+ {plan ? (+ <Badge>{plan}</Badge>+ ) : (+ <span className="rounded-full bg-border px-2 py-0.5 text-xs text-foreground">+ load+ </span>+ )}{" "}+ plan.+ {endsAt && startsAt && (+ <>+ {" "}+ Current billing cycle:{" "}+ <span className="font-medium text-foreground">+ {`${formattedDate(startsAt)} - ${formattedDate(endsAt)}`}+ </span>+ .+ </>+ )}+ </p>+ </div>+ <div className="border-b border-gray-200 dark:border-gray-700" />+ <div className="grid grid-cols-1 divide-y divide-gray-200 dark:divide-gray-700 sm:grid-cols-2 sm:divide-x sm:divide-y-0">+ {/* <div className="p-10">+ <div className="flex items-center space-x-2">+ <h3 className="font-medium">Total Documents</h3>+ </div>+ {plan === "enterprise" ? (+ <div className="mt-4 flex items-center">+ {usage || usage === 0 ? (+ <Number value={usage}>+ <p className="text-2xl font-semibold text-black">+ {nFormatter(usage)}+ </p>+ </Number>+ ) : (+ <div className="h-8 w-8 animate-pulse rounded-md bg-gray-200" />+ )}+ <Divider className="h-8 w-8 text-gray-500" />+ <Infinity className="h-8 w-8 text-gray-500" />+ </div>+ ) : (+ <div className="mt-2 flex flex-col space-y-2">+ {usage !== undefined && usageLimit ? (+ <p className="text-sm text-gray-600">+ <Number value={usage}>+ <span>{nFormatter(usage)} </span>+ </Number>+ / {nFormatter(usageLimit)} clicks (+ {((usage / usageLimit) * 100).toFixed(1)}%)+ </p>+ ) : (+ <div className="h-5 w-32 animate-pulse rounded-md bg-gray-200" />+ )}+ <div className="h-3 w-full overflow-hidden rounded-full bg-gray-200">+ <motion.div+ initial={{ width: 0 }}+ animate={{+ width:+ usage !== undefined && usageLimit+ ? (usage / usageLimit) * 100 + "%"+ : "0%",+ }}+ transition={{ duration: 0.5, type: "spring" }}+ className={`${+ usage && usageLimit && usage > usageLimit+ ? "bg-red-500"+ : "bg-blue-500"+ } h-3 rounded-full`}+ />+ </div>+ </div>+ )}+ </div> */}+ {/* <div className="p-10">+ <div className="flex items-center space-x-2">+ <h3 className="font-medium">Number of Links</h3>+ <InfoTooltip content="Number of short links in your project." />+ </div>+ <div className="mt-4 flex items-center">+ {links || links === 0 ? (+ <Number value={links} unit="links">+ <p className="text-2xl font-semibold text-black">+ {nFormatter(links)}+ </p>+ </Number>+ ) : (+ <div className="h-8 w-8 animate-pulse rounded-md bg-gray-200" />+ )}+ <Divider className="h-8 w-8 text-gray-500" />+ <Infinity className="h-8 w-8 text-gray-500" />+ </div>+ </div> */}+ </div>+ <div className="border-b border-gray-200 dark:border-gray-700" />+ <div className="flex flex-col items-center justify-between space-y-3 px-10 py-4 text-center sm:flex-row sm:space-y-0 sm:text-left">+ {plan ? (+ <p className="text-sm text-muted-foreground">+ {plan === "pro"+ ? "On the Pro plan, the sky's the limit! Thank you for your support."+ : "For higher limits, upgrade to the Pro plan."}+ </p>+ ) : (+ <div className="h-3 w-28 animate-pulse rounded-full bg-border" />+ )}+ <div>+ {plan ? (+ plan === "free" ? (+ <UpgradePlanModal>+ <Button type="button">Upgrade</Button>+ </UpgradePlanModal>+ ) : (+ <Button+ onClick={() => {+ setClicked(true);+ fetch(`/api/billing/manage`, {+ method: "POST",+ })+ .then(async (res) => {+ const url = await res.json();+ router.push(url);+ })+ .catch((err) => {+ alert(err);+ setClicked(false);+ });+ }}+ loading={clicked}+ >+ Manage Subscription+ </Button>+ )+ ) : (+ <div className="h-10 w-24 animate-pulse rounded-md bg-border" />+ )}+ </div>+ </div>+ </div>+ </div>+ </div>+ </AppLayout>+ );+}diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 8b67acb9..c24d8f54 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -38,16 +38,21 @@ model Session {}model User {- id String @id @default(cuid())- name String?- email String? @unique- emailVerified DateTime?- image String?- createdAt DateTime @default(now())- accounts Account[]- sessions Session[]- documents Document[]- domains Domain[]+ id String @id @default(cuid())+ name String?+ email String? @unique+ emailVerified DateTime?+ image String?+ createdAt DateTime @default(now())+ accounts Account[]+ sessions Session[]+ documents Document[]+ domains Domain[]+ plan String @default("free")+ stripeId String? @unique // Stripe subscription / customer ID+ subscriptionId String? @unique // Stripe subscription ID+ startsAt DateTime? // Stripe subscription start date+ endsAt DateTime? // Stripe subscription end date}model VerificationToken {@@ -116,4 +121,4 @@ model View {documentId StringviewerEmail String? // Email of the viewer if knownviewedAt DateTime @default(now())-}\ No newline at end of file+}