Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Enhance Stripe webhook handling for subscription updates and deletions. Introduced updateWorkspacePlan utility to streamline plan updates and added logic to check for active subscriptions upon deletion. Cleaned up unused code in customerSubscriptionUpdated.

Kiran K7d1d3b53ee65
diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts
index 5d52fd4baf..76cc9246b9 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-deleted.ts
@@ -1,14 +1,15 @@
import { deleteWorkspaceFolders } from "@/lib/api/folders/delete-workspace-folders";
import { tokenCache } from "@/lib/auth/token-cache";
import { isBlacklistedEmail } from "@/lib/edge-config/is-blacklisted-email";
+import { stripe } from "@/lib/stripe";
import { recordLink } from "@/lib/tinybird";
import { redis } from "@/lib/upstash";
import { webhookCache } from "@/lib/webhook/cache";
import { prisma } from "@dub/prisma";
-import { FREE_PLAN, log } from "@dub/utils";
+import { FREE_PLAN, getPlanFromPriceId, log } from "@dub/utils";
import { NextResponse } from "next/server";
import Stripe from "stripe";
-import { sendCancellationFeedback } from "./utils";
+import { sendCancellationFeedback, updateWorkspacePlan } from "./utils";
export async function customerSubscriptionDeleted(event: Stripe.Event) {
const subscriptionDeleted = event.data.object as Stripe.Subscription;
@@ -24,8 +25,10 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {
select: {
id: true,
slug: true,
- domains: true,
+ plan: true,
foldersUsage: true,
+ paymentFailedAt: true,
+ payoutsLimit: true,
links: {
where: {
key: "_root",
@@ -71,6 +74,26 @@ export async function customerSubscriptionDeleted(event: Stripe.Event) {
return NextResponse.json({ received: true });
}
+ // Check if the customer has another active subscription
+ const { data: activeSubscriptions } = await stripe.subscriptions.list({
+ customer: stripeId,
+ status: "active",
+ });
+
+ if (activeSubscriptions.length > 0) {
+ const activeSubscription = activeSubscriptions[0];
+ const priceId = activeSubscription.items.data[0].price.id;
+ const plan = getPlanFromPriceId(priceId);
+
+ await updateWorkspacePlan({
+ workspace,
+ plan,
+ priceId,
+ });
+
+ return NextResponse.json({ received: true });
+ }
+
const workspaceLinks = workspace.links;
const workspaceUsers = workspace.users.map(({ user }) => user);
diff --git a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts
index b7d783b110..434464680b 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/customer-subscription-updated.ts
@@ -1,11 +1,8 @@
-import { deleteWorkspaceFolders } from "@/lib/api/folders/delete-workspace-folders";
-import { tokenCache } from "@/lib/auth/token-cache";
-import { webhookCache } from "@/lib/webhook/cache";
import { prisma } from "@dub/prisma";
-import { getPlanFromPriceId, LEGACY_PRICE_IDS } from "@dub/utils";
+import { getPlanFromPriceId } from "@dub/utils";
import { NextResponse } from "next/server";
import Stripe from "stripe";
-import { sendCancellationFeedback } from "./utils";
+import { sendCancellationFeedback, updateWorkspacePlan } from "./utils";
export async function customerSubscriptionUpdated(event: Stripe.Event) {
const subscriptionUpdated = event.data.object as Stripe.Subscription;
@@ -65,113 +62,11 @@ export async function customerSubscriptionUpdated(event: Stripe.Event) {
return NextResponse.json({ received: true });
}
- const newPlanName = plan.name.toLowerCase();
- const shouldDisableWebhooks = newPlanName === "free" || newPlanName === "pro";
- const shouldDeleteFolders =
- newPlanName === "free" && workspace.foldersUsage > 0;
-
- // If a workspace upgrades/downgrades their subscription
- // or if the payouts limit changes and the new plan is not a legacy plan
- // update their usage limit in the database
- if (
- workspace.plan !== newPlanName ||
- (workspace.payoutsLimit !== plan.limits.payouts &&
- !LEGACY_PRICE_IDS.includes(priceId))
- ) {
- await Promise.allSettled([
- prisma.project.update({
- where: {
- stripeId,
- },
- data: {
- plan: newPlanName,
- usageLimit: plan.limits.clicks!,
- linksLimit: plan.limits.links!,
- payoutsLimit: plan.limits.payouts!,
- domainsLimit: plan.limits.domains!,
- aiLimit: plan.limits.ai!,
- tagsLimit: plan.limits.tags!,
- foldersLimit: plan.limits.folders!,
- groupsLimit: plan.limits.groups!,
- usersLimit: plan.limits.users!,
- paymentFailedAt: null,
- ...(shouldDeleteFolders && { foldersUsage: 0 }),
- },
- }),
-
- prisma.restrictedToken.updateMany({
- where: {
- projectId: workspace.id,
- },
- data: {
- rateLimit: plan.limits.api,
- },
- }),
-
- // expire tokens cache
- tokenCache.expireMany({
- hashedKeys: workspace.restrictedTokens.map(
- ({ hashedKey }) => hashedKey,
- ),
- }),
- ]);
-
- // Disable the webhooks if the new plan does not support webhooks
- if (shouldDisableWebhooks) {
- await Promise.all([
- prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- webhookEnabled: false,
- },
- }),
-
- prisma.webhook.updateMany({
- where: {
- projectId: workspace.id,
- },
- data: {
- disabledAt: new Date(),
- },
- }),
- ]);
-
- // Update the webhooks cache
- const webhooks = await prisma.webhook.findMany({
- where: {
- projectId: workspace.id,
- },
- select: {
- id: true,
- url: true,
- secret: true,
- triggers: true,
- disabledAt: true,
- },
- });
-
- await webhookCache.mset(webhooks);
- }
-
- // Delete the folders if the new plan is free
- // For downgrade from Business → Pro, it should be fine since we're accounting that to make sure all folders get write access.
- if (shouldDeleteFolders) {
- await deleteWorkspaceFolders({
- workspaceId: workspace.id,
- });
- }
- } else if (workspace.paymentFailedAt) {
- await prisma.project.update({
- where: {
- id: workspace.id,
- },
- data: {
- paymentFailedAt: null,
- },
- });
- }
+ await updateWorkspacePlan({
+ workspace,
+ plan,
+ priceId,
+ });
const subscriptionCanceled =
subscriptionUpdated.status === "active" &&
diff --git a/apps/web/app/(ee)/api/stripe/webhook/utils.ts b/apps/web/app/(ee)/api/stripe/webhook/utils.ts
index 495d6565ee..4fd8cff04a 100644
--- a/apps/web/app/(ee)/api/stripe/webhook/utils.ts
+++ b/apps/web/app/(ee)/api/stripe/webhook/utils.ts
@@ -1,4 +1,10 @@
+import { deleteWorkspaceFolders } from "@/lib/api/folders/delete-workspace-folders";
+import { tokenCache } from "@/lib/auth/token-cache";
+import { WorkspaceProps } from "@/lib/types";
+import { webhookCache } from "@/lib/webhook/cache";
import { sendEmail } from "@dub/email";
+import { prisma } from "@dub/prisma";
+import { getPlanFromPriceId, LEGACY_PRICE_IDS } from "@dub/utils";
import Stripe from "stripe";
const cancellationReasonMap = {
@@ -37,3 +43,132 @@ export async function sendCancellationFeedback({
),
);
}
+
+export async function updateWorkspacePlan({
+ workspace,
+ plan,
+ priceId,
+}: {
+ workspace: Pick<
+ WorkspaceProps,
+ "id" | "paymentFailedAt" | "payoutsLimit" | "foldersUsage"
+ > & {
+ plan: string;
+ restrictedTokens: {
+ hashedKey: string;
+ }[];
+ };
+ plan: ReturnType<typeof getPlanFromPriceId>;
+ priceId: string;
+}) {
+ if (!plan) {
+ return;
+ }
+
+ const newPlanName = plan.name.toLowerCase();
+ const shouldDisableWebhooks = newPlanName === "free" || newPlanName === "pro";
+ const shouldDeleteFolders = newPlanName === "free" && plan.limits.folders > 0;
+
+ // If a workspace upgrades/downgrades their subscription
+ // or if the payouts limit changes and the new plan is not a legacy plan
+ // update their usage limit in the database
+ if (
+ workspace.plan !== newPlanName ||
+ (workspace.payoutsLimit !== plan.limits.payouts &&
+ !LEGACY_PRICE_IDS.includes(priceId))
+ ) {
+ await Promise.allSettled([
+ prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ plan: newPlanName,
+ usageLimit: plan.limits.clicks!,
+ linksLimit: plan.limits.links!,
+ payoutsLimit: plan.limits.payouts!,
+ domainsLimit: plan.limits.domains!,
+ aiLimit: plan.limits.ai!,
+ tagsLimit: plan.limits.tags!,
+ foldersLimit: plan.limits.folders!,
+ groupsLimit: plan.limits.groups!,
+ usersLimit: plan.limits.users!,
+ paymentFailedAt: null,
+ ...(shouldDeleteFolders && { foldersUsage: 0 }),
+ },
+ }),
+
+ prisma.restrictedToken.updateMany({
+ where: {
+ projectId: workspace.id,
+ },
+ data: {
+ rateLimit: plan.limits.api,
+ },
+ }),
+
+ // expire tokens cache
+ tokenCache.expireMany({
+ hashedKeys: workspace.restrictedTokens.map(
+ ({ hashedKey }) => hashedKey,
+ ),
+ }),
+ ]);
+
+ // Disable the webhooks if the new plan does not support webhooks
+ if (shouldDisableWebhooks) {
+ await Promise.all([
+ prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ webhookEnabled: false,
+ },
+ }),
+
+ prisma.webhook.updateMany({
+ where: {
+ projectId: workspace.id,
+ },
+ data: {
+ disabledAt: new Date(),
+ },
+ }),
+ ]);
+
+ // Update the webhooks cache
+ const webhooks = await prisma.webhook.findMany({
+ where: {
+ projectId: workspace.id,
+ },
+ select: {
+ id: true,
+ url: true,
+ secret: true,
+ triggers: true,
+ disabledAt: true,
+ },
+ });
+
+ await webhookCache.mset(webhooks);
+ }
+
+ // Delete the folders if the new plan is free
+ // For downgrade from Business → Pro, it should be fine since we're accounting that to make sure all folders get write access.
+ if (shouldDeleteFolders) {
+ await deleteWorkspaceFolders({
+ workspaceId: workspace.id,
+ });
+ }
+ } else if (workspace.paymentFailedAt) {
+ await prisma.project.update({
+ where: {
+ id: workspace.id,
+ },
+ data: {
+ paymentFailedAt: null,
+ },
+ });
+ }
+}