Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: support for 3ds card payment

=991ad44de940
diff --git a/backend/src/ee/routes/v1/license-v2-router.ts b/backend/src/ee/routes/v1/license-v2-router.ts
index 99f36b2cca..0e00560ed7 100644
--- a/backend/src/ee/routes/v1/license-v2-router.ts
+++ b/backend/src/ee/routes/v1/license-v2-router.ts
@@ -127,6 +127,7 @@ const BillingV2EntitlementSchema = z.object({
trialPlanName: z.string().optional(),
trialPlanEndsAt: z.string().nullable().optional(),
trialPlanDaysLeft: z.number().nullable().optional(),
+ trialPaymentDueAt: z.string().nullable().optional(),
renewsOn: z.string().nullable().optional(),
deprecation: BillingV2DeprecationSchema.extend({
kind: z.enum(["product", "plan"])
@@ -141,6 +142,7 @@ const BillingV2TrialSchema = z.object({
planTier: z.string().nullable(),
basePlanTier: z.string().nullable(),
outcome: z.string(),
+ endedReason: z.string().nullable(),
endedDetail: z.string().nullable(),
endedAt: z.string().nullable(),
endedDaysAgo: z.number().nullable()
@@ -189,6 +191,8 @@ const BillingV2OverviewSchema = z.object({
trialedProductKeys: z.string().array(),
trials: BillingV2TrialSchema.array(),
onDemandAmount: z.number(),
+ trialPaymentDue: z.object({ dueAt: z.string(), productKeys: z.string().array() }).nullable(),
+ paymentAlert: z.object({ state: z.enum(["needs_action", "failed"]), actionUrl: z.string() }).nullable(),
checkoutFrozen: z.boolean(),
selfServe: z.boolean()
});
@@ -530,8 +534,9 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- outcome: z.enum(["checkout_created", "subscription_updated"]),
+ outcome: z.enum(["checkout_created", "subscription_updated", "payment_action_required"]),
checkoutUrl: z.string().optional(),
+ paymentUrl: z.string().optional(),
subscriptionId: z.string().optional()
})
}
@@ -552,6 +557,10 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
returnPath: req.body.returnPath
});
+ if (result.outcome === "payment_action_required") {
+ return { outcome: result.outcome, paymentUrl: result.paymentUrl };
+ }
+
void server.services.telemetry
.sendPostHogEvents({
event:
@@ -591,7 +600,8 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- outcome: z.literal("upgraded"),
+ outcome: z.enum(["upgraded", "payment_action_required"]),
+ paymentUrl: z.string().optional(),
subscriptionId: z.string().optional(),
fromPlanKey: z.string().optional(),
toPlanKey: z.string().optional()
@@ -609,6 +619,11 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
prorationDate: req.body.prorationDate
});
+ // Nothing is upgraded until the bank approves the charge.
+ if (result.outcome === "payment_action_required") {
+ return result;
+ }
+
void server.services.telemetry
.sendPostHogEvents({
event: PostHogEventTypes.BillingPlanUpgraded,
@@ -665,8 +680,9 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- outcome: z.enum(["checkout_created", "subscription_updated"]),
+ outcome: z.enum(["checkout_created", "subscription_updated", "payment_action_required"]),
checkoutUrl: z.string().optional(),
+ paymentUrl: z.string().optional(),
subscriptionId: z.string().optional()
})
}
@@ -762,6 +778,35 @@ export const registerLicenseV2Router = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/:organizationId/billing/v2/trial/confirm-payment",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "confirmBillingTrialPayment",
+ description:
+ "Open a Stripe Checkout where the customer approves a trial conversion charge their bank is holding (for example 3D Secure). The trial converts once the checkout completes.",
+ params: z.object({ organizationId: z.string().trim().uuid() }),
+ body: z.object({ returnPath: ReturnPathSchema }),
+ response: {
+ 200: z.object({
+ outcome: z.literal("checkout_created"),
+ checkoutUrl: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ return server.services.licenseV2.confirmTrialPayment({
+ orgId: req.params.organizationId,
+ actor: buildActor(req.permission),
+ returnPath: req.body.returnPath
+ });
+ }
+ });
+
server.route({
method: "POST",
url: "/:organizationId/billing/v2/subscription/cancel",
diff --git a/backend/src/ee/services/license-v2/license-v2-service.ts b/backend/src/ee/services/license-v2/license-v2-service.ts
index 484066d2a7..3fd175dd30 100644
--- a/backend/src/ee/services/license-v2/license-v2-service.ts
+++ b/backend/src/ee/services/license-v2/license-v2-service.ts
@@ -43,6 +43,7 @@ import {
TBuyBillingV2ProductDTO,
TCancelBillingV2TrialDTO,
TChangeBillingV2CommitmentDTO,
+ TConfirmBillingV2TrialPaymentDTO,
TCreateBillingV2PortalSessionDTO,
TGetBillingV2CatalogDTO,
TGetBillingV2OverviewDTO,
@@ -89,6 +90,7 @@ type TLicenseV2ServiceFactoryDep = {
| "changeCommitments"
| "startTrial"
| "cancelTrial"
+ | "confirmTrialPayment"
| "getTrials"
| "cancelSubscription"
| "resumeSubscription"
@@ -126,6 +128,27 @@ const formatDate = (unixSeconds: number | null | undefined): string | null => {
});
};
+// Payment URLs from the license server are handed to the browser as links, so anything but a
+// well-formed https URL is dropped rather than shown.
+const toHttpsUrl = (value: string | null | undefined): string | null => {
+ if (!value) {
+ return null;
+ }
+ try {
+ return new URL(value).protocol === "https:" ? value : null;
+ } catch {
+ return null;
+ }
+};
+
+const toPaymentAlert = (payment: TSubscriptionResponse["payment"]): BillingV2Overview["paymentAlert"] => {
+ if (!payment || (payment.state !== "needs_action" && payment.state !== "failed")) {
+ return null;
+ }
+ const actionUrl = toHttpsUrl(payment.actionUrl);
+ return actionUrl ? { state: payment.state, actionUrl } : null;
+};
+
// Entitlement product dates (trial_ends_at, current_period_end) are ISO strings, not unix seconds.
const formatIsoDate = (iso: string | null | undefined): string | null => {
if (!iso) {
@@ -663,6 +686,7 @@ export const licenseV2ServiceFactory = ({
trialPlanDaysLeft: daysUntil(item.trialPlanEndsAt)
}
: {}),
+ trialPaymentDueAt: formatDate(item.trialPaymentDueAt),
renewsOn,
...(deprecation ? { deprecation } : {}),
used,
@@ -799,6 +823,7 @@ export const licenseV2ServiceFactory = ({
planTier: trial.plan_key ?? null,
basePlanTier: trial.base_plan_key ?? null,
outcome: trial.outcome,
+ endedReason: trial.ended_reason ?? null,
endedDetail: trial.ended_detail ?? null,
endedAt: formatDate(trial.ended_at),
endedDaysAgo: daysSince(trial.ended_at)
@@ -837,6 +862,19 @@ export const licenseV2ServiceFactory = ({
nextCharge
};
+ const itemsAwaitingPayment = (subscription?.items ?? []).flatMap((item) =>
+ item.trialPaymentDueAt ? [{ productId: item.productId, dueAt: item.trialPaymentDueAt }] : []
+ );
+ const trialPaymentDue =
+ itemsAwaitingPayment.length > 0
+ ? {
+ dueAt: formatDate(Math.min(...itemsAwaitingPayment.map((item) => item.dueAt))) ?? "",
+ productKeys: [...new Set(itemsAwaitingPayment.map((item) => item.productId))]
+ }
+ : null;
+
+ const paymentAlert = toPaymentAlert(subscription?.payment);
+
const overview: BillingV2Overview = {
// Self-hosted is a read-only, managed view: the UI hides payment/invoices/details and shows the
// "managed by your account team" banner off these two fields.
@@ -852,6 +890,8 @@ export const licenseV2ServiceFactory = ({
trialedProductKeys: [...new Set(trialHistory.map((trial) => trial.productKey))],
trials: trialHistory,
onDemandAmount,
+ trialPaymentDue,
+ paymentAlert,
checkoutFrozen: subscription?.capabilities?.checkoutFrozen ?? false,
// false for an enterprise-managed org (self-serve mutations 403); default true keeps paygo and
// older servers unchanged.
@@ -1112,6 +1152,23 @@ export const licenseV2ServiceFactory = ({
return { products };
};
+ // The bank wants the customer to approve the charge on the Stripe invoice; the change settles by webhook
+ // once they do. Without a usable link there is nothing to send them to, so it degrades to the same
+ // coded error as a declined charge, which points them at the billing portal.
+ const paymentActionRequired = async (orgId: string, paymentUrl: string | undefined) => {
+ const url = toHttpsUrl(paymentUrl);
+ if (!url) {
+ logger.error(`billing-v2: payment_action_required without a usable paymentUrl [orgId=${orgId}]`);
+ throw new BadRequestError({
+ message:
+ "Your bank needs you to approve this payment, but we couldn't get the approval link. Open the billing portal to complete it.",
+ details: { code: "payment_action_required" }
+ });
+ }
+ await licenseClient.markEntitlementsStale(orgId, { checkout: true });
+ return { outcome: "payment_action_required" as const, paymentUrl: url };
+ };
+
const buildReturnUrl = (orgId: string, returnPath?: string): string => {
if (!envConfig.SITE_URL) {
throw new InternalServerError({ message: "Failed to build a billing return URL" });
@@ -1172,6 +1229,14 @@ export const licenseV2ServiceFactory = ({
returnUrl: buildReturnUrl(orgId, returnPath)
});
+ if (result.outcome === "payment_action_required") {
+ return {
+ ...(await paymentActionRequired(orgId, result.paymentUrl)),
+ plan: resolved.planTier,
+ cadence: normalizedCadence
+ };
+ }
+
if (result.outcome === "subscription_updated") {
await licenseClient.markEntitlementsStale(orgId);
return {
@@ -1312,6 +1377,9 @@ export const licenseV2ServiceFactory = ({
expectedPlanVersionId,
prorationDate
});
+ if (result.outcome === "payment_action_required") {
+ return paymentActionRequired(orgId, result.paymentUrl);
+ }
await licenseClient.markEntitlementsStale(orgId);
return {
outcome: result.outcome,
@@ -1330,6 +1398,9 @@ export const licenseV2ServiceFactory = ({
productId,
dimensions: changes.map((change) => ({ dimensionKey: change.dimensionKey, quantity: change.quantity }))
});
+ if (result.outcome === "payment_action_required") {
+ return paymentActionRequired(orgId, result.paymentUrl);
+ }
if (result.outcome === "checkout_created") {
if (!result.checkoutUrl) {
throw new InternalServerError({ message: "Checkout session did not return a URL" });
@@ -1381,6 +1452,15 @@ export const licenseV2ServiceFactory = ({
return { outcome: result.outcome };
};
+ // Hands back a Stripe Checkout that runs the bank's approval step for a trial conversion charge. The
+ // trial converts via webhook once it completes, so the revalidation window is held open like checkout.
+ const confirmTrialPayment = async ({ orgId, actor, returnPath }: TConfirmBillingV2TrialPaymentDTO) => {
+ await ensureManageBilling(orgId, actor);
+ const result = await licenseClient.confirmTrialPayment(orgId, { returnUrl: buildReturnUrl(orgId, returnPath) });
+ await licenseClient.markEntitlementsStale(orgId, { checkout: true });
+ return { outcome: result.outcome, checkoutUrl: result.checkoutUrl };
+ };
+
// Remove a single product from a multi-product subscription, the operation the Stripe Customer
// Portal cannot do. The license server prorates at commit time (Stripe default = now).
const removeProduct = async ({ orgId, actor, productId }: TRemoveBillingV2ProductDTO) => {
@@ -1419,6 +1499,7 @@ export const licenseV2ServiceFactory = ({
changeCommitments,
startTrial,
cancelTrial,
+ confirmTrialPayment,
cancelSubscription,
resumeSubscription
};
diff --git a/backend/src/ee/services/license-v2/license-v2-types.ts b/backend/src/ee/services/license-v2/license-v2-types.ts
index 4914208cdf..5879c5392b 100644
--- a/backend/src/ee/services/license-v2/license-v2-types.ts
+++ b/backend/src/ee/services/license-v2/license-v2-types.ts
@@ -144,6 +144,7 @@ export type BillingV2Entitlement = {
trialPlanName?: string;
trialPlanEndsAt?: string | null;
trialPlanDaysLeft?: number | null;
+ trialPaymentDueAt?: string | null;
// Formatted date this product's soonest line renews (each product bills on its own cycle); null when
// the product has no dated line (e.g. feature-only entitlements).
renewsOn?: string | null;
@@ -181,6 +182,7 @@ export type BillingV2Trial = {
planTier: string | null;
basePlanTier: string | null;
outcome: string;
+ endedReason: string | null;
endedDetail: string | null;
endedAt: string | null;
endedDaysAgo: number | null;
@@ -212,6 +214,10 @@ export type BillingV2Overview = {
trials: BillingV2Trial[];
// Total monthly on-demand overage across all products (dollars), for the summary's on-demand note.
onDemandAmount: number;
+ // Earliest trial payment deadline across products, for the page banner; null when none is waiting.
+ trialPaymentDue: { dueAt: string; productKeys: string[] } | null;
+ // A renewal invoice that needs approval or was declined. Named apart from `payment` (the card on file).
+ paymentAlert: { state: "needs_action" | "failed"; actionUrl: string } | null;
checkoutFrozen: boolean;
selfServe: boolean;
};
@@ -319,6 +325,7 @@ export type TRemoveBillingV2ProductDTO = {
// prices at the current server time; a client-supplied proration instant is never accepted. productId
// is required: it names the product so the server resolves the trialing plan and creates/attaches the
// subscription when there isn't one yet (a trialing org). Not trialing it → product_not_trialing.
+// Checkout also happens when the card on file needs the customer to approve the charge.
export type TChangeBillingV2CommitmentDTO = {
orgId: string;
actor: OrgServiceActor;
@@ -341,6 +348,12 @@ export type TCancelBillingV2TrialDTO = {
productId: string;
};
+export type TConfirmBillingV2TrialPaymentDTO = {
+ orgId: string;
+ actor: OrgServiceActor;
+ returnPath?: string;
+};
+
export type TBillingV2SubscriptionLifecycleDTO = {
orgId: string;
actor: OrgServiceActor;
diff --git a/backend/src/services/license-client/license-client-backends.test.ts b/backend/src/services/license-client/license-client-backends.test.ts
index a25abd88e3..770a92aac5 100644
--- a/backend/src/services/license-client/license-client-backends.test.ts
+++ b/backend/src/services/license-client/license-client-backends.test.ts
@@ -73,3 +73,67 @@ describe("licenseServerBackend region on license-creating calls", () => {
expect(readBody(fetchMock)).not.toHaveProperty("region");
});
});
+
+describe("licenseServerBackend confirmTrialPayment", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ test("posts the return URL to the org's trial confirm-payment endpoint", async () => {
+ const fetchMock = mockFetchReturning({
+ outcome: "checkout_created",
+ checkoutUrl: "https://checkout.stripe.com/c/1"
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ const result = await licenseServerBackend(SERVER_URL, "key", "eu").confirmTrialPayment(ORG_ID, {
+ returnUrl: "https://app.infisical.com/organizations/org-1/billing"
+ });
+
+ const [url, init] = vi.mocked(fetchMock).mock.calls[0];
+ expect(String(url)).toBe(`${SERVER_URL}/v1/organizations/${ORG_ID}/subscription/trials/confirm-payment`);
+ expect(init?.method).toBe("POST");
+ expect(readBody(fetchMock)).toEqual({ returnUrl: "https://app.infisical.com/organizations/org-1/billing" });
+ expect(result).toMatchObject({ outcome: "checkout_created", checkoutUrl: "https://checkout.stripe.com/c/1" });
+ });
+});
+
+describe("licenseServerBackend payment_action_required", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ test("changeCommitments accepts the approval outcome and its payment URL", async () => {
+ vi.stubGlobal(
+ "fetch",
+ mockFetchReturning({
+ outcome: "payment_action_required",
+ paymentUrl: "https://invoice.stripe.com/i/1",
+ subscriptionId: "sub_1",
+ request_id: "req-1"
+ })
+ );
+
+ const result = await licenseServerBackend(SERVER_URL, "key").changeCommitments(ORG_ID, {
+ productId: "boost",
+ dimensions: []
+ });
+
+ expect(result).toMatchObject({ outcome: "payment_action_required", paymentUrl: "https://invoice.stripe.com/i/1" });
+ });
+
+ test("upgradeProduct accepts the approval outcome", async () => {
+ vi.stubGlobal(
+ "fetch",
+ mockFetchReturning({ outcome: "payment_action_required", paymentUrl: "https://invoice.stripe.com/i/1" })
+ );
+
+ const result = await licenseServerBackend(SERVER_URL, "key").upgradeProduct(ORG_ID, {
+ productId: "boost",
+ plan: "enterprise",
+ expectedPlanVersionId: "v1"
+ });
+
+ expect(result.outcome).toBe("payment_action_required");
+ });
+});
diff --git a/backend/src/services/license-client/license-client-backends.ts b/backend/src/services/license-client/license-client-backends.ts
index 626ed8a85b..3d0934cdc3 100644
--- a/backend/src/services/license-client/license-client-backends.ts
+++ b/backend/src/services/license-client/license-client-backends.ts
@@ -9,6 +9,7 @@ import {
catalogResponseSchema,
checkoutResultSchema,
cloudPlanResponseSchema,
+ confirmTrialPaymentResultSchema,
entitlementsResponseSchema,
sessionResponseSchema,
subscriptionPreviewResponseSchema,
@@ -20,6 +21,8 @@ import {
TChangeCommitmentsPayload,
TCheckoutResult,
TCloudPlanResponse,
+ TConfirmTrialPaymentPayload,
+ TConfirmTrialPaymentResult,
TCreatePortalPayload,
TEntitlementOrg,
TEntitlementsResponse,
@@ -96,7 +99,8 @@ const BILLING_ERROR_MESSAGES: Record<string, string> = {
dimension_not_priced: "That plan doesn't price something you're billed for today. Contact support to switch.",
no_payment_method: "Add a payment method before making this change.",
subscription_syncing: "Your billing details are still syncing. Please try again in a moment.",
- plan_deprecated: "This plan is being retired and is no longer available."
+ plan_deprecated: "This plan is being retired and is no longer available.",
+ no_trial_awaiting_payment: "There's no trial payment waiting to be completed. It may have already gone through."
};
const throwIfResponseError = async (res: Response): Promise<void> => {
@@ -106,15 +110,14 @@ const throwIfResponseError = async (res: Response): Promise<void> => {
const requestId = readLicenseRequestId(res);
if (res.status >= 400 && res.status < 500) {
const body = (await res.json().catch(() => null)) as {
- error?: string;
message?: string;
details?: { code?: string };
} | null;
// Resolve the contract's machine code (details.code) to friendly copy so the message thrown here is
- // user-facing; keep the code in details for any caller that still branches on it. The envelope uses
- // `error`; older servers used `message`, so read both as the fallback.
+ // user-facing; keep the code in details for any caller that still branches on it. Otherwise fall back
+ // to the envelope's `message`, which is written for the customer (`error` is the class name).
const code = body?.details?.code;
- const message = (code && BILLING_ERROR_MESSAGES[code]) || body?.error || body?.message;
+ const message = (code && BILLING_ERROR_MESSAGES[code]) || body?.message;
logger.warn(licenseErrorMessage(requestId, `request rejected [status=${res.status}] [code=${code ?? "none"}]`));
throw new BadRequestError({
name: LICENSE_SERVER_ERROR_NAME,
@@ -358,6 +361,22 @@ export const licenseServerBackend = (
return trialCancelResultSchema.parse(body);
},
+ confirmTrialPayment: async (
+ orgId: string,
+ payload: TConfirmTrialPaymentPayload
+ ): Promise<TConfirmTrialPaymentResult> => {
+ const url = new URL(orgScoped(orgId, "/subscription/trials/confirm-payment"), serverUrl);
+ const res = await fetch(url, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${mintServiceToken(signingKey)}`, "Content-Type": "application/json" },
+ body: JSON.stringify({ returnUrl: payload.returnUrl }),
+ redirect: "manual"
+ });
+ await throwIfResponseError(res);
+ const body: unknown = await res.json();
+ return confirmTrialPaymentResultSchema.parse(body);
+ },
+
// The org's trial history. 404 (org has no license yet) degrades to an empty history.
fetchTrials: async (orgId: string): Promise<TTrialsResponse> => {
const url = new URL(orgScoped(orgId, "/billing/trials"), serverUrl);
@@ -483,6 +502,7 @@ export const licenseServerSelfHostedBackend = (
changeCommitments: notSupportedOnSelfHosted("changeCommitments"),
startTrial: notSupportedOnSelfHosted("startTrial"),
cancelTrial: notSupportedOnSelfHosted("cancelTrial"),
+ confirmTrialPayment: notSupportedOnSelfHosted("confirmTrialPayment"),
fetchTrials: notSupportedOnSelfHosted("fetchTrials"),
cancelSubscription: notSupportedOnSelfHosted("cancelSubscription"),
resumeSubscription: notSupportedOnSelfHosted("resumeSubscription")
diff --git a/backend/src/services/license-client/license-client-types.ts b/backend/src/services/license-client/license-client-types.ts
index 4ffbcd2153..89a12427e9 100644
--- a/backend/src/services/license-client/license-client-types.ts
+++ b/backend/src/services/license-client/license-client-types.ts
@@ -169,6 +169,7 @@ const subscriptionItemSchema = z
trialEndsAt: z.number().nullish(),
trialPlan: z.string().nullish(),
trialPlanEndsAt: z.number().nullish(),
+ trialPaymentDueAt: z.number().nullish(),
// Present only when this item's product OR plan is deprecated (product supersedes plan). The item
// keeps working; this carries the contract-specific message (the sunset date comes from the catalog).
deprecation: z.object({ reason: z.string().nullish(), nextSteps: z.string().nullish() }).nullish(),
@@ -224,6 +225,7 @@ export const subscriptionResponseSchema = z
currentPeriodEnd: z.number().nullish(),
recurringTotal: z.number().nullish(),
billing: subscriptionBillingSchema.nullish(),
+ payment: z.object({ state: z.string(), actionUrl: z.string() }).passthrough().nullish(),
tier: z.string().optional(),
items: z.array(subscriptionItemSchema)
})
@@ -238,11 +240,14 @@ export const sessionResponseSchema = z
// Result of a checkout / add / remove / commitment change. Checkout either needs the customer to
// complete a Stripe Checkout (checkout_created) or is applied directly to an existing subscription
// (subscription_updated). Removing the last product cancels the whole subscription
-// (subscription_canceled).
+// (subscription_canceled). payment_action_required: the card's bank wants the customer to approve the
+// charge on the Stripe invoice at paymentUrl. paymentUrl stays a plain string so a bad value can't fail
+// the parse; the service validates it.
export const checkoutResultSchema = z
.object({
- outcome: z.enum(["checkout_created", "subscription_updated", "subscription_canceled"]),
+ outcome: z.enum(["checkout_created", "subscription_updated", "subscription_canceled", "payment_action_required"]),
checkoutUrl: z.string().optional(),
+ paymentUrl: z.string().optional(),
subscriptionId: z.string().optional()
})
.passthrough();
@@ -276,7 +281,8 @@ export const subscriptionPreviewResponseSchema = z
export const upgradeResultSchema = z
.object({
- outcome: z.literal("upgraded"),
+ outcome: z.enum(["upgraded", "payment_action_required"]),
+ paymentUrl: z.string().optional(),
subscriptionId: z.string().optional(),
fromPlanKey: z.string().optional(),
toPlanKey: z.string().optional(),
@@ -429,7 +435,8 @@ export type TCreatePortalPayload = {
// The license server prices at its current time; the app never forwards a client-supplied instant.
// productId is required: it names the product so the server can resolve the trialing plan and
// create/attach the subscription when there isn't one yet (a trialing org) instead of having to infer
-// it. Not trialing the named product → product_not_trialing.
+// it. Not trialing the named product → product_not_trialing. Returns checkout_created when the org
+// has no subscription yet or when the card needs the customer to approve the charge.
export type TChangeCommitmentsPayload = {
productId: string;
dimensions: TCommitmentChange[];
@@ -469,6 +476,26 @@ export type TCancelTrialPayload = {
productKey: string;
};
+export type TConfirmTrialPaymentPayload = {
+ returnUrl: string;
+};
+
+// A Stripe Checkout that runs the bank's approval step for a trial conversion charge. 409
+// no_trial_awaiting_payment when nothing is waiting.
+const confirmTrialPaymentResultSchema = z
+ .object({
+ outcome: z.literal("checkout_created"),
+ checkoutUrl: z
+ .string()
+ .url()
+ .refine((val) => val.startsWith("http://") || val.startsWith("https://"), {
+ message: "URL must start with http:// or https://"
+ })
+ })
+ .passthrough();
+export type TConfirmTrialPaymentResult = z.infer<typeof confirmTrialPaymentResultSchema>;
+export { confirmTrialPaymentResultSchema };
+
// Revokes the trialing entitlement immediately (product → free) and marks the trial completed so it
// never converts. Idempotent-ish: the server 404s when there's no active trial to cancel.
const trialCancelResultSchema = z.object({ outcome: z.literal("trial_completed") }).passthrough();
@@ -484,6 +511,9 @@ const trialHistoryItemSchema = z
base_plan_key: z.string().nullish(),
// trialing | converted | expired | canceled | completed | reverted
outcome: z.string(),
+ // Why the trial ended (e.g. payment_not_completed). ended_detail is a machine code only on
+ // `reverted`; on `canceled` it is free text.
+ ended_reason: z.string().nullish(),
ended_detail: z.string().nullish(),
started_at: z.number().nullish(),
trial_ends_at: z.number().nullish(),
@@ -516,6 +546,7 @@ export type TLicenseClientBackend = {
startTrial: (orgId: string, payload: TStartTrialPayload) => Promise<TTrialResult>;
// Cancel an in-progress trial for a product (product → free; the trial never converts).
cancelTrial: (orgId: string, payload: TCancelTrialPayload) => Promise<TTrialCancelResult>;
+ confirmTrialPayment: (orgId: string, payload: TConfirmTrialPaymentPayload) => Promise<TConfirmTrialPaymentResult>;
// The org's trial history, used to tell which products have already used their one-time trial.
fetchTrials: (orgId: string) => Promise<TTrialsResponse>;
cancelSubscription: (orgId: string) => Promise<TCheckoutResult>;
diff --git a/backend/src/services/license-client/license-client.ts b/backend/src/services/license-client/license-client.ts
index 6f1adbe1fb..1c40eadcd4 100644
--- a/backend/src/services/license-client/license-client.ts
+++ b/backend/src/services/license-client/license-client.ts
@@ -9,6 +9,7 @@ import {
TBuyProductPayload,
TCancelTrialPayload,
TChangeCommitmentsPayload,
+ TConfirmTrialPaymentPayload,
TCreatePortalPayload,
TEntitlementOrg,
TLicenseClientBackend,
@@ -205,6 +206,13 @@ export const licenseClientFactory = ({ envConfig, keyStore, isOffline = false }:
return backend.cancelTrial(orgId, payload);
};
+ const confirmTrialPayment = async (orgId: string, payload: TConfirmTrialPaymentPayload) => {
+ if (!backend) {
+ throw new Error("license client backend is not configured");
+ }
+ return backend.confirmTrialPayment(orgId, payload);
+ };
+
// The org's trial history; returns an empty history when no backend is configured (self-hosted).
const getTrials = async (orgId: string) => {
if (!backend) {
@@ -248,6 +256,7 @@ export const licenseClientFactory = ({ envConfig, keyStore, isOffline = false }:
changeCommitments,
startTrial,
cancelTrial,
+ confirmTrialPayment,
getTrials,
cancelSubscription,
resumeSubscription
diff --git a/frontend/src/hooks/api/billingV2/index.tsx b/frontend/src/hooks/api/billingV2/index.tsx
index 4db58a26d8..2bcb46397f 100644
--- a/frontend/src/hooks/api/billingV2/index.tsx
+++ b/frontend/src/hooks/api/billingV2/index.tsx
@@ -4,6 +4,7 @@ export {
useCancelBillingV2Subscription,
useCancelBillingV2Trial,
useChangeBillingV2Commitment,
+ useConfirmBillingV2TrialPayment,
useCreateBillingV2PortalSession,
usePreviewBillingV2Change,
useRefreshBillingV2Entitlements,
@@ -45,4 +46,4 @@ export type {
BillingV2UpgradeResult,
BillingV2UsageBreakdown
} from "./types";
-export { BillingV2BreakdownDimension } from "./types";
+export { BillingV2BreakdownDimension, BillingV2ErrorCode } from "./types";
diff --git a/frontend/src/hooks/api/billingV2/mutations.tsx b/frontend/src/hooks/api/billingV2/mutations.tsx
index 94b7fb7fa5..c00ad71cc8 100644
--- a/frontend/src/hooks/api/billingV2/mutations.tsx
+++ b/frontend/src/hooks/api/billingV2/mutations.tsx
@@ -1,4 +1,5 @@
import { QueryClient, useMutation, useQueryClient } from "@tanstack/react-query";
+import axios from "axios";
import { apiRequest } from "@app/config/request";
@@ -6,6 +7,8 @@ import { subscriptionQueryKeys } from "../subscriptions/queries";
import { billingV2Keys } from "./queries";
import {
BillingV2CheckoutResult,
+ BillingV2ConfirmTrialPaymentResult,
+ BillingV2ErrorCode,
BillingV2MutationResult,
BillingV2Preview,
BillingV2TrialCancelResult,
@@ -16,6 +19,7 @@ import {
TBuyBillingV2ProductDTO,
TCancelBillingV2TrialDTO,
TChangeBillingV2CommitmentDTO,
+ TConfirmBillingV2TrialPaymentDTO,
TCreateBillingV2PortalSessionDTO,
TPreviewBillingV2ChangeDTO,
TRemoveBillingV2ProductDTO,
@@ -185,6 +189,31 @@ export const useStartBillingV2Trial = () => {
});
};
+// Opens a Stripe Checkout where the customer approves a trial conversion charge their bank is holding.
+// A no_trial_awaiting_payment error means the payment already went through, so refetch to drop the
+// stale banner; the global handler still shows the message.
+export const useConfirmBillingV2TrialPayment = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ orgId, returnPath }: TConfirmBillingV2TrialPaymentDTO) => {
+ const { data } = await apiRequest.post<BillingV2ConfirmTrialPaymentResult>(
+ `/api/v1/organizations/${orgId}/billing/v2/trial/confirm-payment`,
+ { returnPath }
+ );
+
+ return data;
+ },
+ onError: (error, { orgId }) => {
+ if (
+ axios.isAxiosError<{ details?: { code?: string } }>(error) &&
+ error.response?.data?.details?.code === BillingV2ErrorCode.NoTrialAwaitingPayment
+ ) {
+ invalidateBillingV2(queryClient, orgId);
+ }
+ }
+ });
+};
+
// Cancel an in-progress trial for a product (product drops to free; the trial never converts).
export const useCancelBillingV2Trial = () => {
const queryClient = useQueryClient();
diff --git a/frontend/src/hooks/api/billingV2/types.ts b/frontend/src/hooks/api/billingV2/types.ts
index ca90884392..34825df897 100644
--- a/frontend/src/hooks/api/billingV2/types.ts
+++ b/frontend/src/hooks/api/billingV2/types.ts
@@ -143,6 +143,9 @@ export type BillingV2Entitlement = {
trialPlanName?: string;
trialPlanEndsAt?: string | null;
trialPlanDaysLeft?: number | null;
+ // Formatted grace deadline while the trial's conversion charge waits on the customer's bank. The
+ // product stays trialing and usable until then, even though trialEndsAt has passed.
+ trialPaymentDueAt?: string | null;
// Formatted date this product's soonest line renews (each product bills on its own cycle); null when
// the product has no dated line.
renewsOn?: string | null;
@@ -168,6 +171,9 @@ export type BillingV2Trial = {
planTier: string | null;
basePlanTier: string | null;
outcome: BillingV2TrialOutcome | string;
+ // Why the trial ended (e.g. payment_not_completed). endedDetail is a machine code only when outcome
+ // is "reverted"; on "canceled" it is free text, so never map it outside that case.
+ endedReason: string | null;
endedDetail: string | null;
endedAt: string | null;
endedDaysAgo: number | null;
@@ -213,6 +219,8 @@ export type BillingV2Overview = {
entitlements: Record<string, BillingV2Entitlement>;
trialedProductKeys: string[];
trials: BillingV2Trial[];
+ trialPaymentDue: { dueAt: string; productKeys: string[] } | null;
+ paymentAlert: { state: "needs_action" | "failed"; actionUrl: string } | null;
// Mutating billing actions are frozen server-side; the UI disables purchase/commit/remove controls.
checkoutFrozen: boolean;
// false for an enterprise-managed org: render the self-serve billing UI but disable its controls
@@ -220,9 +228,12 @@ export type BillingV2Overview = {
selfServe: boolean;
};
+// payment_action_required: the bank wants the customer to approve the charge on the Stripe invoice at
+// paymentUrl, which has no return URL, so open it in a new tab rather than redirecting.
export type BillingV2CheckoutResult = {
- outcome: "checkout_created" | "subscription_updated";
+ outcome: "checkout_created" | "subscription_updated" | "payment_action_required";
checkoutUrl?: string;
+ paymentUrl?: string;
subscriptionId?: string;
};
@@ -272,10 +283,9 @@ export type BillingV2Preview = {
};
export type BillingV2MutationResult = {
- // checkout_created is returned when committing on a trialing org with no card created the
- // subscription and it needs hosted checkout (checkoutUrl); otherwise subscription_updated.
- outcome?: "checkout_created" | "subscription_updated";
+ outcome?: "checkout_created" | "subscription_updated" | "payment_action_required";
checkoutUrl?: string;
+ paymentUrl?: string;
subscriptionId?: string;
};
@@ -311,7 +321,8 @@ export type TUpgradeBillingV2ProductDTO = {
};
export type BillingV2UpgradeResult = {
- outcome: "upgraded";
+ outcome: "upgraded" | "payment_action_required";
+ paymentUrl?: string;
subscriptionId?: string;
fromPlanKey?: string;
toPlanKey?: string;
@@ -355,6 +366,22 @@ export type BillingV2TrialCancelResult = {
outcome: "trial_completed";
};
+export type TConfirmBillingV2TrialPaymentDTO = {
+ orgId: string;
+ returnPath?: string;
+};
+
+export type BillingV2ConfirmTrialPaymentResult = {
+ outcome: "checkout_created";
+ checkoutUrl: string;
+};
+
+// License-server machine codes the billing UI branches on (read from the error's details.code).
+export const BillingV2ErrorCode = {
+ PaymentActionRequired: "payment_action_required",
+ NoTrialAwaitingPayment: "no_trial_awaiting_payment"
+} as const;
+
export type TBillingV2LifecycleDTO = {
orgId: string;
};
diff --git a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
index bd441cc5f8..f6ccea033b 100644
--- a/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/BillingV2Page.tsx
@@ -16,6 +16,7 @@ import { useDebounce } from "@app/hooks";
import {
BillingV2BreakdownScopeKind,
useAddBillingV2PaymentMethod,
+ useConfirmBillingV2TrialPayment,
useCreateBillingV2PortalSession,
useGetBillingV2Catalog,
useGetBillingV2Organizations,
@@ -83,6 +84,7 @@ export const BillingV2Page = () => {
const { data: catalog = [] } = useGetBillingV2Catalog(selectedOrgId);
const createPortalSession = useCreateBillingV2PortalSession();
const addPaymentMethod = useAddBillingV2PaymentMethod();
+ const confirmTrialPayment = useConfirmBillingV2TrialPayment();
// More than one organization means the server decided this caller may switch: an instance admin on
// self-hosted, where one licence spans every org on the box. Cloud is bounded to the logged-in root
@@ -183,6 +185,20 @@ export const BillingV2Page = () => {
);
};
+ const onCompleteTrialPayment = () => {
+ confirmTrialPayment.mutate(
+ {
+ orgId: selectedOrgId,
+ returnPath: window.location.pathname
+ },
+ {
+ onSuccess: ({ checkoutUrl }) => {
+ window.location.href = checkoutUrl;
+ }
+ }
+ );
+ };
+
// Billing name/email and address are edited in the Stripe billing portal.
const onEditDetails = () => {
redirectToPortal();
@@ -244,6 +260,8 @@ export const BillingV2Page = () => {
onUpdatePayment={onUpdatePayment}
onEditDetails={onEditDetails}
onContact={onContact}
+ onCompleteTrialPayment={onCompleteTrialPayment}
+ isCompletingTrialPayment={confirmTrialPayment.isPending}
onRetry={onRetry}
canManageBilling={canManageBilling}
/>
diff --git a/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts b/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts
index 83fc147dd3..1e50a3b68d 100644
--- a/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts
+++ b/frontend/src/pages/organization/BillingV2Page/billing-v2-format.ts
@@ -1,3 +1,5 @@
+import axios from "axios";
+
import {
BillingV2Cadence,
BillingV2CatalogProduct,
@@ -19,6 +21,12 @@ export const catalogById = (
export const byDisplayOrder = <T extends { displayOrder?: number }>(a: T, b: T): number =>
(a.displayOrder ?? 0) - (b.displayOrder ?? 0);
+// The license server's machine code (details.code) on a failed billing request, if any.
+export const billingV2ErrorCode = (error: unknown): string | undefined =>
+ axios.isAxiosError<{ details?: { code?: string } }>(error)
+ ? error.response?.data?.details?.code
+ : undefined;
+
export const fmtMoney = (n: number, maximumFractionDigits = 0): string =>
`$${Number(n).toLocaleString("en-US", { maximumFractionDigits })}`;
diff --git a/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx b/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx
index 7bc2cbba58..79d20cfbab 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/ActivateView.tsx
@@ -8,15 +8,23 @@ import {
BillingV2Cadence,
BillingV2CatalogProduct,
BillingV2Dim,
+ BillingV2ErrorCode,
BillingV2Plan,
useBuyBillingV2Product,
usePreviewBillingV2Change
} from "@app/hooks/api";
-import { fmtMoney } from "../billing-v2-format";
+import { billingV2ErrorCode, fmtMoney } from "../billing-v2-format";
import { ChargeBreakdown } from "./ChargeBreakdown";
import { CommitmentTerms } from "./CommitmentTerms";
-import { CostSummary, CostSummaryRow, ProductIcon, Stepper } from "./shared";
+import {
+ CostSummary,
+ CostSummaryRow,
+ PaymentActionRequiredNotice,
+ PaymentApprovalNotice,
+ ProductIcon,
+ Stepper
+} from "./shared";
type Props = {
orgId: string;
@@ -123,6 +131,15 @@ export const ActivateView = ({
const quantitiesForCadence = cadence === "annual" ? commitments : undefined;
const quantitiesKey = JSON.stringify(quantitiesForCadence ?? {});
+ // Keyed to the selection that was declined, so changing cadence or quantities clears the notice.
+ const selectionKey = `${cadence}:${quantitiesKey}`;
+ const [declinedSelectionKey, setDeclinedSelectionKey] = useState<string | null>(null);
+ const showPaymentActionRequired = declinedSelectionKey === selectionKey;
+ const [approval, setApproval] = useState<{ selectionKey: string; paymentUrl: string } | null>(
+ null
+ );
+ const approvalUrl = approval?.selectionKey === selectionKey ? approval.paymentUrl : null;
+
// The plan's headline price for the chosen cadence, shown on the static product row.
const localRecurring = cadence === "annual" ? annualHeadline(plan) : monthlyHeadline(plan);
@@ -203,6 +220,8 @@ export const ActivateView = ({
}, [plan]);
const handleActivate = async () => {
+ setDeclinedSelectionKey(null);
+ setApproval(null);
try {
const result = await buyProduct.mutateAsync({
orgId,
@@ -212,6 +231,10 @@ export const ActivateView = ({
quantities: quantitiesForCadence,
returnPath
});
+ if (result.outcome === "payment_action_required" && result.paymentUrl) {
+ setApproval({ selectionKey, paymentUrl: result.paymentUrl });
+ return;
+ }
if (result.outcome === "subscription_updated") {
createNotification({
type: "success",
@@ -225,8 +248,11 @@ export const ActivateView = ({
return;
}
createNotification({ type: "error", text: "Failed to start checkout." });
- } catch {
+ } catch (error) {
// The backend's message is surfaced by the global mutation error handler (reactQuery.tsx).
+ if (billingV2ErrorCode(error) === BillingV2ErrorCode.PaymentActionRequired) {
+ setDeclinedSelectionKey(selectionKey);
+ }
}
};
@@ -353,6 +379,9 @@ export const ActivateView = ({
{needsCommitmentAck && (
<CommitmentTerms acknowledged={acknowledged} onAcknowledgedChange={setAcknowledged} />
)}
+
+ {showPaymentActionRequired && <PaymentActionRequiredNotice orgId={orgId} />}
+ {approvalUrl && <PaymentApprovalNotice paymentUrl={approvalUrl} />}
</div>
<SheetFooter className="flex-row justify-between border-t">
diff --git a/frontend/src/pages/organization/BillingV2Page/components/Banner.tsx b/frontend/src/pages/organization/BillingV2Page/components/Banner.tsx
index 702848f111..af703cec8e 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/Banner.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/Banner.tsx
@@ -1,6 +1,14 @@
-import { CircleAlert, CreditCard, Info, type LucideIcon, TriangleAlert } from "lucide-react";
+import {
+ CircleAlert,
+ CreditCard,
+ ExternalLink,
+ Info,
+ type LucideIcon,
+ TriangleAlert
+} from "lucide-react";
import { Alert, AlertDescription, AlertTitle, Button } from "@app/components/v3";
+import { BillingV2Overview } from "@app/hooks/api";
import { BillingV2Mode, BillingV2RenderState } from "../billing-v2-view-types";
@@ -8,6 +16,7 @@ type BannerProps = {
mode: BillingV2Mode;
subState: BillingV2RenderState;
canManage: boolean;
+ paymentAlert?: BillingV2Overview["paymentAlert"];
onUpdatePayment: () => void;
onManageSubscription: () => void;
};
@@ -34,12 +43,34 @@ const DUNNING: Partial<Record<BillingV2RenderState, Dunning>> = {
}
};
+const PAYMENT_ALERT: Record<
+ NonNullable<BillingV2Overview["paymentAlert"]>["state"],
+ Dunning & { actionLabel: string }
+> = {
+ needs_action: {
+ variant: "warning",
+ icon: TriangleAlert,
+ title: "Your bank needs you to approve your renewal payment",
+ body: "Approve the payment to keep your products active.",
+ actionLabel: "Approve payment"
+ },
+ failed: {
+ variant: "danger",
+ icon: CircleAlert,
+ title: "Your last payment failed",
+ body: "Pay the open invoice or update your payment method to avoid losing access.",
+ actionLabel: "Pay invoice"
+ }
+};
+
// Top-of-page notice: a managed org shows the "managed by your account team" note; a self-serve org in
-// dunning (past-due / suspended) shows a payment-recovery prompt. Nothing otherwise.
+// dunning (past-due / suspended) shows a payment-recovery prompt. A renewal payment alert replaces the
+// generic dunning prompt so a past-due org never sees two payment banners. Nothing otherwise.
export const Banner = ({
mode,
subState,
canManage,
+ paymentAlert,
onUpdatePayment,
onManageSubscription
}: BannerProps) => {
@@ -56,6 +87,38 @@ export const Banner = ({
);
}
+ if (paymentAlert) {
+ const alert = PAYMENT_ALERT[paymentAlert.state];
+ const AlertIcon = alert.icon;
+ return (
+ <Alert variant={alert.variant}>
+ <AlertIcon />
+ <AlertTitle>{alert.title}</AlertTitle>
+ <AlertDescription>
+ {alert.body}
+ {canManage && (
+ <div className="mt-3 flex flex-wrap gap-2">
+ <Button
+ variant={alert.variant}
+ size="sm"
+ onClick={() => window.open(paymentAlert.actionUrl, "_blank", "noopener,noreferrer")}
+ >
+ <ExternalLink />
+ {alert.actionLabel}
+ </Button>
+ {paymentAlert.state === "failed" && (
+ <Button variant="outline" size="sm" onClick={onUpdatePayment}>
+ <CreditCard />
+ Update payment method
+ </Button>
+ )}
+ </div>
+ )}
+ </AlertDescription>
+ </Alert>
+ );
+ }
+
const dunning = DUNNING[subState];
if (!dunning) {
return null;
diff --git a/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx b/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx
index 1d8e339b2f..5061cb070f 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/CommitmentView.tsx
@@ -14,14 +14,22 @@ import {
BillingV2CatalogProduct,
BillingV2CommitmentChange,
BillingV2Entitlement,
+ BillingV2ErrorCode,
useChangeBillingV2Commitment,
usePreviewBillingV2Change
} from "@app/hooks/api";
-import { dimCommitManageable, fmtMoney } from "../billing-v2-format";
+import { billingV2ErrorCode, dimCommitManageable, fmtMoney } from "../billing-v2-format";
import { ChargeBreakdown } from "./ChargeBreakdown";
import { CommitmentTerms } from "./CommitmentTerms";
-import { CostSummary, CostSummaryRow, ProductIcon, Stepper } from "./shared";
+import {
+ CostSummary,
+ CostSummaryRow,
+ PaymentActionRequiredNotice,
+ PaymentApprovalNotice,
+ ProductIcon,
+ Stepper
+} from "./shared";
type Props = {
orgId: string;
@@ -93,6 +101,12 @@ export const CommitmentView = ({
const changesKey = JSON.stringify(changes);
const hasChanges = changes.length > 0;
+ // Keyed to the changes that were declined, so editing the selection clears the notice.
+ const [declinedChangesKey, setDeclinedChangesKey] = useState<string | null>(null);
+ const showPaymentActionRequired = declinedChangesKey === changesKey;
+ const [approval, setApproval] = useState<{ changesKey: string; paymentUrl: string } | null>(null);
+ const approvalUrl = approval?.changesKey === changesKey ? approval.paymentUrl : null;
+
// A preview is fresh only once priced for the current changes; stale ones render as skeletons.
const previewFresh =
!preview.isPending &&
@@ -153,9 +167,16 @@ export const CommitmentView = ({
const canConfirm = selfServe && hasChanges && previewFresh && (!isIncreasing || acknowledged);
const handleConfirm = async () => {
+ setDeclinedChangesKey(null);
+ setApproval(null);
try {
const result = await applyCommitment.mutateAsync({ orgId, changes, productId: prod.id });
- if (result.checkoutUrl) {
+ if (result.outcome === "payment_action_required" && result.paymentUrl) {
+ setApproval({ changesKey, paymentUrl: result.paymentUrl });
+ return;
+ }
+ // checkout_created: no card on a trialing org, or the card needs the customer to approve it.
+ if (result.outcome === "checkout_created" && result.checkoutUrl) {
window.location.href = result.checkoutUrl;
return;
}
@@ -164,8 +185,11 @@ export const CommitmentView = ({
text: `${prod.name} commitment updated. It may take a moment to update here.`
});
onDone();
- } catch {
+ } catch (error) {
// The backend's message is surfaced by the global mutation error handler (reactQuery.tsx).
+ if (billingV2ErrorCode(error) === BillingV2ErrorCode.PaymentActionRequired) {
+ setDeclinedChangesKey(changesKey);
+ }
}
};
@@ -302,6 +326,9 @@ export const CommitmentView = ({
{isIncreasing && (
<CommitmentTerms acknowledged={acknowledged} onAcknowledgedChange={setAcknowledged} />
)}
+
+ {showPaymentActionRequired && <PaymentActionRequiredNotice orgId={orgId} />}
+ {approvalUrl && <PaymentApprovalNotice paymentUrl={approvalUrl} />}
</div>
<SheetFooter className="flex-row justify-between border-t">
diff --git a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
index eaa7655d69..1987b29a0f 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/Overview.tsx
@@ -36,6 +36,8 @@ export type OverviewProps = {
onUpdatePayment: () => void;
onEditDetails: () => void;
onContact: (prod: BillingV2CatalogProduct) => void;
+ onCompleteTrialPayment: () => void;
+ isCompletingTrialPayment: boolean;
onRetry: () => void;
canManageBilling: boolean;
};
@@ -60,6 +62,8 @@ export const Overview = ({
onUpdatePayment,
onEditDetails,
onContact,
+ onCompleteTrialPayment,
+ isCompletingTrialPayment,
onRetry,
canManageBilling
}: OverviewProps) => {
@@ -188,6 +192,7 @@ export const Overview = ({
mode={mode}
subState={subState}
canManage={canManageBilling}
+ paymentAlert={overview.paymentAlert}
onUpdatePayment={onUpdatePayment}
onManageSubscription={onManageSubscription}
/>
@@ -215,6 +220,7 @@ export const Overview = ({
mode={mode}
subState={subState}
canManage={canManageBilling}
+ paymentAlert={overview.paymentAlert}
onUpdatePayment={onUpdatePayment}
onManageSubscription={onManageSubscription}
/>
@@ -225,6 +231,8 @@ export const Overview = ({
onManage={onUpgrade}
onUpdatePayment={onUpdatePayment}
onContact={onContact}
+ onCompleteTrialPayment={onCompleteTrialPayment}
+ isCompletingTrialPayment={isCompletingTrialPayment}
/>
<BillingHeaderCard overview={overview} catalog={catalog} />
<ProductsCard
diff --git a/frontend/src/pages/organization/BillingV2Page/components/TrialBanners.tsx b/frontend/src/pages/organization/BillingV2Page/components/TrialBanners.tsx
index ca9248d389..399da1be33 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/TrialBanners.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/TrialBanners.tsx
@@ -1,18 +1,24 @@
-import { CircleAlert } from "lucide-react";
+import { CircleAlert, CreditCard } from "lucide-react";
import { Alert, AlertDescription, AlertTitle, Button } from "@app/components/v3";
import { BillingV2CatalogProduct, BillingV2Overview, BillingV2Trial } from "@app/hooks/api";
import { tierLabel } from "../billing-v2-format";
-// A reverted trial stays in the history forever, so only surface it while it is still actionable.
-const REVERTED_NOTICE_DAYS = 14;
+// An ended trial stays in the history forever, so only surface it while it is still actionable.
+const ENDED_NOTICE_DAYS = 14;
+
+const PAYMENT_NOT_COMPLETED = "payment_not_completed";
const REVERTED_REASON: Record<string, { body: string; action?: "payment" | "contact" }> = {
no_payment_method: {
body: "We couldn't charge a card when the trial ended, so nothing changed.",
action: "payment"
},
+ payment_action_required: {
+ body: "Your bank needed you to approve the charge when the trial ended, so nothing changed.",
+ action: "payment"
+ },
commitment_not_portable: {
body: "Your annual commitment couldn't carry over to the new plan, so nothing changed.",
action: "contact"
@@ -35,10 +41,14 @@ const planName = (
return prod?.plans.find((plan) => plan.tier === tier)?.name ?? tierLabel(tier);
};
+const isRecent = (trial: BillingV2Trial): boolean =>
+ trial.endedDaysAgo === null || trial.endedDaysAgo <= ENDED_NOTICE_DAYS;
+
const isRecentRevert = (trial: BillingV2Trial): boolean =>
- trial.outcome === "reverted" &&
- Boolean(trial.basePlanTier) &&
- (trial.endedDaysAgo === null || trial.endedDaysAgo <= REVERTED_NOTICE_DAYS);
+ trial.outcome === "reverted" && Boolean(trial.basePlanTier) && isRecent(trial);
+
+const isRecentUnpaidEnd = (trial: BillingV2Trial): boolean =>
+ trial.outcome !== "reverted" && trial.endedReason === PAYMENT_NOT_COMPLETED && isRecent(trial);
type Props = {
overview: BillingV2Overview;
@@ -47,6 +57,8 @@ type Props = {
onManage: (productId: string) => void;
onUpdatePayment: () => void;
onContact: (prod: BillingV2CatalogProduct) => void;
+ onCompleteTrialPayment: () => void;
+ isCompletingTrialPayment: boolean;
};
// A running upgrade trial is rendered on the product's own card, not here. This is only the
@@ -57,19 +69,52 @@ export const TrialBanners = ({
readOnly,
onManage,
onUpdatePayment,
- onContact
+ onContact,
+ onCompleteTrialPayment,
+ isCompletingTrialPayment
}: Props) => {
- // A revert that has since been superseded by a running trial of the same product is stale news.
+ const canAct = overview.selfServe && !readOnly;
+ // The trial history is a permanent log, so an unpaid end is stale news once the org has moved on:
+ // it is trialing the product again, or now holds it on an active paid plan.
+ const isSuperseded = (trial: BillingV2Trial): boolean => {
+ const entitlement = overview.entitlements[trial.productKey];
+ return Boolean(
+ entitlement?.trialPlan || entitlement?.isTrialing || entitlement?.status === "active"
+ );
+ };
const reverted = overview.trials
.filter(isRecentRevert)
.filter((trial) => !overview.entitlements[trial.productKey]?.trialPlan);
+ const unpaid = overview.trials.filter(isRecentUnpaidEnd).filter((trial) => !isSuperseded(trial));
- if (reverted.length === 0) {
+ if (!overview.trialPaymentDue && reverted.length === 0 && unpaid.length === 0) {
return null;
}
return (
<>
+ {overview.trialPaymentDue && (
+ <Alert variant="warning">
+ <CreditCard />
+ <AlertTitle>Complete your trial payment</AlertTitle>
+ <AlertDescription>
+ Your bank needs you to confirm this payment. Access continues until{" "}
+ {overview.trialPaymentDue.dueAt}.
+ {canAct && (
+ <div className="mt-3 flex flex-wrap gap-2">
+ <Button
+ variant="warning"
+ size="xs"
+ isPending={isCompletingTrialPayment}
+ onClick={onCompleteTrialPayment}
+ >
+ Complete payment
+ </Button>
+ </div>
+ )}
+ </AlertDescription>
+ </Alert>
+ )}
{reverted.map((trial) => {
const reason = trial.endedDetail ? REVERTED_REASON[trial.endedDetail] : undefined;
const catalogProduct = catalog.find((prod) => prod.id === trial.productKey);
@@ -83,7 +128,7 @@ export const TrialBanners = ({
</AlertTitle>
<AlertDescription>
{reason?.body ?? "Your trial ended."} You&apos;re still on {basePlan}.
- {overview.selfServe && !readOnly && (
+ {canAct && (
<div className="mt-3 flex flex-wrap gap-2">
{reason?.action === "payment" && (
<Button variant="outline" size="xs" onClick={onUpdatePayment}>
@@ -104,6 +149,27 @@ export const TrialBanners = ({
</Alert>
);
})}
+ {unpaid.map((trial) => (
+ <Alert key={`unpaid-${trial.productKey}-${trial.planTier ?? ""}`} variant="warning">
+ <CircleAlert />
+ <AlertTitle>
+ Your {planName(catalog, trial.productKey, trial.planTier)} trial ended
+ </AlertTitle>
+ <AlertDescription>
+ Trial ended because the payment was never completed.
+ {trial.basePlanTier && (
+ <> You&apos;re still on {planName(catalog, trial.productKey, trial.basePlanTier)}.</>
+ )}
+ {canAct && (
+ <div className="mt-3 flex flex-wrap gap-2">
+ <Button variant="ghost" size="xs" onClick={() => onManage(trial.productKey)}>
+ View plans
+ </Button>
+ </div>
+ )}
+ </AlertDescription>
+ </Alert>
+ ))}
</>
);
};
diff --git a/frontend/src/pages/organization/BillingV2Page/components/UpgradeView.tsx b/frontend/src/pages/organization/BillingV2Page/components/UpgradeView.tsx
index 670b7227a6..9fdbde2390 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/UpgradeView.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/UpgradeView.tsx
@@ -13,14 +13,21 @@ import {
} from "@app/components/v3";
import {
BillingV2CatalogProduct,
+ BillingV2ErrorCode,
BillingV2Plan,
usePreviewBillingV2Change,
useUpgradeBillingV2Product
} from "@app/hooks/api";
-import { fmtMoney } from "../billing-v2-format";
+import { billingV2ErrorCode, fmtMoney } from "../billing-v2-format";
import { ChargeBreakdown } from "./ChargeBreakdown";
-import { CostSummary, CostSummaryRow, ProductIcon } from "./shared";
+import {
+ CostSummary,
+ CostSummaryRow,
+ PaymentActionRequiredNotice,
+ PaymentApprovalNotice,
+ ProductIcon
+} from "./shared";
// The server rejects a proration date older than 15 minutes. Re-price before that so a sheet left
// open fails by refreshing the number rather than by throwing at the customer.
@@ -54,6 +61,8 @@ export const UpgradeView = ({
const preview = usePreviewBillingV2Change();
const upgrade = useUpgradeBillingV2Product();
const [pricedAt, setPricedAt] = useState(0);
+ const [paymentActionRequired, setPaymentActionRequired] = useState(false);
+ const [approvalUrl, setApprovalUrl] = useState<string | null>(null);
const { mutate: runPreview } = preview;
useEffect(() => {
@@ -84,6 +93,8 @@ export const UpgradeView = ({
});
const handleUpgrade = async () => {
+ setPaymentActionRequired(false);
+ setApprovalUrl(null);
let priced = preview.data;
if (Date.now() - pricedAt > PREVIEW_MAX_AGE_MS) {
const fresh = await rePreview();
@@ -113,20 +124,27 @@ export const UpgradeView = ({
}
try {
- await upgrade.mutateAsync({
+ const result = await upgrade.mutateAsync({
orgId,
productId: prod.id,
plan: plan.tier,
expectedPlanVersionId: priced.toPlanVersionId,
prorationDate: priced.prorationDate ?? undefined
});
+ if (result.outcome === "payment_action_required" && result.paymentUrl) {
+ setApprovalUrl(result.paymentUrl);
+ return;
+ }
createNotification({
type: "success",
text: `You're on ${plan.name}. It may take a moment to update here.`
});
onDone();
- } catch {
+ } catch (error) {
// The backend's message is surfaced by the global mutation error handler (reactQuery.tsx).
+ if (billingV2ErrorCode(error) === BillingV2ErrorCode.PaymentActionRequired) {
+ setPaymentActionRequired(true);
+ }
await rePreview();
}
};
@@ -200,6 +218,9 @@ export const UpgradeView = ({
totalDueNow={preview.data?.totalDueNow ?? 0}
/>
)}
+
+ {paymentActionRequired && <PaymentActionRequiredNotice orgId={orgId} />}
+ {approvalUrl && <PaymentApprovalNotice paymentUrl={approvalUrl} />}
</div>
<SheetFooter className="flex-row justify-between border-t">
diff --git a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
index c386aa4d94..bab1dea55d 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/cards/ProductsCard.tsx
@@ -80,6 +80,8 @@ const ActiveProductCard = ({
? (entitlement.trialPlanName ?? trialedPlan?.name ?? tierLabel(entitlement.trialPlan))
: null;
const trialDaysLeft = entitlement?.trialPlanDaysLeft;
+ // Past trialEndsAt but still usable: the conversion charge is waiting on the customer's bank.
+ const trialPaymentDueAt = entitlement?.trialPaymentDueAt;
// The headline figure steps down a size when a second amount line shares the block.
const priceLines = [annualCommitted > 0, monthlyRecurring > 0, onDemand > 0].filter(
@@ -97,7 +99,11 @@ const ActiveProductCard = ({
// Cadence and renewal (or trial) as one muted subline under the product name.
let subline: ReactNode = null;
- if (isTrialing) {
+ if (trialPaymentDueAt) {
+ subline = (
+ <span className="text-warning">Payment needed · access until {trialPaymentDueAt}</span>
+ );
+ } else if (isTrialing) {
subline = entitlement?.trialEndsAt ? (
<span>Trial ends {entitlement.trialEndsAt}</span>
) : (
@@ -166,7 +172,10 @@ const ActiveProductCard = ({
<Clock className="size-3.5 shrink-0 text-warning" />
Trialing {trialPlanName}
</span>
- {trialDaysLeft !== null && trialDaysLeft !== undefined && (
+ {trialPaymentDueAt && (
+ <span className="shrink-0 text-xs font-medium text-warning">Payment needed</span>
+ )}
+ {!trialPaymentDueAt && trialDaysLeft !== null && trialDaysLeft !== undefined && (
<span className="shrink-0 text-xs font-medium text-warning tabular-nums">
{trialDaysLeft === 0
? "Ends today"
@@ -175,8 +184,16 @@ const ActiveProductCard = ({
)}
</div>
<span className="text-[11px] text-muted">
- {entitlement?.trialPlanEndsAt ? `Trial ends ${entitlement.trialPlanEndsAt} · ` : ""}
- upgrades to {trialPlanName} automatically when it ends
+ {trialPaymentDueAt ? (
+ <>
+ Access until {trialPaymentDueAt} · confirm payment to upgrade to {trialPlanName}
+ </>
+ ) : (
+ <>
+ {entitlement?.trialPlanEndsAt ? `Trial ends ${entitlement.trialPlanEndsAt} · ` : ""}
+ upgrades to {trialPlanName} automatically when it ends
+ </>
+ )}
</span>
</div>
)}
diff --git a/frontend/src/pages/organization/BillingV2Page/components/shared.tsx b/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
index 51b34f4b73..5370f34c2d 100644
--- a/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
+++ b/frontend/src/pages/organization/BillingV2Page/components/shared.tsx
@@ -1,8 +1,11 @@
import { CSSProperties, Fragment, ReactNode, useState } from "react";
-import { Box, MinusIcon, PlusIcon } from "lucide-react";
+import { Box, ExternalLink, MinusIcon, PlusIcon, TriangleAlert } from "lucide-react";
import { DynamicIcon, type IconName } from "lucide-react/dynamic";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Badge,
Button,
Empty,
@@ -17,7 +20,11 @@ import {
Skeleton
} from "@app/components/v3";
import { cn } from "@app/components/v3/utils";
-import { BillingV2CatalogProduct, BillingV2EntitlementDim } from "@app/hooks/api";
+import {
+ BillingV2CatalogProduct,
+ BillingV2EntitlementDim,
+ useCreateBillingV2PortalSession
+} from "@app/hooks/api";
import {
dimBarSegments,
@@ -318,3 +325,57 @@ export const Stepper = ({ value, min = 0, max = 9999, onChange, isDisabled }: St
</div>
);
};
+
+// Shown when the bank declined or held a charge (payment_action_required). The change was not applied,
+// so the way forward is a different card from the billing portal and a retry.
+export const PaymentActionRequiredNotice = ({ orgId }: { orgId: string }) => {
+ const portalSession = useCreateBillingV2PortalSession();
+ return (
+ <Alert variant="warning">
+ <TriangleAlert />
+ <AlertTitle>Your bank didn&apos;t approve this charge</AlertTitle>
+ <AlertDescription>
+ Nothing was changed. Try a different card from the billing portal, then retry.
+ <div className="mt-3 flex flex-wrap gap-2">
+ <Button
+ variant="outline"
+ size="xs"
+ isPending={portalSession.isPending}
+ onClick={() =>
+ portalSession.mutate(
+ { orgId, returnPath: window.location.pathname },
+ {
+ onSuccess: (url) => {
+ window.location.href = url;
+ }
+ }
+ )
+ }
+ >
+ Open billing portal
+ </Button>
+ </div>
+ </AlertDescription>
+ </Alert>
+ );
+};
+
+export const PaymentApprovalNotice = ({ paymentUrl }: { paymentUrl: string }) => (
+ <Alert variant="warning">
+ <TriangleAlert />
+ <AlertTitle>Approve this payment with your bank</AlertTitle>
+ <AlertDescription>
+ Your bank needs you to confirm this charge. Approve it to finish the change.
+ <div className="mt-3 flex flex-wrap gap-2">
+ <Button
+ variant="warning"
+ size="xs"
+ onClick={() => window.open(paymentUrl, "_blank", "noopener,noreferrer")}
+ >
+ <ExternalLink />
+ Approve payment
+ </Button>
+ </div>
+ </AlertDescription>
+ </Alert>
+);