Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/billing-provider-from-env.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@codelitdev/billing": minor
---

Choose the payment provider and catalog from env settings, so a product switches between Dodo and Lemon Squeezy without code changes.

- `@codelitdev/billing/providers/env`: `readBillingProviderEnv(env, { offers })` reads `BILLING_PROVIDER`, the catalog revision, currency and each offer's amount and product ID, and checks each provider's credentials. It returns null when `BILLING_PROVIDER` is unset, and names the setting when one is missing or invalid.
- A provider other than the checkout one stays connected while its credentials are set, so its subscribers keep working after a switch.
- `createBillingProvidersFromEnv(providers, env, clock)` loads each adapter only when used. `dodoOptionsFromEnv` and `lemonSqueezyOptionsFromEnv` build the options alone.
39 changes: 39 additions & 0 deletions docs/decisions/0019-choose-billing-provider-by-settings.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# ADR 0019: Choose the billing provider by settings

Status: accepted
Date: 2026-11-17

## Context

The provider contract lets a product swap adapters, but each product parsed its
own env and called one adapter's constructor. Moving CourseLit from Dodo to
Lemon Squeezy, and back when Lemon Squeezy announced it is winding down, needed
code changes each time. MediaLit had already written env parsing that picks the
provider and keeps the old one connected for its subscribers.

## Decision

- Add `@codelitdev/billing/providers/env`, based on MediaLit's parsing:
`readBillingProviderEnv`, `createBillingProvidersFromEnv`,
`dodoOptionsFromEnv` and `lemonSqueezyOptionsFromEnv`.
- The functions take the env record as an argument. Core and adapters still
never read the process environment (invariant 2).
- Settings names are shared by every product: `BILLING_PROVIDER`,
`BILLING_CATALOG_REVISION`, `BILLING_CURRENCY`,
`BILLING_DATA_ENCRYPTION_KEY`, `BILLING_<OFFER>_AMOUNT_MINOR` and
`BILLING_<OFFER>_PRODUCT_ID`, plus each provider's credentials.
- New checkout goes to `BILLING_PROVIDER`. Any other provider whose
credentials are set stays connected, so its subscriptions keep receiving
webhooks and reconciliation.
- Offers always have `providerTrialDays: 0`. Trials are the product's own.
- Adapters are loaded with dynamic imports, so the optional `dodopayments` peer
is needed only by products that use Dodo.

## Consequences

- A product switches provider by changing settings and raising
`BILLING_CATALOG_REVISION`.
- Products should accept every connected provider on
`POST /webhooks/billing/:provider`.
- `createBillingProvidersFromEnv` is async, so engine composition that uses it
must be too.
2 changes: 1 addition & 1 deletion packages/billing/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Do not add `console.log` (Biome's console rule, `warn`/`error` allowed). Do not
| `src/schema/` | Canonical model + TS generator. |
| `src/cli/` | `generate` / `--check` only. No migrate command. |
| `src/adapters/drizzle/` | Store, `withTransaction`, `getTransaction()`, `noteProviderCall`. Only place that imports drizzle-orm. |
| `src/providers/` | Contract, registry, fake, Dodo. Dodo must not read `process.env` or emit `sendlit*` metadata. |
| `src/providers/` | Contract, registry, fake, Dodo, Lemon Squeezy, and `env/` (choose the provider from an env record passed in). None of them read `process.env`; Dodo must not emit `sendlit*` metadata. |
| `src/workflows/engine.ts` | All cross-boundary workflows in one module (`createBilling`). Experimental. |
| `src/operations/` | Operator inspect/retry/reconcile/cancel/decrypt. Requires `OperatorContext`. |
| `src/ports/` | Audit, authorization grant, lifecycle hooks, sensitive values, telemetry. |
Expand Down
37 changes: 37 additions & 0 deletions packages/billing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ Public imports (do not import `src/`):
| `@codelitdev/billing/providers` | Registry, fake, contract types |
| `@codelitdev/billing/providers/dodo` | `createDodoBillingProvider` |
| `@codelitdev/billing/providers/lemonsqueezy` | `createLemonSqueezyBillingProvider` |
| `@codelitdev/billing/providers/env` | Choose the provider and catalog from env settings |
| `@codelitdev/billing/core` | Statuses, money, errors, clock |
| `@codelitdev/billing/catalog` | Offer validation / public catalog |
| `@codelitdev/billing/testing` | Provider contract + workflow harness |
Expand Down Expand Up @@ -175,6 +176,42 @@ When several products share one Dodo business, Dodo sends every event to every w

To sell through Lemon Squeezy instead, compose `createLemonSqueezyBillingProvider` from `@codelitdev/billing/providers/lemonsqueezy` with `apiKey`, the product's `storeId`, and the store webhook's `webhookSecrets`, and set `checkoutProvider: "lemonsqueezy"`. Catalog offers name Lemon Squeezy variant IDs as `providerProductId`. Webhooks from other stores are stored as `ignored`. Trials come from the variant, so checkout rejects `trialDays`; plan changes apply immediately, and `do_not_bill` is refused for a change to another interval because Lemon Squeezy bills that at once. Turn off plan changes in the store's customer portal settings: the engine quarantines a plan change it did not start, along with that subscription's later webhooks.

### Choosing the provider by settings

`@codelitdev/billing/providers/env` lets a product change provider by changing settings, without code changes. The app passes its env record; the package does not read the process environment.

```ts
import {
createBillingProvidersFromEnv,
readBillingProviderEnv,
} from "@codelitdev/billing/providers/env";

const config = readBillingProviderEnv(process.env, {
offers: [
{ key: "pro_month", plan: "pro", interval: "month" },
{ key: "pro_year", plan: "pro", interval: "year" },
],
});
// null when BILLING_PROVIDER is unset, e.g. a fake provider in development.
const providers = config
? await createBillingProvidersFromEnv(config.providers, process.env, clock)
: [];
// createBilling({ providers, checkoutProvider: config.checkoutProvider,
// requestedRevision: config.revision, offers: config.offers, ... })
```

| Setting | Meaning |
| --- | --- |
| `BILLING_PROVIDER` | `dodo` or `lemonsqueezy`: where new checkout goes |
| `BILLING_CATALOG_REVISION` | Raise it whenever prices, product IDs or the provider change |
| `BILLING_CURRENCY` | Three-letter code |
| `BILLING_DATA_ENCRYPTION_KEY` | Required here so a missing key fails at startup |
| `BILLING_<OFFER>_AMOUNT_MINOR`, `BILLING_<OFFER>_PRODUCT_ID` | Per offer; `pro_month` reads `BILLING_PRO_MONTH_*`. A Dodo product ID or a Lemon Squeezy variant ID |
| `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY_CURRENT` | Dodo credentials. Optional: `DODO_PAYMENTS_ENVIRONMENT` (`test_mode` by default), `DODO_PAYMENTS_WEBHOOK_KEY_PREVIOUS`, `DODO_BRAND_ID` |
| `LEMONSQUEEZY_API_KEY`, `LEMONSQUEEZY_STORE_ID`, `LEMONSQUEEZY_WEBHOOK_SECRET` | Lemon Squeezy credentials. Optional: `LEMONSQUEEZY_WEBHOOK_SECRET_PREVIOUS` |

A provider other than `BILLING_PROVIDER` stays connected while its credentials are set, so its existing subscribers keep receiving webhooks after a switch; set all of its credentials or none. Accept every name in `config.providers` on `POST /webhooks/billing/:provider`. Provider products must have no trial: offers always carry `providerTrialDays: 0`. Each adapter loads only when used, so `dodopayments` is needed only with Dodo.

```ts
import { systemClock } from "@codelitdev/billing/core";
import { createDrizzleBillingStore } from "@codelitdev/billing/drizzle";
Expand Down
5 changes: 5 additions & 0 deletions packages/billing/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@
"import": "./dist/providers/dodo/index.js",
"default": "./dist/providers/dodo/index.js"
},
"./providers/env": {
"types": "./dist/providers/env/index.d.ts",
"import": "./dist/providers/env/index.js",
"default": "./dist/providers/env/index.js"
},
"./providers/lemonsqueezy": {
"types": "./dist/providers/lemonsqueezy/index.d.ts",
"import": "./dist/providers/lemonsqueezy/index.js",
Expand Down
1 change: 1 addition & 0 deletions packages/billing/src/exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ describe("public exports", () => {
"./operations",
"./providers",
"./providers/dodo",
"./providers/env",
"./providers/lemonsqueezy",
"./testing",
];
Expand Down
174 changes: 174 additions & 0 deletions packages/billing/src/providers/env/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { describe, expect, it } from "bun:test";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { systemClock } from "../../core/clock.js";
import {
type BillingEnv,
createBillingProvidersFromEnv,
dodoOptionsFromEnv,
lemonSqueezyOptionsFromEnv,
readBillingProviderEnv,
} from "./index.js";

const OFFERS = [
{ key: "pro_month", plan: "pro", interval: "month" },
{ key: "pro_year", plan: "pro", interval: "year" },
] as const;

const LEMONSQUEEZY: BillingEnv = {
LEMONSQUEEZY_API_KEY: "ls-key",
LEMONSQUEEZY_STORE_ID: "4242",
LEMONSQUEEZY_WEBHOOK_SECRET: "ls-secret",
};
const DODO: BillingEnv = {
DODO_PAYMENTS_API_KEY: "dodo-key",
DODO_PAYMENTS_WEBHOOK_KEY_CURRENT: "whsec_current",
};

function env(provider: string, overrides: BillingEnv = {}): BillingEnv {
const dodo = provider === "dodo";
return {
BILLING_PROVIDER: provider,
BILLING_CATALOG_REVISION: "3",
BILLING_CURRENCY: "usd",
BILLING_DATA_ENCRYPTION_KEY: "test-encryption-key",
BILLING_PRO_MONTH_AMOUNT_MINOR: "1900",
BILLING_PRO_YEAR_AMOUNT_MINOR: "19000",
BILLING_PRO_MONTH_PRODUCT_ID: dodo ? "pdt_month" : "1001",
BILLING_PRO_YEAR_PRODUCT_ID: dodo ? "pdt_year" : "1002",
...(dodo ? DODO : LEMONSQUEEZY),
...overrides,
};
}

const read = (values: BillingEnv) => readBillingProviderEnv(values, { offers: OFFERS });

describe("readBillingProviderEnv", () => {
it("returns null without BILLING_PROVIDER", () => {
expect(read({})).toBeNull();
expect(read({ BILLING_PROVIDER: " " })).toBeNull();
});

it("builds the catalog for the checkout provider", () => {
for (const provider of ["dodo", "lemonsqueezy"] as const) {
const config = read(env(provider));
expect(config?.checkoutProvider).toBe(provider);
expect(config?.providers).toEqual([provider]);
expect(config?.revision).toBe(3);
expect(config?.currency).toBe("USD");
expect(config?.offers[0]).toEqual({
key: "pro_month",
revision: 3,
plan: "pro",
interval: "month",
currency: "USD",
amountMinor: 1900,
provider,
providerProductId: provider === "dodo" ? "pdt_month" : "1001",
providerTrialDays: 0,
});
}
});

it("switches provider by settings alone and keeps the old one connected", () => {
const config = read(env("dodo", LEMONSQUEEZY));
expect(config?.checkoutProvider).toBe("dodo");
expect(config?.providers).toEqual(["dodo", "lemonsqueezy"]);
expect(config?.offers.every((offer) => offer.provider === "dodo")).toBe(true);
});

it("rejects an unknown provider", () => {
expect(() => read(env("stripe"))).toThrow("BILLING_PROVIDER_invalid");
});

it("names a missing setting", () => {
expect(() => read(env("dodo", { DODO_PAYMENTS_API_KEY: "" }))).toThrow(
"DODO_PAYMENTS_API_KEY_required",
);
expect(() =>
read(env("lemonsqueezy", { BILLING_PRO_YEAR_AMOUNT_MINOR: undefined })),
).toThrow("BILLING_PRO_YEAR_AMOUNT_MINOR_required");
expect(() => read(env("dodo", { BILLING_DATA_ENCRYPTION_KEY: "" }))).toThrow(
"BILLING_DATA_ENCRYPTION_KEY_required",
);
});

it("refuses a partly configured second provider", () => {
expect(() => read(env("dodo", { LEMONSQUEEZY_API_KEY: "ls-key" }))).toThrow(
"LEMONSQUEEZY_STORE_ID_required",
);
});

it("validates amounts, revision, currency and product ids", () => {
expect(() =>
read(env("dodo", { BILLING_PRO_MONTH_AMOUNT_MINOR: "19.00" })),
).toThrow("BILLING_PRO_MONTH_AMOUNT_MINOR_invalid");
expect(() => read(env("dodo", { BILLING_CATALOG_REVISION: "0" }))).toThrow(
"BILLING_CATALOG_REVISION_invalid",
);
expect(() => read(env("dodo", { BILLING_CURRENCY: "dollars" }))).toThrow(
"BILLING_CURRENCY_invalid",
);
expect(() =>
read(env("lemonsqueezy", { BILLING_PRO_MONTH_PRODUCT_ID: "pdt_month" })),
).toThrow("BILLING_PRO_MONTH_PRODUCT_ID_invalid");
expect(() =>
read(env("dodo", { BILLING_PRO_YEAR_PRODUCT_ID: "pdt_month" })),
).toThrow("BILLING_PRODUCT_IDS_must_be_unique");
});
});

describe("provider options", () => {
it("reads Dodo options with rotation and brand", () => {
const options = dodoOptionsFromEnv(
{
...DODO,
DODO_PAYMENTS_ENVIRONMENT: "live_mode",
DODO_PAYMENTS_WEBHOOK_KEY_PREVIOUS: "whsec_old",
DODO_BRAND_ID: "brnd_1",
},
systemClock,
);
expect(options.environment).toBe("live_mode");
expect(options.brandId).toBe("brnd_1");
expect(options.webhookSecrets.map((entry) => entry.version)).toEqual([
"current",
"previous",
]);
expect(dodoOptionsFromEnv(DODO, systemClock).environment).toBe("test_mode");
expect(() =>
dodoOptionsFromEnv({ ...DODO, DODO_PAYMENTS_ENVIRONMENT: "prod" }, systemClock),
).toThrow("DODO_PAYMENTS_ENVIRONMENT_invalid");
});

it("reads Lemon Squeezy options", () => {
const options = lemonSqueezyOptionsFromEnv(LEMONSQUEEZY, systemClock);
expect(options.storeId).toBe("4242");
expect(options.webhookSecrets).toEqual([
{ version: "current", secret: "ls-secret" },
]);
});
});

describe("createBillingProvidersFromEnv", () => {
it("creates each connected adapter, checkout provider first", async () => {
const adapters = await createBillingProvidersFromEnv(
["dodo", "lemonsqueezy"],
{ ...DODO, ...LEMONSQUEEZY },
systemClock,
);
expect(adapters.map((adapter) => adapter.provider)).toEqual([
"dodo",
"lemonsqueezy",
]);
});

it("does not read process.env or import the Dodo SDK statically", async () => {
const dir = path.dirname(fileURLToPath(import.meta.url));
const source = await readFile(path.join(dir, "index.ts"), "utf8");
expect(source).not.toMatch(/process\.env/);
expect(source).not.toMatch(/from "dodopayments"/);
expect(source).not.toMatch(/^import .*\/dodo\/index\.js/m);
});
});
Loading
Loading