Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

chore(billing): require credit card only on non-zero checkout sessions (#9467)

Michael Fröhlich7377a313e569
diff --git a/web/src/ee/features/billing/components/BillingActionButtons.tsx b/web/src/ee/features/billing/components/BillingActionButtons.tsx
index 0bb2d6e548..3281877a90 100644
--- a/web/src/ee/features/billing/components/BillingActionButtons.tsx
+++ b/web/src/ee/features/billing/components/BillingActionButtons.tsx
@@ -1,5 +1,5 @@
// Langfuse Cloud only
-
+import { useMemo } from "react";
import { Button } from "@/src/components/ui/button";
import Link from "next/link";
@@ -10,9 +10,21 @@ import { useBillingInformation } from "./useBillingInformation";
import { StripeCancellationButton } from "./StripeCancellationButton";
export const BillingActionButtons = () => {
- const { organization } = useBillingInformation();
+ const { organization, hasValidPaymentMethod, isLoading } =
+ useBillingInformation();
const { setOpen } = useSupportDrawer();
+ // Show pricing page button
+ const shouldDisableChangePlan = useMemo(() => {
+ if (!organization?.cloudConfig?.stripe?.activeSubscriptionId) {
+ return false; // always show for hobby plan users
+ }
+ return !hasValidPaymentMethod;
+ }, [
+ organization?.cloudConfig?.stripe?.activeSubscriptionId,
+ hasValidPaymentMethod,
+ ]);
+
// Do not show checkout or customer portal if manual plan is set in cloud config
if (organization?.cloudConfig?.plan) {
return (
@@ -29,30 +41,39 @@ export const BillingActionButtons = () => {
);
}
- // Show pricing page button
return (
- <div className="mt-4 flex flex-row items-center gap-2">
- {/* Always show – also for people who are currently on hobby plan */}
- <BillingSwitchPlanDialog />
+ <div className="mt-4 flex flex-col gap-2">
+ <div className="flex flex-row items-center gap-2">
+ {/* Always show – also for people who are currently on hobby plan */}
+ <BillingSwitchPlanDialog disabled={shouldDisableChangePlan} />
- {organization?.cloudConfig?.stripe?.activeSubscriptionId && (
- <>
- <StripeCustomerPortalButton
- orgId={organization.id}
- title="Update Billing Details"
- variant="secondary"
- />
- <StripeCancellationButton
- orgId={organization.id}
- variant="secondary"
- />
- </>
- )}
- <Button variant="secondary" asChild>
- <Link href={"https://langfuse.com/pricing"} target="_blank">
- Compare plans
- </Link>
- </Button>
+ {organization?.cloudConfig?.stripe?.activeSubscriptionId && (
+ <>
+ <StripeCustomerPortalButton
+ orgId={organization.id}
+ title="Update Billing Details"
+ variant="secondary"
+ />
+ <StripeCancellationButton
+ orgId={organization.id}
+ variant="secondary"
+ />
+ </>
+ )}
+ <Button variant="secondary" asChild>
+ <Link href={"https://langfuse.com/pricing"} target="_blank">
+ Compare plans
+ </Link>
+ </Button>
+ </div>
+ {organization?.cloudConfig?.stripe?.activeSubscriptionId &&
+ !hasValidPaymentMethod &&
+ !isLoading && (
+ <p className="text-sm text-red-600">
+ You do not have a valid payment method. Please Update Billing
+ Details.
+ </p>
+ )}
</div>
);
};
diff --git a/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx b/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx
index 507cebb86b..aa8e28aa2c 100644
--- a/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx
+++ b/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx
@@ -28,7 +28,11 @@ import { StripeCancellationButton } from "./StripeCancellationButton";
import { StripeSwitchPlanButton } from "./StripeSwitchPlanButton";
import { StripeKeepPlanButton } from "./StripeKeepPlanButton";
-export const BillingSwitchPlanDialog = () => {
+export const BillingSwitchPlanDialog = ({
+ disabled = false,
+}: {
+ disabled?: boolean;
+}) => {
const [processingPlanId, setProcessingPlanId] = useState<string | null>(null);
const [_opId, setOpId] = useState<string | null>(null);
@@ -38,6 +42,7 @@ export const BillingSwitchPlanDialog = () => {
cancellation,
scheduledPlanSwitch,
isLegacySubscription,
+ hasValidPaymentMethod,
} = useBillingInformation();
const capture = usePostHogClientCapture();
@@ -64,7 +69,7 @@ export const BillingSwitchPlanDialog = () => {
}}
>
<DialogTrigger asChild>
- <Button>Change plan</Button>
+ <Button disabled={disabled}>Change plan</Button>
</DialogTrigger>
<DialogContent className="max-w-5xl">
<DialogHeader className="flex flex-row items-center justify-between">
@@ -174,7 +179,9 @@ export const BillingSwitchPlanDialog = () => {
{!cancellation?.isCancelled &&
!scheduledPlanSwitch && (
<Button className="w-full" disabled>
- Current plan
+ {!hasValidPaymentMethod
+ ? "Payment method required"
+ : "Current plan"}
</Button>
)}
</>
@@ -193,7 +200,8 @@ export const BillingSwitchPlanDialog = () => {
{!isCurrentPlan &&
scheduledPlanSwitch &&
scheduledPlanSwitch.newPlanId !==
- product.stripeProductId && (
+ product.stripeProductId &&
+ (hasValidPaymentMethod ? (
<StripeSwitchPlanButton
orgId={organization?.id}
currentPlan={organization?.plan}
@@ -206,23 +214,33 @@ export const BillingSwitchPlanDialog = () => {
processingPlanId === product.stripeProductId
}
/>
- )}
+ ) : (
+ <Button className="w-full" disabled>
+ Payment method required
+ </Button>
+ ))}
{/* The default behavior when it is not the current plan and no schedule exists*/}
- {!isCurrentPlan && !scheduledPlanSwitch && (
- <StripeSwitchPlanButton
- orgId={organization?.id}
- currentPlan={organization?.plan}
- newPlanTitle={product.checkout?.title}
- isLegacySubscription={isLegacySubscription}
- isUpgrade={isThisUpgrade}
- stripeProductId={product.stripeProductId}
- onProcessing={setProcessingPlanId}
- processing={
- processingPlanId === product.stripeProductId
- }
- />
- )}
+ {!isCurrentPlan &&
+ !scheduledPlanSwitch &&
+ (hasValidPaymentMethod ? (
+ <StripeSwitchPlanButton
+ orgId={organization?.id}
+ currentPlan={organization?.plan}
+ newPlanTitle={product.checkout?.title}
+ isLegacySubscription={isLegacySubscription}
+ isUpgrade={isThisUpgrade}
+ stripeProductId={product.stripeProductId}
+ onProcessing={setProcessingPlanId}
+ processing={
+ processingPlanId === product.stripeProductId
+ }
+ />
+ ) : (
+ <Button className="w-full" disabled>
+ Payment method required
+ </Button>
+ ))}
</div>
) : (
// The default behavior when the user is not on a paid plan.
diff --git a/web/src/ee/features/billing/components/useBillingInformation.tsx b/web/src/ee/features/billing/components/useBillingInformation.tsx
index 7d285bc2c7..411523658f 100644
--- a/web/src/ee/features/billing/components/useBillingInformation.tsx
+++ b/web/src/ee/features/billing/components/useBillingInformation.tsx
@@ -23,17 +23,19 @@ export type BillingScheduledSwitchInfo = {
};
export type UseBillingInformationResult = {
+ isLoading: boolean;
organization: ReturnType<typeof useQueryOrganization>;
planLabel: string;
cancellation: BillingCancellationInfo | null;
scheduledPlanSwitch: BillingScheduledSwitchInfo | null;
isLegacySubscription: boolean;
hasActiveSubscription: boolean;
+ hasValidPaymentMethod: boolean;
};
export const useBillingInformation = (): UseBillingInformationResult => {
const organization = useQueryOrganization();
- const { data: subscriptionInfo } =
+ const { data: subscriptionInfo, isLoading: isLoadingSubscriptionInfo } =
api.cloudBilling.getSubscriptionInfo.useQuery(
{ orgId: organization?.id ?? "" },
{ enabled: Boolean(organization?.id) },
@@ -92,6 +94,7 @@ export const useBillingInformation = (): UseBillingInformationResult => {
}, [subscriptionInfo]);
return {
+ isLoading: isLoadingSubscriptionInfo,
organization,
planLabel,
cancellation,
@@ -102,5 +105,6 @@ export const useBillingInformation = (): UseBillingInformationResult => {
hasActiveSubscription: Boolean(
organization?.cloudConfig?.stripe?.activeSubscriptionId,
),
+ hasValidPaymentMethod: subscriptionInfo?.hasValidPaymentMethod ?? false,
};
};
diff --git a/web/src/ee/features/billing/server/stripeBillingService.ts b/web/src/ee/features/billing/server/stripeBillingService.ts
index fc83203ef6..63a9d7c238 100644
--- a/web/src/ee/features/billing/server/stripeBillingService.ts
+++ b/web/src/ee/features/billing/server/stripeBillingService.ts
@@ -60,6 +60,7 @@ export type BillingSubscriptionInfo = {
duration: "forever" | "once" | "repeating" | null;
durationInMonths: number | null;
}>;
+ hasValidPaymentMethod: boolean;
};
class BillingService {
@@ -265,7 +266,12 @@ class BillingService {
if (!subscriptionId) {
// No active subscription → nothing scheduled
- return { cancellation: null, scheduledChange: null, billingPeriod: null };
+ return {
+ cancellation: null,
+ scheduledChange: null,
+ billingPeriod: null,
+ hasValidPaymentMethod: false,
+ };
}
const subscription =
@@ -424,7 +430,46 @@ class BillingService {
})
.filter((d) => d !== null);
- return { cancellation, scheduledChange, billingPeriod, discounts };
+ // Check if customer has a valid payment method
+ let hasValidPaymentMethod = false;
+ try {
+ const customerId =
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer.id;
+
+ const paymentMethods = await client.customers.listPaymentMethods(
+ customerId,
+ { limit: 1 },
+ );
+
+ hasValidPaymentMethod = paymentMethods.data.length > 0;
+ } catch (error) {
+ logger.error(
+ "StripeBillingService.getSubscriptionInfo:failed to check payment method",
+ {
+ userId: this.ctx.session.user?.id,
+ userEmail: this.ctx.session.user?.email,
+ customerId:
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer.id,
+ subscriptionId: parsedOrg.cloudConfig?.stripe?.activeSubscriptionId,
+ orgId: parsedOrg.id,
+ error,
+ },
+ );
+ // Default to false if there's an error checking
+ hasValidPaymentMethod = false;
+ }
+
+ return {
+ cancellation,
+ scheduledChange,
+ billingPeriod,
+ discounts,
+ hasValidPaymentMethod,
+ };
}
/**
@@ -540,6 +585,7 @@ class BillingService {
},
}
: {}),
+ payment_method_collection: "if_required",
billing_address_collection: "required",
success_url: returnUrl,
cancel_url: returnUrl,
@@ -1646,14 +1692,43 @@ class BillingService {
userEmail: this.ctx.session.user?.email,
});
- await client.subscriptions.update(
- subscriptionId,
- {
- discounts: [...existingDiscounts, { promotion_code: promo.id }],
- proration_behavior: "none",
- },
- { idempotencyKey },
- );
+ try {
+ await client.subscriptions.update(
+ subscriptionId,
+ {
+ discounts: [...existingDiscounts, { promotion_code: promo.id }],
+ proration_behavior: "none",
+ },
+ { idempotencyKey },
+ );
+ } catch (error: any) {
+ logger.error(
+ "StripeBillingService.applyPromotionCode:stripe.subscription.update.failed",
+ {
+ userId: this.ctx.session.user?.id,
+ userEmail: this.ctx.session.user?.email,
+ customerId: subscription.customer,
+ subscriptionId,
+ orgId: parsedOrg.id,
+ promotionCodeId: promo.id,
+ error,
+ },
+ );
+
+ // Provide user-friendly error message
+ let errorMessage = "Failed to apply promotion code";
+
+ if (error?.message?.includes("prior transactions")) {
+ errorMessage = "Promotion code only valid for new customers";
+ } else if (error?.message) {
+ errorMessage = error.message;
+ }
+
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: errorMessage,
+ });
+ }
void auditLog({
session: this.ctx.session,