Billing, plans and quotas (Phase 13)
Plan matrix, trial, Stripe/iyzico/mock providers, usage report, quota and feature gates, alert emails. Design decisions: ADR-0020. Shared code: packages/billing (plan matrix, provider adapters, quota…
Plan matrix, trial, Stripe/iyzico/mock providers, usage report, quota and feature gates, alert emails. Design decisions: docs/adr/0020-faturalama-kota-admin.md. Shared code: packages/billing (plan matrix, provider adapters, quota helpers, DNS verification, disposable email list).
1. Plans
The plans table is seeded by migration 0021; packages/billing/src/plans.ts is the single source of truth (ensurePlans fills in missing rows). The dashboard's Organization → Billing and GET /internal/v1/billing/plans read the same data.
| Plan | Monthly | Subscribers | Messages/month | API rps | Members | Apps | Retention | Journeys | Segments | A/B variants | Features |
|---|---|---|---|---|---|---|---|---|---|---|---|
| free | 0 | 10k | 100k | 20 | 3 | 1 | 30 days | 1 | 10 | 2 | push, email, in-app, journeys (no A/B, SMS, approval flow or composer) |
| starter | $99 | 50k | 1M | 100 | 10 | 3 | 90 days | 10 | 50 | 4 | + A/B, SMS, audit export, composer |
| growth | $399 | 500k | 10M | 500 | 50 | 10 | 365 days | 100 | 500 | 10 | + approval flow |
| enterprise | custom | ∞ | ∞ | 2000 | ∞ | ∞ | 730 days | ∞ | ∞ | 10 | + SSO |
Other limits: tags_per_user, aliases_per_user, subscriptions_per_user, report_history_days, webhooks, api_keys. null = unlimited. Role gate: roles outside features.roles cannot be assigned (HS_PLAN_FEATURE_REQUIRED, details.feature = "roles").
Effective plan (effectivePlanCode): the plan of a subscription in good payment standing (active, trialing, past_due; PAID_PLAN_STATUSES) > starter while a trial is running (it only upgrades: a higher organizations.plan_code assigned by a platform administrator is not downgraded during the trial) > organizations.plan_code > free. An incomplete/incomplete_expired subscription does not unlock a plan. A new organization gets a 14-day trial (trial_ends_at); emails are sent 3 days before it ends and when it ends.
2. Providers
| Provider | Selection | Notes |
|---|---|---|
stripe | STRIPE_SECRET_KEY + STRIPE_WEBHOOK_SECRET | REST (no SDK): Checkout Session (subscription mode, client_reference_id = org_id, metadata.plan_code), Customer Portal, cancel_at_period_end, invoice list. Webhook POST /hooks/billing/stripe — Stripe-Signature (t/v1 HMAC-SHA256, 5 min tolerance). The plan price is mapped via plans.stripe_price_id (the metadata.plan_code field of the Stripe price is also read). |
iyzico | IYZICO_API_KEY + IYZICO_SECRET_KEY + IYZICO_MERCHANT_ID + the billing.iyzico feature flag (or BILLING_PROVIDER=iyzico) | Subscription Checkout Form (IYZWSv2 signed). Flow: POST …/billing/checkout → subscription/checkoutform/initialize (customer name, email, GSM — the phone number in the billing info is normalized to the +90… format) → form content in Redis hs:iyzico:form:<token> (30 min) → the user goes to the API-hosted GET /hooks/billing/iyzico/form/:token page (with a page-specific CSP) → iyzico POST /hooks/billing/iyzico/checkout (token) → the result is queried with GET /v2/subscription/checkoutform/{token}, the subscription/plan is synced, and the user is returned to the dashboard with a 303. Card update: POST /hooks/billing/iyzico/card. Webhook POST /hooks/billing/iyzico: X-IYZ-SIGNATURE-V3 = hex HMAC-SHA256(secretKey, merchantId + secretKey + iyziEventType + subscriptionReferenceCode + orderReferenceCode + customerReferenceCode); events `subscription.order.success |
creem | CREEM_API_KEY + CREEM_WEBHOOK_SECRET + CREEM_PRODUCTS | REST (ADR-0045): POST /v1/checkouts, customer portal POST /v1/customers/billing, end-of-period cancellation mode=scheduled. Webhook POST /hooks/billing/creem, header creem-signature (HMAC-SHA256 of the raw body). USD products for Starter and Growth (Creem does not accept TRY; if there is no match, checkout falls back to USD). Free and Enterprise are not products. No Creem trial is started. |
mock | no key (non-production) | Checkout returns to …/settings/billing?checkout=success&mock_checkout=<id>&plan=<kod>&customer=<cus>; the dashboard calls POST …/billing/mock/complete → Stripe-style checkout.session.completed + customer.subscription.created + `invoice.paid |
BILLING_PROVIDER=auto (default): stripe if a Stripe key is present, creem if a Creem key is present, iyzico if the iyzico flag + key are present, otherwise mock.
The none state — in production (NODE_ENV=production), if Stripe, Creem or iyzico is not configured, the read endpoints still work: GET …/billing returns provider: "none", and GET …/billing/plans and GET /internal/v1/billing/plans return all plans with purchasable: false; invoices and the usage report are unaffected. Checkout and the portal return 503 HS_SERVICE_UNAVAILABLE (details.reason = billing_provider_not_configured, "Payment provider is not configured"). The dashboard shows the current plan, limits and usage; instead of the purchase row, a "Contact support to change your plan" card appears (with the brand's support email, or support@pushizo.com if none). Plan changes are made from the platform admin panel.
Webhook processing (BillingService.applyEvent): idempotent via billing_events (if processing fails, the event record is deleted so the provider's retry processes it again); a subscription event upserts billing_subscriptions + syncs organizations.plan_code (cancellation → free) + invalidates the plan cache; an invoice event upserts invoices, and invoice.payment_failed → past_due + a payment_failed email (owner/admin/billing). On a paid plan, the card is collected once at checkout; the monthly fee is charged automatically, and cancellation keeps the plan active until the end of the period (iyzico cancellations cannot be undone). Overage is added to the next invoice on Stripe and charged once to the saved card on iyzico; if the charge fails, it is paid from the dashboard. Events of the overage subscription do not change the main plan.
3. Endpoints
| Path | Permission | Description |
|---|---|---|
GET /internal/v1/billing/plans | session | Plan matrix (purchasable: provider price defined, or mock) |
GET /internal/v1/orgs/:orgId/billing | billing.manage | Status: provider, plan, trial, subscription, suspension, billing info |
PUT …/billing/info | billing.manage | Billing/tax details (settings.billing) |
POST …/billing/checkout {plan_code} | billing.manage | Checkout URL; if there is an active subscription, use the portal instead (409) |
POST …/billing/portal | billing.manage | Customer portal |
POST …/billing/cancel {cancel_at_period_end} | billing.manage | Cancel at period end / undo |
GET …/billing/invoices?sync=1 | billing.manage | Invoices (sync fetches from the provider) |
GET …/usage?days=30 | analytics.read | Usage report |
GET …/features | session | Plan features/limits + feature flag values |
POST …/billing/mock/complete | billing.manage | Mock checkout simulation (non-production) |
GET /v1/organization/usage?days= | org-wide analytics:read/admin key | The same usage report (public; Node hs.organization.usage(), PHP $hs->organization->usage(), other SDKs organization.usage) |
POST /hooks/billing/:provider | signature | Provider webhook |
Usage report: metrics[] (metric, used, limit, percent, hard), apps[] (messages_sent, active_subscriptions, mau), daily[] (messages_sent / api_requests / events_ingested for the last N days), trialing, trial_ends_at.
4. Usage and quotas
- Rollup (
usage-rollup, hourly;apps/worker/src/processors/billing.ts):usage_dailyfor yesterday + today (org × app × metric;app_id = ''is the total):messages_sent(deliveries.sent_at),events_ingested,api_requests(api_request_logs),active_subscriptions,mau(last_active_atwithin the last 30 days). - Monthly message counter Redis
hs:usage:{org}:{YYYYMM}:messages: API/campaign sends reserve the estimated recipient count at creation time (QuotaService.assertMessages,options.quota_reserved); during audience resolution, the worker corrects the difference with the actual target count once (hs:usage:adj:<mesaj>), and deliveries that exceed the remaining quota becomesuppressed/quota_exceeded. Scheduled/recurring campaigns are pre-checked at scheduling time (without reservation). The rollup never lowers the counter; it only reconciles it upward. - Hard limits (
HS_QUOTA_EXCEEDED429,details { metric, limit, used, add, plan }): monthly messages, apps, members + pending invites, active (published) journeys, segments, webhooks, API keys, number of A/B variants, tags/aliases/subscriptions per user; a new organization is limited to 1000 messages per day for the first 24 hours (new_org_daily_messages). The subscriber count is a soft limit (warning). If the counter has exceeded the limit during audience resolution, the worker writes deliveries assuppressed/quota_exceeded(last line of defense). - Feature gates (
HS_PLAN_FEATURE_REQUIRED403,details { feature, plan }):sms/emailchannel setup,in_appmessage creation,journeyspublishing,ab_testing(variants),roles(role assignment). - Plan-based rate limit: the default API key capacity is the plan's
api_rpsvalue (RateLimitGuard; org plan cache 60 s). - Alerts (
usage_alerts, once per period): 80% and 100% (messages_per_month,subscriptions) emails to owner/admin/billing members; trial ending; payment failed.
The effective plan cache is Redis hs:plan:{org} (60 s); QuotaService.invalidate on plan/subscription changes.
5. Suspension
organizations.status = suspended (platform admin): API key requests get 403 HS_ORG_SUSPENDED, the dashboard can only read billing/status, SDK endpoints return 403, and worker deliveries become suppressed/org_suspended. When lifted, an org_unsuspended email is sent. Details: platform-admin.md.
6. Tests
Stripe test mode (Phase 13 acceptance): tests/e2e/billing-stripe.spec.ts verifies the flow sign-up → trial → quota exceeded 429 → Stripe Checkout (published test card) → webhook → Growth → invoice → send. It runs only when E2E_STRIPE=1; in CI, the e2e.yml → e2e-stripe job runs when the repository variable STRIPE_E2E=true and the secrets STRIPE_TEST_SECRET_KEY (only sk_test_/rk_test_ are accepted) and STRIPE_TEST_PRICE_GROWTH are defined; webhooks are forwarded with stripe listen --forward-to http://localhost:4000/hooks/billing/stripe, and STRIPE_WEBHOOK_SECRET is generated within the job. Locally: start the API with test keys and BILLING_PROVIDER=stripe, set plans.stripe_price_id to the Growth test price, run stripe listen, and run E2E_STRIPE=1 npx playwright test tests/e2e/billing-stripe.spec.ts.
packages/billing/src/__tests__/billing.test.ts (plan matrix, effective plan, quota/threshold/reputation helpers, Stripe signature/normalization/REST, iyzico auth/webhook, mock, DNS, disposable email), apps/api/src/__tests__/phase13.int.test.ts (plans/trial/usage, quota and feature gates, mock checkout → subscription → invoice, webhook signature, suspension 403, support session, admin endpoints, status page, OAuth, DNS), apps/worker/src/__tests__/billing.int.test.ts (rollup, alerts, suppressions, reputation, DNS, quota reservation, complaint review), apps/api/src/__tests__/iyzico.int.test.ts (form → result → webhook against a fake iyzico server; one-time payment of overage fees), apps/worker/src/__tests__/overage.int.test.ts and packages/billing/src/__tests__/overage.test.ts (passing overage fees to the provider, ADR-0036 §6), E2E tests/e2e/billing-admin.spec.ts (trial → quota exceeded 429 → mock upgrade → sending unlocked) and tests/e2e/billing-stripe.spec.ts.
Server-side quickstart
Create an API key, send your first POST /v1/notifications request with cURL, then use one of the server SDKs (Node, PHP, Python, Go, Java, .NET, Ruby).
Channels overview
The channels Pushizo supports (Web Push, iOS, Android, Huawei, email, SMS, WhatsApp, RCS, in-app, notification inbox, Live Activities), their providers and setup requirements.