Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

♻️ Always send the pay wall currency, retry without it on a currency conflict

Luke Vella798ab931523d
diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.ts
index 581f67c3c..b0e6b5e4c 100644
--- a/apps/web/src/features/billing/actions.ts
+++ b/apps/web/src/features/billing/actions.ts
@@ -27,7 +27,7 @@ import { getStripe } from "@/features/billing/service";
import {
canChangeBillingInterval,
isEarlySupporter,
- resolveCheckoutCurrency,
+ isStripeCurrencyConflictError,
resolvePriceSet,
} from "@/features/billing/utils";
import { getActiveSpaceForUser } from "@/features/space/data";
@@ -90,12 +90,8 @@ export const upgradeToProAction = authActionClient
const stripe = getStripe();
let customerId = ctx.user.customerId;
- let customerCurrency: string | null = null;
- if (customerId) {
- const customer = await stripe.customers.retrieve(customerId);
- customerCurrency = customer.deleted ? null : (customer.currency ?? null);
- } else {
+ if (!customerId) {
const customer = await stripe.customers.create(
{
email: ctx.user.email,
@@ -120,60 +116,66 @@ export const upgradeToProAction = authActionClient
nonprofitGrantedAt ? await ensureNonprofitCoupon() : null,
);
- const checkoutCurrency = resolveCheckoutCurrency({
- requestedCurrency: currency,
- customerCurrency,
- });
-
- const checkoutSession = await stripe.checkout.sessions.create({
- success_url: absoluteUrl(returnPath ?? "/settings/billing"),
- cancel_url: absoluteUrl(returnPath ?? "/settings/billing"),
- customer: customerId,
- customer_update: {
- name: "auto",
- address: "auto",
- },
- mode: "subscription",
- // Pin the pay wall currency so the subscription and invoices match it.
- // Adaptive Pricing may still present a local amount, with this currency
- // as the alternative. A customer who already has a currency keeps it:
- // Stripe rejects a hint that disagrees with it.
- currency: checkoutCurrency,
- ...discount.session,
- billing_address_collection: "auto",
- tax_id_collection: {
- enabled: true,
- },
- metadata: {
- userId: ctx.user.id,
- spaceId: space.id,
- } satisfies SubscriptionCheckoutMetadata,
- subscription_data: {
+ const createCheckoutSession = (checkoutCurrency?: string) =>
+ stripe.checkout.sessions.create({
+ success_url: absoluteUrl(returnPath ?? "/settings/billing"),
+ cancel_url: absoluteUrl(returnPath ?? "/settings/billing"),
+ customer: customerId,
+ customer_update: {
+ name: "auto",
+ address: "auto",
+ },
+ mode: "subscription",
+ // Pin the pay wall currency so the subscription and invoices match it.
+ // Adaptive Pricing may still present a local amount, with this currency
+ // as the alternative.
+ currency: checkoutCurrency,
+ ...discount.session,
+ billing_address_collection: "auto",
+ tax_id_collection: {
+ enabled: true,
+ },
metadata: {
userId: ctx.user.id,
spaceId: space.id,
- } satisfies SubscriptionMetadata,
- },
- line_items: [
- {
- price:
- period === "yearly"
- ? proPricingData.yearly.id
- : proPricingData.monthly.id,
- quantity: 1,
+ } satisfies SubscriptionCheckoutMetadata,
+ subscription_data: {
+ metadata: {
+ userId: ctx.user.id,
+ spaceId: space.id,
+ } satisfies SubscriptionMetadata,
},
- ],
- automatic_tax: {
- enabled: true,
- },
- expires_at: Math.floor(Date.now() / 1000) + 30 * 60, // 30 minutes
- after_expiration: {
- recovery: {
+ line_items: [
+ {
+ price:
+ period === "yearly"
+ ? proPricingData.yearly.id
+ : proPricingData.monthly.id,
+ quantity: 1,
+ },
+ ],
+ automatic_tax: {
enabled: true,
- ...discount.recovery,
},
+ expires_at: Math.floor(Date.now() / 1000) + 30 * 60, // 30 minutes
+ after_expiration: {
+ recovery: {
+ enabled: true,
+ ...discount.recovery,
+ },
+ },
+ });
+
+ // A customer with something still open in another currency (e.g. a
+ // subscription for another space) must stay in that currency.
+ const checkoutSession = await createCheckoutSession(currency).catch(
+ (error: unknown) => {
+ if (currency && isStripeCurrencyConflictError(error)) {
+ return createCheckoutSession();
+ }
+ throw error;
},
- });
+ );
if (!checkoutSession.url) {
throw new AppError({
diff --git a/apps/web/src/features/billing/utils.test.ts b/apps/web/src/features/billing/utils.test.ts
index 6557bceb2..133b3b0f2 100644
--- a/apps/web/src/features/billing/utils.test.ts
+++ b/apps/web/src/features/billing/utils.test.ts
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
formatMinorUnitAmount,
isEarlySupporter,
- resolveCheckoutCurrency,
+ isStripeCurrencyConflictError,
resolvePriceSet,
} from "./utils";
@@ -123,27 +123,30 @@ describe("formatMinorUnitAmount", () => {
});
});
-describe("resolveCheckoutCurrency", () => {
- it("pins the requested currency for a customer with no currency yet", () => {
+describe("isStripeCurrencyConflictError", () => {
+ it("matches an invalid request on the currency param", () => {
expect(
- resolveCheckoutCurrency({
- requestedCurrency: "eur",
- customerCurrency: null,
+ isStripeCurrencyConflictError({
+ rawType: "invalid_request_error",
+ param: "currency",
}),
- ).toBe("eur");
- expect(resolveCheckoutCurrency({ requestedCurrency: "eur" })).toBe("eur");
+ ).toBe(true);
});
- it("omits the hint for a customer who already has a currency", () => {
+ it("ignores other invalid requests and other errors", () => {
expect(
- resolveCheckoutCurrency({
- requestedCurrency: "eur",
- customerCurrency: "usd",
+ isStripeCurrencyConflictError({
+ rawType: "invalid_request_error",
+ param: "line_items",
}),
- ).toBeUndefined();
- });
-
- it("omits the hint when none was requested", () => {
- expect(resolveCheckoutCurrency({ customerCurrency: null })).toBeUndefined();
+ ).toBe(false);
+ expect(
+ isStripeCurrencyConflictError({
+ rawType: "api_error",
+ param: "currency",
+ }),
+ ).toBe(false);
+ expect(isStripeCurrencyConflictError(new Error("boom"))).toBe(false);
+ expect(isStripeCurrencyConflictError(null)).toBe(false);
});
});
diff --git a/apps/web/src/features/billing/utils.ts b/apps/web/src/features/billing/utils.ts
index 878c44c55..9217b0653 100644
--- a/apps/web/src/features/billing/utils.ts
+++ b/apps/web/src/features/billing/utils.ts
@@ -29,18 +29,17 @@ export function isStripeResourceMissingError(error: unknown) {
}
/**
- * The currency to pin a checkout session to. Stripe rejects a hint that
- * disagrees with a customer's existing currency, so a customer who has
- * already been billed keeps theirs and gets no hint.
+ * Stripe refuses a checkout currency that conflicts with something the
+ * customer still has open in another currency (an active subscription, a
+ * balance, a customer discount).
*/
-export function resolveCheckoutCurrency({
- requestedCurrency,
- customerCurrency,
-}: {
- requestedCurrency?: string;
- customerCurrency?: string | null;
-}) {
- return customerCurrency ? undefined : requestedCurrency;
+export function isStripeCurrencyConflictError(error: unknown) {
+ return (
+ typeof error === "object" &&
+ error !== null &&
+ (error as { rawType?: unknown }).rawType === "invalid_request_error" &&
+ (error as { param?: unknown }).param === "currency"
+ );
}
type PricingLike = Pick<PricingData, "monthly" | "yearly" | "earlySupporter">;