Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
fix: stripe webhook
Marc Seitz73ee7763c49b
diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.tsindex c596caf1..64bc6a60 100644--- a/pages/api/stripe/webhook.ts+++ b/pages/api/stripe/webhook.ts@@ -29,9 +29,23 @@ const relevantEvents = new Set(["customer.subscription.deleted",]);+interface SubscriptionInfo {+ plan: {+ name: string;+ slug: string;+ price: { monthly: any; yearly: any };+ };+ subscriptionId: string;+ startsAt: Date;+ endsAt: Date;+ newCustomer: boolean;+}++const pendingSubscriptionUpdates = new Map<string, SubscriptionInfo>();+export default async function webhookHandler(req: NextApiRequest,- res: NextApiResponse+ res: NextApiResponse,) {// POST /api/stripe/webhook – listen to Stripe webhooksif (req.method === "POST") {@@ -46,6 +60,7 @@ export default async function webhookHandler(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") {@@ -59,17 +74,57 @@ export default async function webhookHandler(return;}- // when the project subscribes to a plan, set their stripe customer ID- // in the database for easy identification in future webhook events+ const clientReferenceId = checkoutSession.client_reference_id;+ const stripeId = checkoutSession.customer.toString();- await prisma.user.update({- where: {- id: checkoutSession.client_reference_id,- },- data: {- stripeId: checkoutSession.customer.toString(),- },- });+ // Check if there are pending subscription updates for this user+ if (pendingSubscriptionUpdates.has(stripeId)) {+ const pendingUpdate = pendingSubscriptionUpdates.get(stripeId);+ const { plan, subscriptionId, startsAt, endsAt, newCustomer } =+ pendingUpdate as SubscriptionInfo;++ // Update the user with the subscription information and stripeId+ const team = await prisma.team.update({+ where: {+ id: clientReferenceId,+ },+ data: {+ stripeId,+ plan: plan.slug,+ subscriptionId,+ startsAt,+ endsAt,+ },+ select: {+ id: true,+ users: {+ where: { role: "ADMIN" },+ select: {+ user: { select: { id: true, email: true, name: true } },+ },+ },+ },+ });++ // Send thank you email to project owner if they are a new customer+ if (newCustomer) {+ await sendUpgradePlanEmail({+ user: {+ email: team.users[0].user.email as string,+ name: team.users[0].user.name as string,+ },+ });+ }++ await identifyUser(team.users[0].user.id);+ await trackAnalytics({+ event: "User Upgraded",+ email: team.users[0].user.email,+ });++ // Remove the pending update from the store+ pendingSubscriptionUpdates.delete(stripeId);+ }// for subscription updates} else if (event.type === "customer.subscription.updated") {@@ -81,42 +136,18 @@ export default async function webhookHandler(const stripeId = subscriptionUpdated.customer.toString();const subscriptionId = subscriptionUpdated.id;const startsAt = new Date(- subscriptionUpdated.current_period_start * 1000+ subscriptionUpdated.current_period_start * 1000,);const endsAt = new Date(- subscriptionUpdated.current_period_end * 1000+ 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 },- });- }-- await identifyUser(user.id);- await trackAnalytics({- event: "User Upgraded",- email: user.email,+ pendingSubscriptionUpdates.set(stripeId, {+ plan,+ subscriptionId,+ startsAt,+ endsAt,+ newCustomer,});// If project cancels their subscription@@ -138,7 +169,9 @@ export default async function webhookHandler(});if (!user) {- await log("User not found in Stripe webhook `customer.subscription.deleted` callback");+ await log(+ "User not found in Stripe webhook `customer.subscription.deleted` callback",+ );return;}diff --git a/pages/api/teams/[teamId]/billing/manage.ts b/pages/api/teams/[teamId]/billing/manage.tsindex b1c66854..aab34417 100644--- a/pages/api/teams/[teamId]/billing/manage.ts+++ b/pages/api/teams/[teamId]/billing/manage.ts@@ -1,14 +1,13 @@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";import { errorhandler } from "@/lib/errorHandler";export default async function handle(req: NextApiRequest,- res: NextApiResponse+ res: NextApiResponse,) {if (req.method === "POST") {// POST /api/teams/:teamId/billing/manage – manage a user's subscriptiondiff --git a/pages/settings/billing.tsx b/pages/settings/billing.tsxindex d4e8a94e..60df7872 100644--- a/pages/settings/billing.tsx+++ b/pages/settings/billing.tsx@@ -16,6 +16,7 @@ interface Tier {title: string;priceMonthly: string;currentPlan: boolean;+ hasPlan: boolean;isTrial?: boolean;description: string;features: string[];@@ -48,6 +49,7 @@ export default function Billing() {priceMonthly: "€0/mo",description: "Enjoy free access",currentPlan: plan && plan == "free" ? true : false,+ hasPlan: false,features: ["PDF up to 30 mb","Unlimited links",@@ -65,6 +67,7 @@ export default function Billing() {priceMonthly: "€15/mo",description: "All free features +",currentPlan: plan && plan == "starter" ? true : false,+ hasPlan: plan && plan !== "free" ? true : false,features: ["Custom domains","Unlimited documents",@@ -78,6 +81,7 @@ export default function Billing() {priceMonthly: "€30/mo",description: "All features and more",currentPlan: plan && plan == "pro" ? true : false,+ hasPlan: plan && plan !== "free" ? true : false,isTrial: plan && plan == "trial" ? true : false,features: ["Team members",@@ -121,46 +125,48 @@ export default function Billing() {<divkey={tier.id}className={cn(- `rounded-3xl p-8 sm:p-10 bg-white dark:bg-gray-800`,+ `rounded-3xl p-8 sm:p-10 bg-white dark:bg-gray-800 flex flex-col justify-between h-full`,tier.currentPlan || tier.isTrial? "ring-2 ring-primary": "ring-1 ring-gray-900/10 dark:ring-gray-200/10",)}>- <h2 className="text-xl font-bold mb-4 inline-flex items-center gap-x-2">- {tier.title}{" "}- {tier.currentPlan ? (- <Badge className="rounded-none">Current Plan</Badge>- ) : null}- {tier.isTrial ? (- <Badge className="rounded-none">Trial</Badge>- ) : null}- </h2>- <div className="text-3xl font-bold mb-4">- {tier.priceMonthly}- </div>- <div className="text-gray-900 dark:text-gray-400 mb-6">- {tier.description}- </div>- {tier.features.map((feature) => (- <div key={feature} className="flex items-center mb-2">- <svg- className="h-5 w-5 text-green-500 dark:text-green-300 mr-2"- fill="none"- stroke="currentColor"- viewBox="0 0 24 24"- xmlns="http://www.w3.org/2000/svg"- >- <path- strokeLinecap="round"- strokeLinejoin="round"- strokeWidth="2"- d="M5 13l4 4L19 7"- ></path>- </svg>- {feature}+ <div className="">+ <h2 className="text-xl font-bold mb-4 inline-flex items-center gap-x-2">+ {tier.title}{" "}+ {tier.currentPlan ? (+ <Badge className="rounded-none">Current Plan</Badge>+ ) : null}+ {tier.isTrial ? (+ <Badge className="rounded-none">Trial</Badge>+ ) : null}+ </h2>+ <div className="text-3xl font-bold mb-4">+ {tier.priceMonthly}+ </div>+ <div className="text-gray-900 dark:text-gray-400 mb-6">+ {tier.description}</div>- ))}+ {tier.features.map((feature) => (+ <div key={feature} className="flex items-center mb-2">+ <svg+ className="h-5 w-5 text-green-500 dark:text-green-300 mr-2"+ fill="none"+ stroke="currentColor"+ viewBox="0 0 24 24"+ xmlns="http://www.w3.org/2000/svg"+ >+ <path+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="2"+ d="M5 13l4 4L19 7"+ ></path>+ </svg>+ {feature}+ </div>+ ))}+ </div><div className="mt-6 flex items-center justify-center gap-x-6">{tier.id === 1 &&(plan ? (@@ -183,8 +189,13 @@ export default function Billing() {))}{tier.id === 2 &&(plan ? (- tier.currentPlan ? (+ tier.hasPlan ? (<Button+ className={cn(+ !tier.currentPlan &&+ "border border-gray-700 dark:bg-secondary hover:dark:border-gray-500 hover:dark:bg-gray-700",+ )}+ variant={tier.currentPlan ? "default" : "outline"}onClick={() => {setClicked(true);fetch(