# Billing provider adapters

Status on 2026-11-25: library only. `convex/billingProviders.ts` is a tested adapter for an agency's own Stripe or Whop account. It has no tables, no routes and no screens yet, so nothing in the app charges anyone. Requests and webhooks are covered by fixtures in `tests/billing-providers.test.ts`. No real Stripe or Whop call has been made, and no live or sandbox account has been used.

The purpose is to let an agency charge its clients a monthly subscription, with an optional free trial, using keys the agency owns.

## What the module does

It runs in the Convex default runtime with `fetch` and Web Crypto. It adds no dependency and uses no provider SDK. Every function that calls a provider takes an optional `fetcher` as its last argument so tests can replace the network.

```ts
type BillingProvider = "stripe" | "whop";
type BillingFetcher = (url: string, init: { method: string; headers: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<Response>;

validateCredentials(
  input: { provider; secretKey: string; sandbox?: boolean },
  fetcher?: BillingFetcher,
): Promise<{ ok: boolean; accountLabel?: string; accountId?: string; mode?: "test" | "live"; detail?: string; uncertain?: boolean }>

createCheckout(
  input: { provider; secretKey; planRef; trialDays?; customerEmail?; reference; successUrl; cancelUrl; idempotencyKey?; sandbox?; accountId? },
  fetcher?: BillingFetcher,
): Promise<{ url: string; sessionId?: string; trialIgnored?: boolean }>

verifyWebhook(
  input: { provider; secret; rawBody: string; headers: Headers | Record<string, string | undefined | null>; toleranceSeconds?: number; now?: number },
): Promise<boolean>

parseEvent(input: { provider; rawBody: string }): BillingEvent

createPortalLink(
  input: { provider; secretKey; customerId; returnUrl; subscriptionId?; sandbox? },
  fetcher?: BillingFetcher,
): Promise<{ url: string | null; reason?: string }>

eventDedupeKey(provider, event: { id: string }): string   // "stripe:evt_..." or "whop:msg_..."
```

```ts
type BillingEvent = {
  id: string;                 // stable provider event id
  type: "checkout.completed" | "subscription.trialing" | "subscription.active"
      | "subscription.past_due" | "subscription.canceled" | "ignored";
  providerType: string;       // the provider's own event name
  occurredAt?: number;        // epoch ms
  reference?: string;
  customerId?: string;
  subscriptionId?: string;
  customerEmail?: string;
  planRef?: string;
  trialEndsAt?: number;       // epoch ms
  currentPeriodEnd?: number;  // epoch ms
  cancelAtPeriodEnd?: boolean;
};
```

`providerType`, `occurredAt` and `cancelAtPeriodEnd` are additions to the requested shape. `occurredAt` matters because neither provider guarantees delivery order.

### Failures

`createCheckout` and `createPortalLink` throw `BillingError` with `kind`, `provider`, `status`, `code` and `retryAfterMs`.

- `definite`: the provider answered and refused (any 4xx except 408), or the input was rejected before a request was made. Nothing happened.
- `uncertain`: there is no trustworthy answer. That covers a network error, a timeout (20 seconds), HTTP 408, any 5xx, a body that is not JSON, and a success response without the expected URL. For a write, the provider may have acted.

Do not retry an uncertain write automatically. `createCheckout` sends an `Idempotency-Key` on both providers. By default it is a SHA-256 hash of the provider, plan, trial, email, reference and URLs, so a deliberate retry of the same request returns the same checkout instead of creating a second one. Both providers keep keys for 24 hours and reject the same key with a different request. Pass `idempotencyKey` to control it.

`validateCredentials` does not throw for a provider answer. `ok: false` with `uncertain: true` means the provider could not be reached, so the key is not proven bad. HTTP 403 is reported as `ok: true` with a `detail`, because a restricted key can be valid without permission to read the account name.

Messages never contain a key. Provider error text is passed through for 4xx responses after anything shaped like a key is replaced with `[redacted]`.

## Stripe

Checked on 2026-11-25 against:

- [Create a Checkout Session](https://docs.stripe.com/api/checkout/sessions/create), which showed `Stripe-Version: 2026-11-18.endive`
- [The Subscription object](https://docs.stripe.com/api/subscriptions/object)
- [Manage webhook endpoints](https://docs.stripe.com/events/manage-webhook-endpoints), for the `Stripe-Signature` header entries and the duplicate-event guidance

Used from prior knowledge and not re-read on the check date: [Check webhook signatures](https://docs.stripe.com/webhooks#verify-manually), [Create a portal session](https://docs.stripe.com/api/customer_portal/sessions/create), [Retrieve account](https://docs.stripe.com/api/accounts/retrieve), [Idempotent requests](https://docs.stripe.com/api/idempotent_requests), [Subscription webhooks](https://docs.stripe.com/billing/subscriptions/webhooks).

| Function | Request |
| --- | --- |
| `validateCredentials` | `GET https://api.stripe.com/v1/account` with `Authorization: Bearer <key>`. Label is `settings.dashboard.display_name`, then `business_profile.name`, `email`, `id`. `mode` comes from the key prefix. |
| `createCheckout` | `POST /v1/checkout/sessions`, form encoded: `mode=subscription`, `line_items[0][price]=<planRef>`, `line_items[0][quantity]=1`, `client_reference_id=<reference>`, `metadata[reference]`, `subscription_data[metadata][reference]`, `subscription_data[trial_period_days]` when `trialDays` is 1 or more, `customer_email` when given, `success_url`, `cancel_url`. Returns `url` and the session `id`. |
| `createPortalLink` | `POST /v1/billing_portal/sessions`, form encoded: `customer`, `return_url`. Returns `url`. |

Keys must start with `sk_live_`, `sk_test_`, `rk_live_` or `rk_test_`. `planRef` is a recurring price id. `reference` is limited to 200 characters, which is Stripe's documented limit for `client_reference_id`.

Webhook verification: the `Stripe-Signature` header carries `t=<unix seconds>` and one or more `v1=<hex>` entries. The module computes HMAC-SHA256 of `<t>.<raw body>` with the endpoint signing secret (`whsec_...`, used as text), accepts any matching `v1`, ignores `v0` and other entries, and rejects a timestamp more than 300 seconds from now in either direction.

| Stripe event | Normalized type |
| --- | --- |
| `checkout.session.completed` with `mode: subscription` | `checkout.completed`. `reference` from `client_reference_id`, `customerId`, `subscriptionId`, `customerEmail` from `customer_details.email`. No `planRef` or dates, because the session payload does not carry them. |
| `customer.subscription.created`, `.updated`, `.paused`, `.resumed` | By `status`: `trialing` to `subscription.trialing`; `active` to `subscription.active`; `past_due`, `unpaid`, `paused` to `subscription.past_due`; `canceled`, `incomplete_expired` to `subscription.canceled`; `incomplete` to `ignored`. |
| `customer.subscription.deleted` | `subscription.canceled` |
| `invoice.payment_failed` with `billing_reason: subscription_cycle` | `subscription.past_due` |
| Everything else, including `checkout.session.completed` in another mode and a failed first invoice | `ignored` |

Subscription events carry `reference` (from subscription metadata), `planRef` (first item's price id), `trialEndsAt`, `currentPeriodEnd` and `cancelAtPeriodEnd`. `currentPeriodEnd` is read from the subscription and, when absent, from the first subscription item, because current API versions report the period per item.

### Dashboard steps for an agency

1. In Stripe, open Product catalog and create a product with a recurring monthly price. Copy the price id (`price_...`).
2. Open Developers, then API keys. Create a restricted key with write access to Checkout Sessions and Customer portal, and read access to Subscriptions and Customers. A standard secret key also works. Copy it once.
3. Open Settings, then Billing, then Customer portal. Turn on the portal and choose what clients may change. Without this the portal call is refused.
4. Open Developers, then Webhooks (Workbench). Add an endpoint with the URL the app shows once the route exists. Select `checkout.session.completed`, `customer.subscription.created`, `customer.subscription.updated`, `customer.subscription.deleted`, `customer.subscription.paused`, `customer.subscription.resumed` and `invoice.payment_failed`.
5. Reveal the endpoint signing secret (`whsec_...`) and save it with the key.
6. Use test mode keys and the test clock first. Test and live mode have separate keys, prices, endpoints and signing secrets.

## Whop

Checked on 2026-11-25 against:

- [Whop API quickstart](https://docs.whop.com/developer/quickstart.md)
- [Webhooks](https://docs.whop.com/developer/guides/webhooks.md)
- [Create a checkout configuration](https://docs.whop.com/api-reference/checkout-configurations/create-a-checkout-configuration.md)
- [API versions](https://docs.whop.com/developer/api/versioning.md) and [Idempotent requests](https://docs.whop.com/developer/api/idempotency.md)
- [Accept payments](https://docs.whop.com/developer/guides/accept-payments.md)
- The published OpenAPI document at `https://api.whop.com/api/v1/openapi.json`, version date `2026-11-25`, for the `membership.activated`, `membership.updated`, `payment.succeeded` and `payment.failed` payloads, `GET /memberships/{id}` and `GET /accounts/me`

Every request sends `Authorization: Bearer <key>` and `Api-Version-Date: 2026-11-25` (the constant `WHOP_API_VERSION_DATE`). The pin matters: without it, an older key is served an earlier API shape that does not know `variant_id`.

| Function | Request |
| --- | --- |
| `validateCredentials` | `GET https://api.whop.com/api/v1/accounts/me`. Label is `title`, then `route`, `id`. |
| `createCheckout` | `POST /checkout_configurations` with JSON `{ "variant_id": "<planRef>", "metadata": { "reference": "<reference>" }, "redirect_url": "<successUrl>" }`, plus `account_id` when `accountId` is given. Returns `purchase_url` as `url` and the `ch_...` id as `sessionId`. |
| `createPortalLink` | `GET /memberships/<subscriptionId>` and returns its `manage_url`. Whop has no portal session call. Without `subscriptionId` no request is made and the result is `{ url: null, reason }`. A missing `manage_url` also returns `null` with a reason. |

`sandbox: true` switches all three to `https://sandbox-api.whop.com/api/v1`. Whop's sandbox and production keys look identical, so the caller has to store which one a key belongs to.

Differences from Stripe that the caller must handle:

- **Trial.** A trial belongs to the plan in Whop (`trial_period_days` on the variant). A checkout configuration for an existing plan cannot add or change it. `trialDays` is ignored and the result carries `trialIgnored: true` when a trial was asked for. Set the trial on the plan in the Whop dashboard.
- **Email.** No documented field prefills the buyer's email on a checkout configuration, so `customerEmail` is not sent.
- **Cancel URL.** The hosted checkout has no cancel URL. `cancelUrl` is validated and not sent.
- **Return.** The docs say the buyer lands on the redirect URL whatever the outcome, with `payment` and `status` appended. Fulfil from the webhook, never from the redirect.
- **Customer email on events.** Membership payloads carry no email. Only payment events do. Match a signup by `reference`.

Webhook verification: Whop follows the Standard Webhooks specification. Headers are `webhook-id`, `webhook-timestamp` (unix seconds) and `webhook-signature` (`v1,<base64>`, several separated by spaces). The module computes HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<raw body>`, keyed with the `ws_...` secret exactly as shown, and rejects a timestamp more than 300 seconds from now.

| Whop event | Normalized type |
| --- | --- |
| `membership.activated` with status `trialing` or `active` | `checkout.completed`. `reference` from `metadata.reference`, `subscriptionId` is the `mem_...` id, `customerId` is `member_id` or else `user_id`, `planRef` is `variant_id`. |
| `membership.updated` | By `status`: `trialing` to `subscription.trialing`; `active` to `subscription.active`; `past_due`, `unresolved` to `subscription.past_due`; `canceled`, `expired` to `subscription.canceled`; `completed`, `scheduled` to `ignored`. |
| `payment.succeeded` with a `membership_id` and a subscription `billing_reason` | `subscription.active` |
| `payment.failed` with a `membership_id` and `billing_reason: subscription_cycle` | `subscription.past_due` |
| Everything else, including `membership.trial_ending_soon` and a failed first payment | `ignored` |

Whop sends `membership.activated` and also a `membership.updated` for the same change, so an activation produces a `checkout.completed` followed by a `subscription.trialing` or `subscription.active`. Each has its own event id.

### Dashboard steps for an agency

1. In Whop, create a product and a recurring plan for the monthly price. Set the free trial length on the plan if one is wanted. Copy the plan id (`plan_...`).
2. Open the dashboard Developer page (`whop.com/dashboard/developer`). Under Account API keys choose Create. Use a custom permission set rather than Admin. The calls here need `checkout_configuration:create`, and `member:manage` if the manage link is wanted. The webhooks need `webhook_receive:memberships`, `webhook_receive:payments`, `member:basic:read`, `member:email:read`, `payment:basic:read` and `plan:basic:read`; the payment event pages list further read permissions for fields this module does not use. Copy the key once.
3. On the same page choose Create webhook. Enter the URL the app shows once the route exists, keep the API version on `v1`, and select `membership.activated`, `membership.updated`, `payment.succeeded` and `payment.failed`.
4. Copy the signing secret from the Secret column, including the `ws_` prefix, and save it with the key.
5. Build and test at `sandbox.whop.com` first. Sandbox and production share no accounts, keys, plans or webhooks.

## What the caller still has to build

- A table for stored keys and signing secrets, kept server side and never returned to the browser.
- An HTTP route that reads the raw body as text, calls `verifyWebhook`, then `parseEvent`, records `eventDedupeKey` durably, and answers 2xx within five seconds. A replay inside the five minute window still verifies, so the durable record is what prevents double handling.
- A pending signup keyed by `reference`, and the rule for which event grants access.
- Ordering. Compare `occurredAt` before applying an event, or read the current state from the provider.
- A decision on `trialIgnored` for Whop: show the plan's trial rather than the requested one.

## Not confirmed from documentation

1. **Whop signing key bytes.** The docs say the key is the `ws_...` secret, passed as given and not base64 encoded. The module uses the UTF-8 bytes of the whole string, prefix included. A real delivery has not been verified. If verification fails in the sandbox, this is the first thing to check.
2. **Whop `account_id`.** The schema lists it without marking it required. The module omits it and relies on the account behind an Account API key. `accountId` is available if Whop asks for it.
3. **Whop trial end.** For a trialing membership the module reads `most_recent_action_at` when `most_recent_action` is `trial_ends_at`, and otherwise `current_period_end`. The field descriptions suggest this but no page states it.
4. **Whop metadata on memberships.** The checkout configuration says its metadata is "copied to payments and memberships". The membership field itself is described as custom pairs "commonly used for software licensing". The round trip of `reference` rests on the first statement.
5. **Whop past due signal.** The `membership.updated` description lists activation, deactivation, cancel-at-period-end and seller edits. It does not say a move to `past_due` sends it. `payment.failed` on a renewal is mapped as a second signal for that reason.
6. **Whop `manage_url`.** Described as the page where the buyer signs in to manage billing, returned only with `member:manage`. Not seen in a real response.
7. **Whop permissions.** `GET /accounts/me` lists `company:balance:read` as its scope. A key without it is reported as working with a note. The permission list in the dashboard steps was assembled from the per-operation scopes and is not a published checklist.
8. **Whop API version pin.** `2026-11-25` is the version date of the OpenAPI document on the check date. Whop ships dated versions often. Raising the pin needs a re-read of the changelog.
9. **Stripe API version.** No `Stripe-Version` header is sent, so requests and webhook payloads follow the account and endpoint versions. The parser accepts both the older and the current location of `current_period_end` and of the invoice's subscription id.
10. **Stripe `paused`.** Mapped to `subscription.past_due` because a trial that ends without a payment method pauses the subscription and access should stop. Stripe does not call this past due.
11. **Stripe trial without a card.** `payment_method_collection` is left at Stripe's default, `always`, so a card is collected before the trial starts.
12. **403 means authenticated.** Both providers are assumed to answer 401 for a bad key and 403 for a valid key without permission.
13. **Sandbox and test mode behaviour.** Nothing here has been run against either.
