Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

refactor: componentize stripe webhook response functions

Marc Seitz42c9c6e3e36b
diff --git a/lib/stripe/index.ts b/lib/stripe/index.ts
index b926fb66..2995b8d0 100644
--- a/lib/stripe/index.ts
+++ b/lib/stripe/index.ts
@@ -3,11 +3,12 @@ import Stripe from "stripe";
export const stripe = new Stripe(
process.env.STRIPE_SECRET_KEY_LIVE ?? process.env.STRIPE_SECRET_KEY ?? "",
{
- apiVersion: "2023-10-16",
+ apiVersion: "2024-06-20",
appInfo: {
name: "Papermark.io",
version: "0.1.0",
},
+ typescript: true,
},
);
diff --git a/lib/stripe/webhooks/checkout-session-completed.ts b/lib/stripe/webhooks/checkout-session-completed.ts
new file mode 100644
index 00000000..ef41af43
--- /dev/null
+++ b/lib/stripe/webhooks/checkout-session-completed.ts
@@ -0,0 +1,91 @@
+import {
+ BUSINESS_PLAN_LIMITS,
+ DATAROOMS_PLAN_LIMITS,
+ PRO_PLAN_LIMITS,
+} from "@/ee/limits/constants";
+import Stripe from "stripe";
+
+import { sendUpgradePlanEmail } from "@/lib/emails/send-upgrade-plan";
+import prisma from "@/lib/prisma";
+import { stripe } from "@/lib/stripe";
+import { log } from "@/lib/utils";
+
+import { getPlanFromPriceId } from "../utils";
+
+export async function checkoutSessionCompleted(event: Stripe.Event) {
+ const checkoutSession = event.data.object as Stripe.Checkout.Session;
+
+ if (
+ checkoutSession.client_reference_id === null ||
+ checkoutSession.customer === null
+ ) {
+ await log({
+ message: "Missing items in Stripe webhook callback",
+ type: "error",
+ });
+ return;
+ }
+
+ const subscription = await stripe.subscriptions.retrieve(
+ checkoutSession.subscription as string,
+ );
+ const priceId = subscription.items.data[0].price.id;
+ const subscriptionId = subscription.id;
+ const subscriptionStart = new Date(subscription.current_period_start * 1000);
+ const subscriptionEnd = new Date(subscription.current_period_end * 1000);
+
+ const plan = getPlanFromPriceId(priceId);
+
+ if (!plan) {
+ await log({
+ message: `Invalid price ID in checkout.session.completed event: ${priceId}`,
+ type: "error",
+ });
+ return;
+ }
+
+ const stripeId = checkoutSession.customer.toString();
+ const teamId = checkoutSession.client_reference_id;
+
+ let planLimits = structuredClone(PRO_PLAN_LIMITS);
+ if (plan.slug === "pro") {
+ planLimits = structuredClone(PRO_PLAN_LIMITS);
+ } else if (plan.slug === "business") {
+ planLimits = structuredClone(BUSINESS_PLAN_LIMITS);
+ } else if (plan.slug === "datarooms") {
+ planLimits = structuredClone(DATAROOMS_PLAN_LIMITS);
+ }
+
+ // Update the user with the subscription information and stripeId
+ const team = await prisma.team.update({
+ where: {
+ id: teamId,
+ },
+ data: {
+ stripeId,
+ plan: plan.slug,
+ subscriptionId,
+ startsAt: subscriptionStart,
+ endsAt: subscriptionEnd,
+ limits: planLimits,
+ },
+ 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
+ await sendUpgradePlanEmail({
+ user: {
+ email: team.users[0].user.email as string,
+ name: team.users[0].user.name as string,
+ },
+ planType: plan.name,
+ });
+}
diff --git a/lib/stripe/webhooks/customer-subscription-deleted.ts b/lib/stripe/webhooks/customer-subscription-deleted.ts
new file mode 100644
index 00000000..0f200236
--- /dev/null
+++ b/lib/stripe/webhooks/customer-subscription-deleted.ts
@@ -0,0 +1,55 @@
+import { NextApiResponse } from "next";
+
+import { FREE_PLAN_LIMITS } from "@/ee/limits/constants";
+import Stripe from "stripe";
+
+import prisma from "@/lib/prisma";
+import { log } from "@/lib/utils";
+
+export async function customerSubscriptionDeleted(
+ event: Stripe.Event,
+ res: NextApiResponse,
+) {
+ const subscriptionDeleted = event.data.object as Stripe.Subscription;
+
+ const stripeId = subscriptionDeleted.customer.toString();
+ const subscriptionId = subscriptionDeleted.id;
+
+ // get free plan limits
+ const freePlanLimits = structuredClone(FREE_PLAN_LIMITS);
+
+ // If a team cancels their subscription, reset their limits to free
+ const team = await prisma.team.update({
+ where: {
+ stripeId,
+ subscriptionId,
+ },
+ data: {
+ plan: "free",
+ subscriptionId: null,
+ endsAt: null,
+ startsAt: null,
+ limits: freePlanLimits,
+ },
+ select: { id: true },
+ });
+
+ if (!team) {
+ await log({
+ message:
+ "Team with Stripe ID *`" +
+ stripeId +
+ "` and Subscription ID *`" +
+ subscriptionId +
+ "`* not found in Stripe webhook `customer.subscription.deleted` callback" +
+ `\n\n Event: https://dashboard.stripe.com/events/${event.id}`,
+ type: "error",
+ });
+ return res.status(200).json({ received: true });
+ }
+
+ await log({
+ message: ":cry: Team *`" + team.id + "`* deleted their subscription",
+ type: "info",
+ });
+}
diff --git a/lib/stripe/webhooks/customer-subscription-updated.ts b/lib/stripe/webhooks/customer-subscription-updated.ts
new file mode 100644
index 00000000..4ce4aa19
--- /dev/null
+++ b/lib/stripe/webhooks/customer-subscription-updated.ts
@@ -0,0 +1,78 @@
+import { NextApiResponse } from "next";
+
+import {
+ BUSINESS_PLAN_LIMITS,
+ DATAROOMS_PLAN_LIMITS,
+ PRO_PLAN_LIMITS,
+} from "@/ee/limits/constants";
+import Stripe from "stripe";
+
+import prisma from "@/lib/prisma";
+import { log } from "@/lib/utils";
+
+import { getPlanFromPriceId } from "../utils";
+
+export async function customerSubsciptionUpdated(
+ event: Stripe.Event,
+ res: NextApiResponse,
+) {
+ const subscriptionUpdated = event.data.object as Stripe.Subscription;
+ const priceId = subscriptionUpdated.items.data[0].price.id;
+
+ const plan = getPlanFromPriceId(priceId);
+
+ if (!plan) {
+ await log({
+ message: `Invalid price ID in customer.subscription.updated event: ${priceId}`,
+ type: "error",
+ });
+ return;
+ }
+
+ const stripeId = subscriptionUpdated.customer.toString();
+
+ const team = await prisma.team.findUnique({
+ where: { stripeId },
+ });
+
+ if (!team) {
+ await log({
+ message:
+ "Team with Stripe ID *`" +
+ stripeId +
+ "`* not found in Stripe webhook `customer.subscription.updated` callback",
+ type: "error",
+ });
+ return res.status(200).json({ received: true });
+ }
+
+ const newPlan = plan.slug;
+ const subscriptionId = subscriptionUpdated.id;
+ const startsAt = new Date(subscriptionUpdated.current_period_start * 1000);
+ const endsAt = new Date(subscriptionUpdated.current_period_end * 1000);
+
+ // If a team upgrades/downgrades their subscription, update their plan
+ if (team.plan !== newPlan) {
+ // Choose the correct plan limits
+ let planLimits = structuredClone(PRO_PLAN_LIMITS);
+ if (plan.slug === "pro") {
+ planLimits = structuredClone(PRO_PLAN_LIMITS);
+ } else if (plan.slug === "business") {
+ planLimits = structuredClone(BUSINESS_PLAN_LIMITS);
+ } else if (plan.slug === "datarooms") {
+ planLimits = structuredClone(DATAROOMS_PLAN_LIMITS);
+ }
+
+ // Update the user with the subscription information and stripeId
+ await prisma.team.update({
+ where: { stripeId },
+ data: {
+ plan: plan.slug,
+ subscriptionId,
+ startsAt,
+ endsAt,
+ limits: planLimits,
+ },
+ });
+ }
+}
diff --git a/package-lock.json b/package-lock.json
index 65ab9b30..14bb7925 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -40,7 +40,7 @@
"@radix-ui/react-tooltip": "^1.0.7",
"@react-email/components": "^0.0.19",
"@sindresorhus/slugify": "^2.2.1",
- "@stripe/stripe-js": "^3.5.0",
+ "@stripe/stripe-js": "^4.1.0",
"@tailwindcss/typography": "^0.5.13",
"@teamhanko/passkeys-next-auth-provider": "^0.2.7",
"@tremor/react": "^3.17.3",
@@ -103,7 +103,7 @@
"remark-toc": "^9.0.0",
"resend": "^3.2.0",
"sonner": "^1.5.0",
- "stripe": "^14.25.0",
+ "stripe": "^16.1.0",
"swr": "^2.2.5",
"tailwind-merge": "^2.3.0",
"tailwindcss": "^3.4.4",
@@ -4958,9 +4958,9 @@
"integrity": "sha512-+9jVqKhRSpsc591z5vX+X5Yyw+he/HCB4iQ/RYxw35CEPaY1gnsNE43nf9n9AaYjAQrTiI/mOwKUKdUs9vf7Xg=="
},
"node_modules/@stripe/stripe-js": {
- "version": "3.5.0",
- "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-3.5.0.tgz",
- "integrity": "sha512-pKS3wZnJoL1iTyGBXAvCwduNNeghJHY6QSRSNNvpYnrrQrLZ6Owsazjyynu0e0ObRgks0i7Rv+pe2M7/MBTZpQ==",
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-4.1.0.tgz",
+ "integrity": "sha512-HhstGRUz/4JdbZpb26OcOf8Qb/cFR02arvHvgz4sPFLSnI6ZNHC53Jc6JP/FGNwxtrF719YyUnK0gGy4oyhucQ==",
"engines": {
"node": ">=12.16"
}
@@ -15979,9 +15979,9 @@
}
},
"node_modules/stripe": {
- "version": "14.25.0",
- "resolved": "https://registry.npmjs.org/stripe/-/stripe-14.25.0.tgz",
- "integrity": "sha512-wQS3GNMofCXwH8TSje8E1SE8zr6ODiGtHQgPtO95p9Mb4FhKC9jvXR2NUTpZ9ZINlckJcFidCmaTFV4P6vsb9g==",
+ "version": "16.1.0",
+ "resolved": "https://registry.npmjs.org/stripe/-/stripe-16.1.0.tgz",
+ "integrity": "sha512-syeEEd112om/waJ5gOQ+SaYi+setuidQ4ZIPiQREF4yJeegXhn2HKy6C0JYm7uhVQKfMAvuZ22dIRsnoDv7AMw==",
"dependencies": {
"@types/node": ">=8.1.0",
"qs": "^6.11.0"
diff --git a/package.json b/package.json
index 8bd739b4..2a8c858a 100644
--- a/package.json
+++ b/package.json
@@ -49,7 +49,7 @@
"@radix-ui/react-tooltip": "^1.0.7",
"@react-email/components": "^0.0.19",
"@sindresorhus/slugify": "^2.2.1",
- "@stripe/stripe-js": "^3.5.0",
+ "@stripe/stripe-js": "^4.1.0",
"@tailwindcss/typography": "^0.5.13",
"@teamhanko/passkeys-next-auth-provider": "^0.2.7",
"@tremor/react": "^3.17.3",
@@ -112,7 +112,7 @@
"remark-toc": "^9.0.0",
"resend": "^3.2.0",
"sonner": "^1.5.0",
- "stripe": "^14.25.0",
+ "stripe": "^16.1.0",
"swr": "^2.2.5",
"tailwind-merge": "^2.3.0",
"tailwindcss": "^3.4.4",
diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.ts
index 766c0d63..a798c691 100644
--- a/pages/api/stripe/webhook.ts
+++ b/pages/api/stripe/webhook.ts
@@ -1,22 +1,12 @@
import { NextApiRequest, NextApiResponse } from "next";
-import {
- BUSINESS_PLAN_LIMITS,
- DATAROOMS_PLAN_LIMITS,
- FREE_PLAN_LIMITS,
- PRO_PLAN_LIMITS,
-} from "@/ee/limits/constants";
import { Readable } from "node:stream";
import type Stripe from "stripe";
-import { sendUpgradePlanEmail } from "@/lib/emails/send-upgrade-plan";
-import prisma from "@/lib/prisma";
import { stripe } from "@/lib/stripe";
-import {
- getPlanFromPriceId,
- isNewCustomer,
- isUpgradedCustomer,
-} from "@/lib/stripe/utils";
+import { checkoutSessionCompleted } from "@/lib/stripe/webhooks/checkout-session-completed";
+import { customerSubscriptionDeleted } from "@/lib/stripe/webhooks/customer-subscription-deleted";
+import { customerSubsciptionUpdated } from "@/lib/stripe/webhooks/customer-subscription-updated";
import { log } from "@/lib/utils";
// Stripe requires the raw body to construct the event.
@@ -40,20 +30,6 @@ 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,
@@ -71,213 +47,34 @@ export default async function webhookHandler(
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({
- message: "Missing items in Stripe webhook callback",
- type: "error",
- });
- return;
- }
-
- const clientReferenceId = checkoutSession.client_reference_id;
- const 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;
-
- let planLimits = structuredClone(PRO_PLAN_LIMITS);
- if (plan.slug === "pro") {
- planLimits = structuredClone(PRO_PLAN_LIMITS);
- } else if (plan.slug === "business") {
- planLimits = structuredClone(BUSINESS_PLAN_LIMITS);
- } else if (plan.slug === "datarooms") {
- planLimits = structuredClone(DATAROOMS_PLAN_LIMITS);
- }
-
- // 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,
- limits: planLimits,
- },
- 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,
- },
- planType:
- plan.slug.charAt(0).toUpperCase() + plan.slug.slice(1),
- });
- }
-
- // Remove the pending update from the store
- pendingSubscriptionUpdates.delete(stripeId);
- }
-
- // 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 upgradedCustomer = isUpgradedCustomer(
- 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,
- );
-
- pendingSubscriptionUpdates.set(stripeId, {
- plan,
- subscriptionId,
- startsAt,
- endsAt,
- newCustomer,
- });
-
- let planLimits = structuredClone(PRO_PLAN_LIMITS);
- if (plan) {
- if (plan.slug === "pro") {
- planLimits = structuredClone(PRO_PLAN_LIMITS);
- } else if (plan.slug === "business") {
- planLimits = structuredClone(BUSINESS_PLAN_LIMITS);
- } else if (plan.slug === "datarooms") {
- planLimits = structuredClone(DATAROOMS_PLAN_LIMITS);
- }
- }
-
- // if user upgrades from Pro to Business, checkout event won't be fired
- // so we need to update the user immediately
- if (upgradedCustomer && !newCustomer) {
- await prisma.team.update({
- where: {
- stripeId: stripeId,
- },
- data: {
- plan: plan.slug,
- subscriptionId,
- startsAt,
- endsAt,
- limits: planLimits,
- },
- select: {
- id: true,
- },
- });
-
- pendingSubscriptionUpdates.delete(stripeId);
- }
-
- // 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();
- const subscriptionId = subscriptionDeleted.id;
-
- // reset the plan limits to free
- const planlimits = structuredClone(FREE_PLAN_LIMITS);
-
- try {
- const team = await prisma.team.update({
- where: {
- stripeId,
- subscriptionId,
- },
- data: {
- plan: "free",
- subscriptionId: null,
- endsAt: null,
- startsAt: null,
- limits: planlimits,
- },
- select: { id: true },
- });
-
- if (!team) {
- throw new Error("Team not found in database");
- }
+ // Ignore unsupported events
+ if (!relevantEvents.has(event.type)) {
+ return res.status(400).send(`Unhandled event type: ${event.type}`);
+ }
- await log({
- message:
- ":cry: Team *`" + team.id + "`* deleted their subscription",
- type: "info",
- });
- } catch (error) {
- await log({
- message:
- "Team with stripeId: `" +
- stripeId +
- "` and subscriptionId `" +
- subscriptionId +
- "` not found in Stripe webhook `customer.subscription.deleted` callback" +
- `\n\n Error: ${(error as Error).message}` +
- `\n\n Event: https://dashboard.stripe.com/events/${event.id}`,
- type: "error",
- });
- return res
- .status(200)
- .send(
- `Acknowledged error in webhook: ${(error as Error).message}`,
- );
- }
- } else {
- throw new Error("Unhandled relevant event!");
- }
- } catch (error) {
- await log({
- message: `Stripe webook failed for Event: *${event.type}* ([_${
- event.id
- }_](https://dashboard.stripe.com/events/${event.id})) \n\n Error: ${(error as Error).message}`,
- type: "error",
- mention: true,
- });
- return res
- .status(400)
- .send(`Error in webhook: ${(error as Error).message}`);
+ try {
+ switch (event.type) {
+ case "checkout.session.completed":
+ await checkoutSessionCompleted(event);
+ break;
+ case "customer.subscription.updated":
+ await customerSubsciptionUpdated(event, res);
+ break;
+ case "customer.subscription.deleted":
+ await customerSubscriptionDeleted(event, res);
+ break;
}
- } else {
- return res.status(400).send(`🤷‍♀️ Unhandled event type: ${event.type}`);
+ } catch (error) {
+ await log({
+ message: `Stripe webhook failed. Error: ${error}`,
+ type: "error",
+ });
+ return res
+ .status(400)
+ .send("Webhook error: Webhook handler failed. View logs.");
}
- res.status(200).json({ received: true });
+ return res.status(200).json({ received: true });
} else {
res.setHeader("Allow", ["POST"]);
return res.status(405).end(`Method ${req.method} Not Allowed`);