The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Made Stripe webhook bulletproof
Steven Tey9afa47d601fb
diff --git a/app/ui/home/pricing.tsx b/app/ui/home/pricing.tsxindex 04d1e9c852..2445c9f72f 100644--- a/app/ui/home/pricing.tsx+++ b/app/ui/home/pricing.tsx@@ -11,7 +11,7 @@ import {import MaxWidthWrapper from "@/components/shared/max-width-wrapper";import Switch from "#/ui/switch";import Tooltip from "#/ui/tooltip";-import { PLANS } from "#/lib/stripe/constants";+import { PLANS } from "#/lib/stripe/utils";import { nFormatter } from "#/lib/utils";import { MinusCircle } from "lucide-react";diff --git a/components/app/modals/upgrade-plan-modal/pricing.tsx b/components/app/modals/upgrade-plan-modal/pricing.tsxindex affcd8265f..6b062bc8d3 100644--- a/components/app/modals/upgrade-plan-modal/pricing.tsx+++ b/components/app/modals/upgrade-plan-modal/pricing.tsx@@ -13,7 +13,7 @@ import MaxWidthWrapper from "@/components/shared/max-width-wrapper";import Switch from "#/ui/switch";import Tooltip from "#/ui/tooltip";import { getStripe } from "#/lib/stripe/client";-import { PLANS } from "#/lib/stripe/constants";+import { PLANS } from "#/lib/stripe/utils";import { capitalize, nFormatter } from "#/lib/utils";import useProject from "#/lib/swr/use-project";import { MinusCircle } from "lucide-react";diff --git a/lib/stripe/constants.ts b/lib/stripe/constants.tsdeleted file mode 100644index d519b67a78..0000000000--- a/lib/stripe/constants.ts+++ /dev/null@@ -1,44 +0,0 @@-export const PLANS = [- {- name: "Pro",- slug: "pro",- quota: 50000,- price: {- monthly: {- amount: 9,- priceIds: {- test: "price_1LoytoAlJJEpqkPV2oPcQ63m",- production: "price_1LodNLAlJJEpqkPVQSrt33Lc",- },- },- yearly: {- amount: 90,- priceIds: {- test: "price_1LoytoAlJJEpqkPVsWjM4tB9",- production: "price_1LodNLAlJJEpqkPVRxUyCQgZ",- },- },- },- },- {- name: "Enterprise",- slug: "enterprise",- quota: 500000,- price: {- monthly: {- amount: 49,- priceIds: {- test: "price_1LoyrCAlJJEpqkPVZ32BV3wm",- production: "price_1LodLoAlJJEpqkPV9rD0rlNL",- },- },- yearly: {- amount: 490,- priceIds: {- test: "price_1LoyrCAlJJEpqkPVgIlNG23q",- production: "price_1LodLoAlJJEpqkPVJdwv5zrG",- },- },- },- },-];diff --git a/lib/stripe/utils.ts b/lib/stripe/utils.tsnew file mode 100644index 0000000000..41df3c9d75--- /dev/null+++ b/lib/stripe/utils.ts@@ -0,0 +1,91 @@+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:+ | {+ default_payment_method?: string;+ items?: {+ data?: {+ price?: {+ id?: string;+ }[];+ };+ };+ }+ | undefined,+) {+ let isNewCustomer = false;+ try {+ if (+ // if the project is upgrading from free to pro+ previousAttributes?.default_payment_method === null+ ) {+ isNewCustomer = true;+ } else {+ // if the project is upgrading from pro to enterprise+ const oldPriceId =+ previousAttributes?.items?.data &&+ previousAttributes?.items?.data[0].price.id;+ if (oldPriceId && getPlanFromPriceId(oldPriceId).slug === "pro") {+ isNewCustomer = true;+ }+ }+ } catch (error) {+ console.error("An error occurred:", error);+ }+ return isNewCustomer;+}++export const PLANS = [+ {+ name: "Pro",+ slug: "pro",+ quota: 50000,+ price: {+ monthly: {+ amount: 9,+ priceIds: {+ test: "price_1LoytoAlJJEpqkPV2oPcQ63m",+ production: "price_1LodNLAlJJEpqkPVQSrt33Lc",+ },+ },+ yearly: {+ amount: 90,+ priceIds: {+ test: "price_1LoytoAlJJEpqkPVsWjM4tB9",+ production: "price_1LodNLAlJJEpqkPVRxUyCQgZ",+ },+ },+ },+ },+ {+ name: "Enterprise",+ slug: "enterprise",+ quota: 500000,+ price: {+ monthly: {+ amount: 49,+ priceIds: {+ test: "price_1LoyrCAlJJEpqkPVZ32BV3wm",+ production: "price_1LodLoAlJJEpqkPV9rD0rlNL",+ },+ },+ yearly: {+ amount: 490,+ priceIds: {+ test: "price_1LoyrCAlJJEpqkPVgIlNG23q",+ production: "price_1LodLoAlJJEpqkPVJdwv5zrG",+ },+ },+ },+ },+];diff --git a/package.json b/package.jsonindex ad9e89bdce..014425905a 100644--- a/package.json+++ b/package.json@@ -78,7 +78,7 @@"resend": "^0.16.0","shiki": "^0.14.1","sonner": "^0.5.0",- "stripe": "^12.7.0",+ "stripe": "^12.12.0","swr": "^2.1.5","tailwind-merge": "^1.13.2","tailwind-scrollbar-hide": "^1.1.7",diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.tsindex 29cdb9cd85..2707213523 100644--- a/pages/api/stripe/webhook.ts+++ b/pages/api/stripe/webhook.ts@@ -3,7 +3,7 @@ import { Readable } from "node:stream";import Stripe from "stripe";import prisma from "#/lib/prisma";import { stripe } from "#/lib/stripe";-import { PLANS } from "#/lib/stripe/constants";+import { getPlanFromPriceId, isNewCustomer } from "#/lib/stripe/utils";import { redis } from "#/lib/upstash";import { log } from "#/lib/utils";import { sendEmail } from "emails";@@ -77,18 +77,14 @@ export default async function webhookHandler(billingCycleStart: new Date().getDate(),},});++ // for subscription updates} else if (event.type === "customer.subscription.updated") {const subscriptionUpdated = event.data.object as Stripe.Subscription;- const newPriceId = subscriptionUpdated.items.data[0].price.id;- const env =- process.env.NEXT_PUBLIC_VERCEL_ENV === "production"- ? "production"- : "test";- const plan = PLANS.find(- (plan) =>- plan.price.monthly.priceIds[env] === newPriceId ||- plan.price.yearly.priceIds[env] === newPriceId,- )!;+ const priceId = subscriptionUpdated.items.data[0].price.id;+ const newCustomer = isNewCustomer(event.data.previous_attributes);++ const plan = getPlanFromPriceId(priceId);const usageLimit = plan.quota;const stripeId = subscriptionUpdated.customer.toString();@@ -117,20 +113,31 @@ export default async function webhookHandler(},},});+ if (!data) {+ await log({+ message:+ "Project not found in Stripe webhook `customer.subscription.created` callback",+ type: "cron",+ mention: true,+ });+ return;+ }- const owner = data.users[0].user;+ // Send thank you email to project owner if they are a new customer+ if (newCustomer) {+ const owner = data.users[0].user;- // send thank you email to project owner- await sendEmail({- email: owner.email as string,- subject: `Thank you for upgrading to Dub ${plan.name}!`,- react: UpgradeEmail({- name: owner.name,+ await sendEmail({email: owner.email as string,- plan: plan.name,- }),- marketing: true,- });+ subject: `Thank you for upgrading to Dub ${plan.name}!`,+ react: UpgradeEmail({+ name: owner.name,+ email: owner.email as string,+ plan: plan.name,+ }),+ marketing: true,+ });+ }// If project cancels their subscription} else if (event.type === "customer.subscription.deleted") {@@ -193,7 +200,7 @@ export default async function webhookHandler(}} catch (error) {await log({- message: `Stripe wekbook failed. Error: ${error.message}`,+ message: `Stripe webook failed. Error: ${error.message}`,type: "cron",mention: true,});diff --git a/yarn.lock b/yarn.lockindex 69491e3d89..e67f95e5f9 100644--- a/yarn.lock+++ b/yarn.lock@@ -8228,10 +8228,10 @@ strip-final-newline@^2.0.0:resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad"integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==-stripe@^12.7.0:- version "12.7.0"- resolved "https://registry.npmjs.org/stripe/-/stripe-12.7.0.tgz"- integrity sha512-4yY9gNFznBI6fZtR0B4y2a+o2EJe+s7p4DiHECKphwa36zYIczpWzO1g4dF0PF3lhTRw5FWTaHGBjwaD5FEiDQ==+stripe@^12.12.0:+ version "12.12.0"+ resolved "https://registry.yarnpkg.com/stripe/-/stripe-12.12.0.tgz#29d38a893133e36810cff668002103426258ae2f"+ integrity sha512-aM9xfyDryiaf/qSWMtJaTMrlc/he3qyx3aVHMqOZqUiMdgTV6lt7tLpFrU0pG+QURm1LAP9GYZ+EcA17446YoQ==dependencies:"@types/node" ">=8.1.0"qs "^6.11.0"