From 5ad534f82424186c0e5d6a225018e676ec3ee019 Mon Sep 17 00:00:00 2001 From: Narciso Date: Wed, 18 Nov 2026 15:51:25 -0400 Subject: [PATCH 1/3] fix(billing): ignore Stripe events from replaced subscriptions --- .../settings/billing/show-billing.tsx | 42 +++++++-- apps/dokploy/pages/api/stripe/webhook.ts | 86 +++++++++---------- apps/dokploy/server/api/routers/stripe.ts | 20 +++++ apps/dokploy/server/utils/billing.ts | 14 +++ 4 files changed, 112 insertions(+), 50 deletions(-) diff --git a/apps/dokploy/components/dashboard/settings/billing/show-billing.tsx b/apps/dokploy/components/dashboard/settings/billing/show-billing.tsx index ee8e47e04..ab7a0c0ce 100644 --- a/apps/dokploy/components/dashboard/settings/billing/show-billing.tsx +++ b/apps/dokploy/components/dashboard/settings/billing/show-billing.tsx @@ -202,11 +202,13 @@ export const ShowBilling = () => { productId, serverQuantity, isAnnual, - }).then(async (session) => { - await stripe?.redirectToCheckout({ - sessionId: session.sessionId, - }); - }); + }) + .then(async (session) => { + await stripe?.redirectToCheckout({ + sessionId: session.sessionId, + }); + }) + .catch((error) => toast.error(error.message)); } }; @@ -228,7 +230,8 @@ export const ShowBilling = () => { const canSubscribe = !isEnterpriseCloud && (data?.subscriptions?.length ?? 0) === 0 && - !billingStatus?.isOnTrial; + !billingStatus?.isOnTrial && + !billingStatus?.hasPaymentIssue; const maxServers = admin?.user.serversQuantity ?? 1; const percentage = ((servers ?? 0) / maxServers) * 100; const safePercentage = Math.min(percentage, 100); @@ -429,6 +432,33 @@ export const ShowBilling = () => { )} )} + {!isEnterpriseCloud && + billingStatus?.hasPaymentIssue && + admin?.user.stripeCustomerId && ( +
+
+ +
+ + Payment failed + + + We couldn't charge your last invoice. Update your + payment method to reactivate your servers. + +
+
+ +
+ )} {canStartTrial && (
diff --git a/apps/dokploy/pages/api/stripe/webhook.ts b/apps/dokploy/pages/api/stripe/webhook.ts index 946a69234..67a934780 100644 --- a/apps/dokploy/pages/api/stripe/webhook.ts +++ b/apps/dokploy/pages/api/stripe/webhook.ts @@ -154,19 +154,6 @@ export default async function handler( case "customer.subscription.deleted": { const newSubscription = event.data.object as Stripe.Subscription; - await db - .update(user) - .set({ - stripeSubscriptionId: null, - serversQuantity: 0, - }) - .where( - and( - eq(user.stripeCustomerId, newSubscription.customer as string), - eq(user.isEnterpriseCloud, false), - ), - ); - const admin = await findUserByStripeCustomerId( newSubscription.customer as string, ); @@ -177,6 +164,18 @@ export default async function handler( break; } + if (isReplacedSubscription(admin, newSubscription.id)) { + break; + } + + await db + .update(user) + .set({ + stripeSubscriptionId: null, + serversQuantity: 0, + }) + .where(eq(user.id, admin.id)); + // Paying through checkout cancels the leftover trial subscription; // that is a conversion, not a lost trial. const otherActive = await stripe.subscriptions @@ -219,7 +218,10 @@ export default async function handler( return res.status(400).send("Webhook Error: Admin not found"); } - if (admin.isEnterpriseCloud) { + if ( + admin.isEnterpriseCloud || + isReplacedSubscription(admin, newSubscription.id) + ) { break; } @@ -250,13 +252,8 @@ export default async function handler( ); await db .update(user) - .set({ serversQuantity }) - .where( - and( - eq(user.stripeCustomerId, newSubscription.customer as string), - eq(user.isEnterpriseCloud, false), - ), - ); + .set({ serversQuantity, stripeSubscriptionId: newSubscription.id }) + .where(eq(user.id, admin.id)); await updateServersBasedOnQuantity(admin.id, serversQuantity); } else { @@ -264,12 +261,7 @@ export default async function handler( await db .update(user) .set({ serversQuantity: 0 }) - .where( - and( - eq(user.stripeCustomerId, newSubscription.customer as string), - eq(user.isEnterpriseCloud, false), - ), - ); + .where(eq(user.id, admin.id)); } break; @@ -299,22 +291,22 @@ export default async function handler( return res.status(400).send("Webhook Error: Admin not found"); } + if ( + admin.isEnterpriseCloud || + isReplacedSubscription(admin, subscription.id) + ) { + break; + } + const serversQuantity = getSubscriptionServersQuantity( subscription?.items?.data ?? [], ); + // Restores an id cleared by an old subscription's deletion. await db .update(user) - .set({ serversQuantity }) - .where( - and( - eq(user.stripeCustomerId, subscription.customer as string), - eq(user.isEnterpriseCloud, false), - ), - ); + .set({ serversQuantity, stripeSubscriptionId: subscription.id }) + .where(eq(user.id, admin.id)); - if (admin.isEnterpriseCloud) { - break; - } await updateServersBasedOnQuantity(admin.id, serversQuantity); if (admin.sendInvoiceNotifications) { @@ -341,7 +333,10 @@ export default async function handler( return res.status(400).send("Webhook Error: Admin not found"); } - if (admin.isEnterpriseCloud) { + if ( + admin.isEnterpriseCloud || + isReplacedSubscription(admin, subscription.id) + ) { break; } @@ -354,12 +349,7 @@ export default async function handler( .set({ serversQuantity: 0, }) - .where( - and( - eq(user.stripeCustomerId, newInvoice.customer as string), - eq(user.isEnterpriseCloud, false), - ), - ); + .where(eq(user.id, admin.id)); await disableServers(admin.id); } @@ -421,6 +411,14 @@ const findUserByStripeCustomerId = async (stripeCustomerId: string) => { return userResult; }; +// A customer can hold several subscriptions; only the one stored on the +// owner may change their plan and servers. +const isReplacedSubscription = ( + admin: { stripeSubscriptionId: string | null }, + subscriptionId: string, +) => + !!admin.stripeSubscriptionId && admin.stripeSubscriptionId !== subscriptionId; + const getInvoiceSubscriptionId = (invoice: Stripe.Invoice): string | null => { const subscription = invoice.subscription; if (typeof subscription === "string") return subscription; diff --git a/apps/dokploy/server/api/routers/stripe.ts b/apps/dokploy/server/api/routers/stripe.ts index 4dcdf9b15..81fdb8885 100644 --- a/apps/dokploy/server/api/routers/stripe.ts +++ b/apps/dokploy/server/api/routers/stripe.ts @@ -11,6 +11,7 @@ import { z } from "zod"; import { getBillingStatus, getCurrentPlan as getCurrentPlanForOrganization, + LIVE_SUBSCRIPTION_STATUSES, startTrial, TRIAL_DURATION_DAYS, TRIAL_SERVER_LIMITS, @@ -217,6 +218,25 @@ export const stripeRouter = createTRPCRouter({ } } + if (stripeCustomerId) { + const subscriptions = await stripe.subscriptions.list({ + customer: stripeCustomerId, + status: "all", + limit: 100, + }); + if ( + subscriptions.data.some((sub) => + LIVE_SUBSCRIPTION_STATUSES.includes(sub.status), + ) + ) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: + "You already have a subscription. Manage it from the billing portal.", + }); + } + } + const session = await stripe.checkout.sessions.create({ mode: "subscription", line_items: items, diff --git a/apps/dokploy/server/utils/billing.ts b/apps/dokploy/server/utils/billing.ts index 1fd34a4eb..ecdfc1426 100644 --- a/apps/dokploy/server/utils/billing.ts +++ b/apps/dokploy/server/utils/billing.ts @@ -78,6 +78,14 @@ export const getCurrentPlan = async ( return getCurrentPlanForUser(ownerId); }; +// Checkout reuses the owner's customer, so any of these would keep billing +// alongside the new subscription. +export const LIVE_SUBSCRIPTION_STATUSES: Stripe.Subscription.Status[] = [ + "active", + "trialing", + "past_due", +]; + export const TRIAL_DURATION_DAYS = 7; export type TrialTier = "hobby" | "startup"; export const TRIAL_SERVER_LIMITS: Record = { @@ -92,6 +100,7 @@ export interface BillingStatus { trialDaysRemaining: number | null; hasUsedTrial: boolean; hasActiveAccess: boolean; + hasPaymentIssue: boolean; hasPaymentMethod: boolean; isAnnual: boolean; isEnterpriseCloud: boolean; @@ -108,6 +117,7 @@ export const getBillingStatus = async ( trialDaysRemaining: null, hasUsedTrial: false, hasActiveAccess: true, + hasPaymentIssue: false, hasPaymentMethod: true, isAnnual: false, isEnterpriseCloud: false, @@ -123,6 +133,7 @@ export const getBillingStatus = async ( trialDaysRemaining: null, hasUsedTrial: false, hasActiveAccess: false, + hasPaymentIssue: false, hasPaymentMethod: false, isAnnual: false, isEnterpriseCloud: owner?.isEnterpriseCloud ?? false, @@ -174,6 +185,9 @@ export const getBillingStatus = async ( hasPaymentMethod, hasUsedTrial: subscriptions.data.length > 0, hasActiveAccess: plan !== null || !!trialingSub, + hasPaymentIssue: + plan === null && + subscriptions.data.some((sub) => sub.status === "past_due"), isAnnual, isEnterpriseCloud: owner.isEnterpriseCloud, }; From 1f215b76af0867ebb6dbee172fbf3a7c8bf08ee1 Mon Sep 17 00:00:00 2001 From: Narciso Date: Wed, 18 Nov 2026 16:03:54 -0400 Subject: [PATCH 2/3] fix(billing): skip ended subscriptions in created and checkout events --- apps/dokploy/pages/api/stripe/webhook.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/apps/dokploy/pages/api/stripe/webhook.ts b/apps/dokploy/pages/api/stripe/webhook.ts index 67a934780..22a4a087d 100644 --- a/apps/dokploy/pages/api/stripe/webhook.ts +++ b/apps/dokploy/pages/api/stripe/webhook.ts @@ -97,6 +97,9 @@ export default async function handler( const subscription = await stripe.subscriptions.retrieve( session.subscription as string, ); + if (hasEnded(subscription)) { + break; + } const serversQuantity = getSubscriptionServersQuantity( subscription?.items?.data ?? [], ); @@ -134,6 +137,13 @@ export default async function handler( case "customer.subscription.created": { const newSubscription = event.data.object as Stripe.Subscription; + const subscription = await stripe.subscriptions.retrieve( + newSubscription.id, + ); + if (hasEnded(subscription)) { + break; + } + await db .update(user) .set({ @@ -411,6 +421,12 @@ const findUserByStripeCustomerId = async (stripeCustomerId: string) => { return userResult; }; +// Late events of an ended subscription must not make it current again. +const hasEnded = (subscription: Stripe.Subscription) => + subscription.status === "canceled" || + subscription.status === "incomplete_expired" || + subscription.status === "unpaid"; + // A customer can hold several subscriptions; only the one stored on the // owner may change their plan and servers. const isReplacedSubscription = ( From 3ffdb445bbfd19e440bbedecec296e7297e8ff9f Mon Sep 17 00:00:00 2001 From: Narciso Date: Wed, 18 Nov 2026 16:18:48 -0400 Subject: [PATCH 3/3] fix(billing): only adopt live subscriptions from created events --- apps/dokploy/pages/api/stripe/webhook.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/dokploy/pages/api/stripe/webhook.ts b/apps/dokploy/pages/api/stripe/webhook.ts index 22a4a087d..c233ba38e 100644 --- a/apps/dokploy/pages/api/stripe/webhook.ts +++ b/apps/dokploy/pages/api/stripe/webhook.ts @@ -140,7 +140,11 @@ export default async function handler( const subscription = await stripe.subscriptions.retrieve( newSubscription.id, ); - if (hasEnded(subscription)) { + // A late event of an older subscription must not replace the current one. + if ( + subscription.status !== "active" && + subscription.status !== "trialing" + ) { break; }