Skip to content

Open source CapCut alternative.

TypeScript

fix(site): charge what the plan cards show

David Le0d074e91bf97
diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.ts
index b81e5bbc..0c75c655 100644
--- a/site/src/app/api/billing/checkout/route.ts
+++ b/site/src/app/api/billing/checkout/route.ts
@@ -5,12 +5,19 @@ import { z } from "zod";
import { requestLocale } from "@/i18n/requestLocale";
import { auth } from "@/lib/auth";
import { introCouponId } from "@/lib/billing/intro-offer";
-import { chargeCurrency } from "@/lib/billing/charge-currency";
-import { CURRENCIES, DEFAULT_CURRENCY } from "@/lib/billing/currencies";
-import { introCoupon, readIntroOffer } from "@/lib/billing/intro-offer-server";
+import { chargeCurrency, currencyFor } from "@/lib/billing/charge-currency";
+import { CURRENCIES } from "@/lib/billing/currencies";
+import { introCoupon, openIntroOffer } from "@/lib/billing/intro-offer-server";
+import { ensureLocalPrice } from "@/lib/billing/local-price";
import { metaCheckoutMetadata, trackCheckoutStarted } from "@/lib/billing/meta-checkout";
-import { PAID_PLANS, PLAN_NAMES, planRank, type PaidPlan } from "@/lib/billing/plans";
-import { dropIntroDiscount, INTRO_OFFER_METADATA_KEY, liftScheduledCancel, upgradeKey } from "@/lib/billing/plan-upgrade";
+import { PAID_PLANS, PLAN_NAMES, planPrice, planRank, type PaidPlan, type PlanTermsTable } from "@/lib/billing/plans";
+import {
+ declinedUpgrade,
+ dropIntroDiscount,
+ INTRO_OFFER_METADATA_KEY,
+ liftScheduledCancel,
+ upgradeKey,
+} from "@/lib/billing/plan-upgrade";
import {
getActiveSubscription,
isActiveProStatus,
@@ -22,7 +29,7 @@ import {
import { STRIPE_LOCALE } from "@/lib/billing/stripe-locale";
import { drainStripe, ensureStripeCustomer, getStripe } from "@/lib/billing/stripe";
import { countryFromHeaders } from "@/lib/config/country";
-import { contextFromRequest } from "@/lib/config/effective";
+import { contextFromRequest, getGlobalSetting } from "@/lib/config/effective";
import { verifyCreditOfferToken } from "@/lib/credits/offers";
import { openOfferForSubscribing, SUBSCRIBE_BONUS_METADATA_KEY } from "@/lib/credits/subscribe-bonus-claim";
import {
@@ -33,10 +40,11 @@ import {
// The plan to buy, Pro when unnamed. A checkout opened from an offer's claim
// link names the offer by its token, so the credit that lands is the one the
-// dialog described. The currency is the one the surface priced the plan in.
+// dialog described. The currency is the one the surface priced the plan in;
+// a surface that showed no price sends none.
const bodySchema = z
.object({
- currency: z.enum(CURRENCIES).default(DEFAULT_CURRENCY),
+ currency: z.enum(CURRENCIES).optional(),
offerToken: z.string().min(1).optional(),
plan: z.enum(PAID_PLANS).optional(),
})
@@ -62,11 +70,11 @@ export const POST = withDonkeyAuth(async (request) => {
const plan = parsed.data.plan ?? "pro";
// The account checks out in one currency: the one Stripe already bills it
- // in, or its country's. A card priced in another, such as one drawn before
- // the account's pricing read landed, is refused, so the charge always
- // matches what the person saw and no account buys another country's price.
+ // in, or its country's. A card priced in another is refused, so the charge
+ // always matches what the person saw and no account buys another country's
+ // price.
const currency = await chargeCurrency(session.user.id, countryFromHeaders(request.headers));
- if (parsed.data.currency !== currency) {
+ if (parsed.data.currency && parsed.data.currency !== currency) {
return NextResponse.json(
{ error: "currency_changed", message: "Prices for your account changed. Check the new price and try again." },
{ status: HTTP_CONFLICT },
@@ -75,7 +83,7 @@ export const POST = withDonkeyAuth(async (request) => {
// A not-yet-configured price stays a 404 (not 401) so the landing card does
// not treat it as a sign-in prompt.
- const prices = await readPlanPrices();
+ const [prices, terms] = await Promise.all([readPlanPrices(), getGlobalSetting("planTerms")]);
const priceId = prices[plan];
if (!priceId) {
return notFoundResponse();
@@ -85,7 +93,7 @@ export const POST = withDonkeyAuth(async (request) => {
// would double-bill it.
const current = await getActiveSubscription(session.user.id);
if (current) {
- return upgradeInPlace(current.stripeSubscriptionId, plan, prices, request.nextUrl.origin);
+ return upgradeInPlace(current.stripeSubscriptionId, plan, prices, terms, request.nextUrl.origin);
}
const customerId = await ensureStripeCustomer({
@@ -98,19 +106,20 @@ export const POST = withDonkeyAuth(async (request) => {
// ago whose webhook is still on its way. That account moves up in place too.
const live = await adoptLiveSubscription(customerId);
if (live) {
- return upgradeInPlace(live, plan, prices, request.nextUrl.origin);
+ return upgradeInPlace(live, plan, prices, terms, request.nextUrl.origin);
}
await expireOpenCheckouts(customerId);
// A Pro checkout started while an offer for subscribing is open carries the
// offer, so the webhook lands the credit on the subscription it creates.
const offer = plan === "pro" ? await openOfferForSubscribing(session.user.id, namedOfferId) : null;
- // An account inside its intro window checks out of Pro with the discount
- // already on. Stripe takes either a discount or a promotion code field,
- // never both.
- const intro = plan === "pro" ? await readIntroOffer(await contextFromRequest(request)) : null;
+ // An account the intro offer is open to checks out of Pro with the
+ // discount already on, its window starting here if no surface started it.
+ // Stripe takes either a discount or a promotion code field, never both.
+ const intro = plan === "pro" ? await openIntroOffer(await contextFromRequest(request)) : null;
const pricing = intro
? { discounts: [{ coupon: await introCoupon(intro) }] }
: { allow_promotion_codes: true };
+ await ensureLocalPrice(priceId, planPrice(terms[plan], currency), currency);
const stripe = getStripe();
const origin = request.nextUrl.origin;
const checkout = await stripe.checkout.sessions.create({
@@ -145,9 +154,10 @@ export const POST = withDonkeyAuth(async (request) => {
});
// A plan subscription Stripe holds for the customer, synced to the account
-// so every surface reads it; null when the customer has none.
+// so every surface reads it; null when the customer has none. Stripe's list
+// leaves out canceled subscriptions, so the read skips the history.
async function adoptLiveSubscription(customerId: string): Promise<string | null> {
- const subscriptions = await drainStripe(getStripe().subscriptions.list({ customer: customerId, status: "all" }));
+ const subscriptions = await drainStripe(getStripe().subscriptions.list({ customer: customerId }));
for (const subscription of subscriptions) {
if (!isActiveProStatus(subscription.status)) {
continue;
@@ -184,6 +194,7 @@ async function upgradeInPlace(
subscriptionId: string | null,
plan: PaidPlan,
prices: PlanPrices,
+ terms: PlanTermsTable,
origin: string,
): Promise<Response> {
if (!subscriptionId) {
@@ -198,6 +209,11 @@ async function upgradeInPlace(
return notAnUpgrade();
}
+ // The subscription keeps the currency Stripe bills it in, so the new
+ // plan's price has to sell in it too.
+ const billed = currencyFor(subscription.currency, null);
+ await ensureLocalPrice(toPrice, planPrice(terms[plan], billed), billed);
+
let updated: Stripe.Subscription;
try {
updated = await stripe.subscriptions.update(
@@ -213,7 +229,10 @@ async function upgradeInPlace(
{ idempotencyKey: upgradeKey(subscription, line.item.price.id, toPrice) },
);
} catch (e) {
+ // A declined card leaves the old plan in place. The decline is recorded,
+ // so the retry after a card fix sends a fresh update.
if (e instanceof Stripe.errors.StripeCardError) {
+ await stripe.subscriptions.update(subscription.id, declinedUpgrade(subscription));
return NextResponse.json(
{ error: "upgrade_payment_failed", message: e.message },
{ status: HTTP_PAYMENT_REQUIRED },
diff --git a/site/src/app/api/billing/intro-offer/route.ts b/site/src/app/api/billing/intro-offer/route.ts
index 1438fb34..b57b51f8 100644
--- a/site/src/app/api/billing/intro-offer/route.ts
+++ b/site/src/app/api/billing/intro-offer/route.ts
@@ -7,7 +7,7 @@ import { withDonkeyAuth } from "@/lib/donkey-api-auth";
// The surface showing the intro offer POSTs here; the first POST starts the
// offer's window. It answers when the window ends, null when no offer is
// open. The app reads the offer itself from the pricing route, and checkout
-// reads the same offer and applies it.
+// opens the same offer and applies it.
export const POST = withDonkeyAuth(async (request) => {
const offer = await openIntroOffer(await contextFromRequest(request));
return NextResponse.json({ endsAt: offer?.endsAt.toISOString() ?? null });
diff --git a/site/src/lib/billing/charge-currency.ts b/site/src/lib/billing/charge-currency.ts
index 0da5a650..8a73c98f 100644
--- a/site/src/lib/billing/charge-currency.ts
+++ b/site/src/lib/billing/charge-currency.ts
@@ -19,11 +19,35 @@ export function currencyFor(billed: string | null, country: string | null): Curr
return billed;
}
+// Each customer's billed currency, once Stripe has one. Stripe never changes
+// it after that, so the read is kept for the life of the server and only a
+// customer not yet billed asks Stripe again. Bounded in entries; the oldest
+// goes first.
+const BILLED_CACHE_MAX = 10_000;
+const billedCurrency = new Map<string, string>();
+
+async function customerCurrency(customerId: string): Promise<string | null> {
+ const known = billedCurrency.get(customerId);
+ if (known) {
+ return known;
+ }
+
+ const customer = await getStripe().customers.retrieve(customerId);
+ const billed = customer.deleted ? null : customer.currency ?? null;
+ if (!billed) {
+ return null;
+ }
+ if (billedCurrency.size >= BILLED_CACHE_MAX) {
+ billedCurrency.delete(billedCurrency.keys().next().value!);
+ }
+ billedCurrency.set(customerId, billed);
+ return billed;
+}
+
export async function chargeCurrency(userId: string, country: string | null): Promise<Currency> {
const user = await prisma.user.findUnique({ where: { id: userId }, select: { stripeCustomerId: true } });
if (!user?.stripeCustomerId) {
return marketCurrency(country);
}
- const customer = await getStripe().customers.retrieve(user.stripeCustomerId);
- return currencyFor(customer.deleted ? null : customer.currency ?? null, country);
+ return currencyFor(await customerCurrency(user.stripeCustomerId), country);
}
diff --git a/site/src/lib/billing/intro-offer-server.ts b/site/src/lib/billing/intro-offer-server.ts
index cd87c598..a425fa96 100644
--- a/site/src/lib/billing/intro-offer-server.ts
+++ b/site/src/lib/billing/intro-offer-server.ts
@@ -16,16 +16,6 @@ async function introFacts(ctx: ConfigContext) {
return { setting, facts: { seenAt: view?.seenAt ?? null, heldPro: heldPro(subscription?.status ?? null) } };
}
-/** The intro offer open to this account right now, or null. Reading never
- * starts the window; checkout reads it this way. */
-export async function readIntroOffer(ctx: ConfigContext, now = new Date()): Promise<IntroOffer | null> {
- if (!ctx.hasAccount) {
- return null;
- }
- const { setting, facts } = await introFacts(ctx);
- return introOfferAt(setting, facts, now);
-}
-
/** The offer as the app loads it ahead of any surface, which never starts
* the window; see introOfferPreview. */
export async function previewIntroOffer(ctx: ConfigContext, now = new Date()) {
diff --git a/site/src/lib/billing/local-price.test.ts b/site/src/lib/billing/local-price.test.ts
new file mode 100644
index 00000000..de785fd5
--- /dev/null
+++ b/site/src/lib/billing/local-price.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test } from "bun:test";
+import type Stripe from "stripe";
+
+import { localPriceWrite } from "@/lib/billing/local-price";
+
+const price = (options: Record<string, number> = {}) =>
+ ({
+ currency: "usd",
+ currency_options: Object.fromEntries(Object.entries(options).map(([c, unit_amount]) => [c, { unit_amount }])),
+ id: "price_pro",
+ }) as unknown as Stripe.Price;
+
+describe("localPriceWrite", () => {
+ test("a price without the currency gets it at the terms' amount", () => {
+ expect(localPriceWrite(price(), 2_800, "jpy")).toEqual({ currency_options: { jpy: { unit_amount: 2_800 } } });
+ expect(localPriceWrite(price(), 59, "brl")).toEqual({ currency_options: { brl: { unit_amount: 5_900 } } });
+ });
+
+ test("a price already selling the amount needs nothing", () => {
+ expect(localPriceWrite(price({ brl: 5_900 }), 59, "brl")).toBeNull();
+ });
+
+ test("USD sells at the price's own amount", () => {
+ expect(localPriceWrite(price(), 20, "usd")).toBeNull();
+ });
+
+ test("a price holding another amount is refused", () => {
+ expect(() => localPriceWrite(price({ brl: 4_900 }), 59, "brl")).toThrow();
+ });
+});
diff --git a/site/src/lib/billing/local-price.ts b/site/src/lib/billing/local-price.ts
new file mode 100644
index 00000000..e97f5026
--- /dev/null
+++ b/site/src/lib/billing/local-price.ts
@@ -0,0 +1,48 @@
+import type Stripe from "stripe";
+
+import { DEFAULT_CURRENCY, fromMinor, toMinor, type Currency } from "@/lib/billing/currencies";
+import { getStripe } from "@/lib/billing/stripe";
+
+// A plan sells in a local currency through its Stripe price's currency
+// options. su adds them when it saves the terms; a checkout in a currency
+// the price still lacks adds that one first, so a price the card showed
+// from the terms' defaults always reaches Stripe.
+
+/** The currency option a price needs to sell at `amount` in `currency`, or
+ * null when it already does. Stripe never changes an option's amount, so a
+ * price holding another one is refused. The price is read with
+ * expand: ["currency_options"]. */
+export function localPriceWrite(
+ price: Stripe.Price,
+ amount: number,
+ currency: Currency,
+): Pick<Stripe.PriceUpdateParams, "currency_options"> | null {
+ if (currency === price.currency) {
+ return null;
+ }
+
+ const minor = toMinor(amount, currency);
+ const held = price.currency_options?.[currency]?.unit_amount;
+ if (held === undefined || held === null) {
+ return { currency_options: { [currency]: { unit_amount: minor } } };
+ }
+ if (held !== minor) {
+ throw new Error(
+ `Price ${price.id} charges ${fromMinor(held, currency)} ${currency.toUpperCase()}, the terms say ${amount}`,
+ );
+ }
+ return null;
+}
+
+/** Make a plan's Stripe price sell at `amount` in `currency`. */
+export async function ensureLocalPrice(priceId: string, amount: number, currency: Currency): Promise<void> {
+ if (currency === DEFAULT_CURRENCY) {
+ return;
+ }
+ const stripe = getStripe();
+ const price = await stripe.prices.retrieve(priceId, { expand: ["currency_options"] });
+ const write = localPriceWrite(price, amount, currency);
+ if (write) {
+ await stripe.prices.update(priceId, write);
+ }
+}
diff --git a/site/src/lib/billing/plan-upgrade.test.ts b/site/src/lib/billing/plan-upgrade.test.ts
index 4201732a..0340e995 100644
--- a/site/src/lib/billing/plan-upgrade.test.ts
+++ b/site/src/lib/billing/plan-upgrade.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from "bun:test";
import type Stripe from "stripe";
-import { dropIntroDiscount, liftScheduledCancel, upgradeKey } from "@/lib/billing/plan-upgrade";
+import { declinedUpgrade, dropIntroDiscount, liftScheduledCancel, upgradeKey } from "@/lib/billing/plan-upgrade";
const INTRO = "donkey-intro-50-3m";
@@ -69,4 +69,13 @@ describe("upgradeKey", () => {
upgradeKey(subscription(), "price_plus", "price_max"),
);
});
+
+ test("a declined attempt gives the retry a new key", () => {
+ const declined = subscription(declinedUpgrade(subscription()));
+ expect(upgradeKey(declined, "price_plus", "price_max")).not.toBe(
+ upgradeKey(subscription(), "price_plus", "price_max"),
+ );
+ const again = subscription(declinedUpgrade(declined));
+ expect(upgradeKey(again, "price_plus", "price_max")).not.toBe(upgradeKey(declined, "price_plus", "price_max"));
+ });
});
diff --git a/site/src/lib/billing/plan-upgrade.ts b/site/src/lib/billing/plan-upgrade.ts
index d7ca28f0..4133ea35 100644
--- a/site/src/lib/billing/plan-upgrade.ts
+++ b/site/src/lib/billing/plan-upgrade.ts
@@ -44,11 +44,25 @@ export function dropIntroDiscount(
return { discounts: kept.length ? kept.map((d) => ({ discount: d.id })) : "" };
}
+// The subscription metadata key counting declined upgrades. Stripe keeps a
+// declined request's answer under its idempotency key for a day, so each
+// decline moves the count and the retry after a card fix gets a fresh key.
+const UPGRADE_ATTEMPT_METADATA_KEY = "upgradeAttempt";
+
// One upgrade per subscription state. Two clicks that read the same
// subscription send one update; Stripe answers the second with the first's
-// result. The latest invoice moves with every upgrade, so a later move from
-// the same plan gets a fresh key.
+// result. The latest invoice moves with every upgrade and the attempt count
+// with every decline, so a later move from the same plan gets a fresh key.
export function upgradeKey(subscription: Stripe.Subscription, fromPrice: string, toPrice: string): string {
const invoice = stripeId(subscription.latest_invoice) ?? "none";
- return `plan-upgrade:${subscription.id}:${fromPrice}:${toPrice}:${invoice}`;
+ const attempt = subscription.metadata?.[UPGRADE_ATTEMPT_METADATA_KEY] ?? "0";
+ return `plan-upgrade:${subscription.id}:${fromPrice}:${toPrice}:${invoice}:${attempt}`;
+}
+
+/** The metadata write that records a declined upgrade, so the next one
+ * gets its own key. Stripe merges it into the metadata the subscription
+ * holds. */
+export function declinedUpgrade(subscription: Stripe.Subscription): { metadata: Record<string, string> } {
+ const attempt = Number(subscription.metadata?.[UPGRADE_ATTEMPT_METADATA_KEY] ?? "0") + 1;
+ return { metadata: { [UPGRADE_ATTEMPT_METADATA_KEY]: String(attempt) } };
}
diff --git a/site/src/queries/billing.ts b/site/src/queries/billing.ts
index c2bd1d69..854eea51 100644
--- a/site/src/queries/billing.ts
+++ b/site/src/queries/billing.ts
@@ -106,11 +106,15 @@ export function useIntroOffer({ enabled = true }: { enabled?: boolean } = {}): {
if (!unstarted) {
return;
}
- void apiFetch<{ endsAt: string | null }>(INTRO_OFFER_URL, { method: "POST" }).then(({ endsAt }) => {
- queryClient.setQueryData<PricingRead>(pricingQueryKey, (prev) =>
- prev?.intro ? { ...prev, intro: endsAt ? { ...prev.intro, endsAt } : null } : prev,
- );
- });
+ // A start that fails leaves the window to checkout, which opens the same
+ // offer, so the discount on screen is the one charged.
+ void apiFetch<{ endsAt: string | null }>(INTRO_OFFER_URL, { method: "POST" })
+ .then(({ endsAt }) => {
+ queryClient.setQueryData<PricingRead>(pricingQueryKey, (prev) =>
+ prev?.intro ? { ...prev, intro: endsAt ? { ...prev.intro, endsAt } : null } : prev,
+ );
+ })
+ .catch(() => {});
}, [unstarted, queryClient]);
if (!enabled) {
@@ -132,12 +136,13 @@ export function useIntroOffer({ enabled = true }: { enabled?: boolean } = {}): {
// claim link passes the offer's token, so the credit that lands is the one the
// dialog described. An account already on a plan moves up in place and comes
// back with the settings URL.
-// Every checkout names the currency its surface showed. The route refuses
-// one the account no longer checks out in, so a charge never differs from
-// the card.
+// Every checkout names the currency the account's pricing read gave its
+// surface. The route refuses one the account no longer checks out in, so a
+// charge never differs from the card; a checkout sent before that read
+// landed showed no price and names none.
export function useStartCheckout() {
const queryClient = useQueryClient();
- const { currency } = useAccountCurrency({ enabled: true });
+ const currency = usePricing().data?.currency;
return useMutation({
mutationFn: (input?: { plan?: PaidPlan; offerToken?: string } | void) =>
apiFetch<{ url: string }>("/api/billing/checkout", {