# Crovver > This file is very large and may be truncated. For an index of this content, please refer to https://docs.crovver.com/llms.txt instead. # Build with AI tools Source: https://docs.crovver.com/ai-tools/overview Give your coding assistant Crovver's docs as plain text, so it integrates against the real API. Coding assistants integrate Crovver faster and with fewer mistakes when they can read these docs instead of guessing. Crovver serves its documentation as plain text for AI tools. ## llms.txt Point your assistant at a plain-text copy of the docs: | File | Contents | | - | - | | [`/llms.txt`](https://docs.crovver.com/llms.txt) | An index of every page, with a one-line summary each | | [`/llms-full.txt`](https://docs.crovver.com/llms-full.txt) | Every page in full, in one file | Any page is also available as Markdown by adding `.md` to its URL, for example [`/quickstart.md`](https://docs.crovver.com/quickstart.md). # List Active Add-ons Source: https://docs.crovver.com/api-reference/addons/tenant-active GET /api/public/tenants/{tenantId}/addons/active Get a tenant's currently active add-on credit balances. Returns add-on credit ledger entries that still have credits remaining (not exhausted, not expired), grouped by pool key. Returns an empty array `[]` if the tenant has no active subscription or no purchased add-ons. ## Path Parameters **tenantId** `string` *required* The external tenant ID from your application ## Query Parameters **publicKey** `string` Your public key (`pk_live_...`). Alternative to the `Authorization` bearer header. ## Authentication Requires a **public key** (`?publicKey=pk_live_...`) or **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl "https://app.crovver.com/api/public/tenants/workspace_123/addons/active?publicKey=pk_live_..." ``` ```json 200 theme={null} { "success": true, "data": [ { "pool_key": "api_calls", "addon_remaining": "500", "active_addon_grants": "1", "next_addon_expiry": "2026-06-10T05:12:21.000Z" } ] } ``` ```json 200 No active add-ons theme={null} { "success": true, "data": [] } ``` # List Available Add-ons Source: https://docs.crovver.com/api-reference/addons/tenant-available GET /api/public/tenants/{tenantId}/addons/available Get add-ons the tenant can purchase for their current plan and currency. Returns add-ons that are assigned to the tenant's active plan, priced in their subscription currency, and have a corresponding credit pool on the plan. Also includes the tenant's current balance for each pool. Returns an empty array `[]` if the tenant has no active subscription. ## Path Parameters **tenantId** `string` *required* The external tenant ID from your application ## Query Parameters **publicKey** `string` Your public key (`pk_live_...`). Alternative to the `Authorization` bearer header. ## Authentication Requires a **public key** (`?publicKey=pk_live_...`) or **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl "https://app.crovver.com/api/public/tenants/workspace_123/addons/available?publicKey=pk_live_..." ``` ```json 200 theme={null} { "success": true, "data": [ { "id": "uuid", "pool_key": "api_calls", "display_name": "API Call Pack", "description": "500 additional API calls", "credit_qty": 500, "expiry_type": "period_end", "expiry_days": null, "currency": "USD", "amount": "5.00", "current_balance": 0, "pool_limit": 10000 } ] } ``` ```json 200 No active subscription theme={null} { "success": true, "data": [] } ``` # Purchase Add-on Source: https://docs.crovver.com/api-reference/addons/tenant-purchase POST /api/public/tenants/{tenantId}/addons/purchase Initiate a checkout session for a tenant to purchase an add-on. Creates a Stripe checkout session for the tenant to purchase an add-on. Credits are granted automatically after payment confirmation via webhook (`event_type: addon_purchase`). The call is idempotent — passing the same `idempotencyKey` twice returns the original result without creating a duplicate checkout. ## Path Parameters **tenantId** `string` *required* The external tenant ID from your application ## Request Body **addonId** `string` *required* The add-on ID to purchase (from the available add-ons list) **currency** `string` *required* 3-letter ISO currency code. Must match the tenant's subscription currency. **idempotencyKey** `string` *required* Unique key for this purchase event. Duplicate calls with the same key return the original result. **successUrl** `string` URL to redirect to after payment. Defaults to the org's configured success URL. **cancelUrl** `string` URL to redirect to if the user cancels. Defaults to the org's configured cancel URL. **metadata** `object` Optional context stored on the purchase record. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/tenants/workspace_123/addons/purchase" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "addonId": "uuid", "currency": "USD", "idempotencyKey": "addon-purchase-1778423112701", "successUrl": "https://app.com/settings?addon=purchased", "cancelUrl": "https://app.com/settings" }' ``` ```json 200 Checkout created theme={null} { "success": true, "data": { "purchaseId": "uuid", "checkoutUrl": "https://checkout.stripe.com/pay/cs_...", "requiresPayment": true, "addonName": "API Call Pack", "creditQty": 500, "amount": 5, "currency": "USD" } } ``` ```json 200 Already processed (idempotent replay) theme={null} { "success": true, "data": { "purchaseId": "uuid", "checkoutUrl": "https://checkout.stripe.com/pay/cs_...", "alreadyProcessed": true } } ``` ```json 422 Currency mismatch theme={null} { "success": false, "error": "Currency mismatch: subscription uses NPR" } ``` # List Invoices Source: https://docs.crovver.com/api-reference/billing/invoices GET /api/public/billing/invoices A customer's invoices, newest first. Returns the customer's invoices: subscription charges, renewals, seat changes and add-on purchases. Amounts are strings in the currency's normal unit, so `"29.00"` means 29.00. ## Query Parameters **externalTenantId** `string` *required* Your ID for the customer. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl "https://app.crovver.com/api/public/billing/invoices?externalTenantId=workspace_123" \ -H "Authorization: Bearer sk_live_..." ``` ```typescript Node.js theme={null} const { invoices } = await crovver.getInvoices("workspace_123"); ``` ```php PHP theme={null} $result = $client->getInvoices('workspace_123'); ``` ```json 200 theme={null} { "success": true, "data": { "invoices": [ { "id": "9a41e2b6-2db4-41e4-9d60-3a8062fd1998", "invoiceNumber": "INV-USD-2026-000003", "invoiceType": "subscription", "totalAmount": "758.40", "currency": "USD", "status": "paid", "periodStart": "2026-08-13T00:00:00.000Z", "periodEnd": "2027-08-13T00:00:00.000Z", "issuedAt": "2026-10-13T18:14:04.123Z", "dueDate": "2027-08-13T00:00:00.000Z", "paidAt": "2026-10-13T18:16:41.306Z", "paymentProvider": null, "hostedInvoiceUrl": null, "invoicePdf": null, "planName": "Pro" } ] } } ``` # Allocate Seat Source: https://docs.crovver.com/api-reference/capacity/allocate POST /api/public/capacity/allocate Record a seat assignment for a tenant user. Records a seat allocation in Crovver when a user is added to a workspace. This is a lightweight audit operation — it does not trigger billing automatically. If the tenant is already at capacity, returns proration info for confirmation. If `confirmProration: true` is passed and capacity would be exceeded on a seat-based plan, returns a checkout URL to pay for the additional seat. The call is idempotent per `externalUserId` — re-allocating the same user updates their record rather than creating a duplicate. ## Request Body **requestingEntityId** `string` *required* The external tenant ID from your application **externalUserId** `string` *required* Your application's user ID for the seat being allocated. Must be unique within the tenant's subscription. The call is idempotent — reallocating the same ID updates the record rather than creating a duplicate. **email** `string` The user's email address (stored for audit purposes) **name** `string` The user's display name **confirmProration** `boolean` Pass `true` to confirm an over-capacity allocation and proceed to checkout. **metadata** `object` Optional context stored on the allocation record. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/capacity/allocate" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "requestingEntityId": "workspace_123", "externalUserId": "user_456", "email": "user@acme.com", "name": "Jane Smith" }' ``` ```json 200 Seat allocated theme={null} { "success": true, "data": { "success": true, "message": "Seat allocation recorded successfully", "capacity": { "activeCount": 6, "capacityUnits": 10, "exceeded": false } } } ``` ```json 200 Proration required (at capacity) theme={null} { "success": true, "data": { "requiresProration": true, "proration": { "amount": 1.75, "currency": "USD", "description": "Prorated charge for 1 additional seat", "daysRemaining": 17, "totalDaysInPeriod": 30, "currentSeats": 10, "newSeats": 11 }, "message": "Adding this user will exceed your current capacity. Confirm to upgrade and charge the prorated amount." } } ``` ```json 200 Checkout required (confirmed) theme={null} { "success": true, "data": { "requiresCheckout": true, "message": "Capacity upgrade requires payment. Use the proration-checkout endpoint to create checkout session.", "newCapacity": 11 } } ``` # List Allocations Source: https://docs.crovver.com/api-reference/capacity/allocations GET /api/public/capacity/allocations List users allocated to a tenant's active subscription, with capacity summary and pagination. Returns the seat allocations for a tenant's active subscription. Filter by status, paginate through results, and inspect real-time capacity utilization. ## Query Parameters **requestingEntityId** `string` *required* The external tenant ID from your application. **status** `string` (default: active) Filter allocations by status. One of: * `active` — currently allocated users (default) * `removed` — deallocated users * `all` — both active and removed **page** `number` (default: 1) 1-based page number. **limit** `number` (default: 50) Number of results per page. Maximum **100**. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ## Response | Field | Type | Description | | - | - | - | | `allocations` | `AllocationUser[]` | Paginated list of allocated users | | `allocations[].externalUserId` | `string` | Your app's user ID | | `allocations[].email` | `string \| null` | User's email | | `allocations[].name` | `string \| null` | User's display name | | `allocations[].status` | `"active" \| "removed"` | Current allocation status | | `allocations[].allocatedAt` | `string` | ISO 8601 timestamp of when the seat was assigned | | `allocations[].removedAt` | `string \| null` | ISO 8601 timestamp of deallocation (if removed) | | `allocations[].metadata` | `object` | Metadata stored at allocation time | | `capacity.activeCount` | `number` | Current active seat count | | `capacity.capacityUnits` | `number` | Total seat limit on the subscription | | `capacity.utilizationPercentage` | `number` | `activeCount / capacityUnits × 100` | | `capacity.exceeded` | `boolean` | Whether active seats exceed the limit | | `pagination.total` | `number` | Total matching records | | `pagination.page` | `number` | Current page | | `pagination.totalPages` | `number` | Total pages | | `pagination.hasNextPage` | `boolean` | Whether a next page exists | | `pagination.hasPreviousPage` | `boolean` | Whether a previous page exists | ```bash cURL theme={null} curl "https://app.crovver.com/api/public/capacity/allocations?requestingEntityId=workspace_123&status=active&page=1&limit=50" \ -H "Authorization: Bearer sk_live_..." ``` ```typescript Node.js SDK theme={null} const result = await crovver.capacity.getAllocations({ requestingEntityId: "workspace_123", }); result.allocations.forEach((user) => { console.log(`${user.externalUserId} — ${user.email} (${user.status})`); }); const { activeCount, capacityUnits, utilizationPercentage, exceeded } = result.capacity; console.log(`${activeCount} / ${capacityUnits} seats (${utilizationPercentage}%)`); // Page through all users including removed const page2 = await crovver.capacity.getAllocations({ requestingEntityId: "workspace_123", status: "all", page: 2, limit: 25, }); ``` ```php PHP SDK theme={null} // Active users, first page (default) $result = $client->getAllocations('workspace_123'); foreach ($result->allocations as $user) { echo $user->externalUserId . ' — ' . $user->email; echo ' (' . $user->status . ')'; } echo $result->capacity->activeCount . ' / ' . $result->capacity->capacityUnits . ' seats'; echo $result->capacity->utilizationPercentage . '% utilized'; if ($result->capacity->exceeded) { // Over limit — prompt upgrade } // Page 2, all statuses $page2 = $client->getAllocations( requestingEntityId: 'workspace_123', status: 'all', page: 2, limit: 25, ); echo $page2->pagination->total . ' total users'; ``` ```json 200 Success theme={null} { "success": true, "data": { "allocations": [ { "externalUserId": "user_1", "email": "alice@acme.com", "name": "Alice", "status": "active", "allocatedAt": "2026-05-01T10:00:00.000Z", "removedAt": null, "metadata": { "addedBy": "admin_789" } }, { "externalUserId": "user_2", "email": "bob@acme.com", "name": "Bob", "status": "active", "allocatedAt": "2026-05-03T14:30:00.000Z", "removedAt": null, "metadata": {} } ], "capacity": { "activeCount": 8, "capacityUnits": 10, "utilizationPercentage": 80, "exceeded": false }, "pagination": { "total": 8, "page": 1, "limit": 50, "totalPages": 1, "hasNextPage": false, "hasPreviousPage": false } } } ``` ```json 400 Missing required param theme={null} { "success": false, "error": "Missing required query param: requestingEntityId" } ``` ```json 404 No active subscription theme={null} { "success": false, "error": "No active subscription found for this tenant" } ``` # Bulk Allocate Seats Source: https://docs.crovver.com/api-reference/capacity/bulk-allocate POST /api/public/capacity/bulk-allocate Allocate up to 100 users to a tenant's subscription in one atomic operation. Inserts multiple seat allocations in a single call, up to the subscription's current `capacity_units`. No proration is triggered — if the batch would exceed capacity, users are split into `allocated` and `rejected` lists. Upgrade capacity first via [Proration Checkout](/api-reference/capacity/proration-checkout), then retry the rejected IDs. Already-active users are silently skipped and returned in `skipped` — the call is safe to retry. > [!WARNING] > > This endpoint is **never retried automatically** by the SDK to prevent duplicate allocations on network errors. Implement your own retry logic using the `skipped` list for idempotency. ## Request Body **requestingEntityId** `string` *required* The external tenant ID from your application. **users** `BulkAllocateSeatUser[]` *required* List of users to allocate. Maximum **100 users per request**. Each entry must have a unique `externalUserId` — duplicates within the same batch are rejected. **users\[].externalUserId** `string` *required* Your application's user ID. Must be non-empty and unique within the batch. **users\[].email** `string` User's email address (stored for audit and display purposes). **users\[].name** `string` User's display name. **metadata** `object` Arbitrary key-value pairs attached to every allocation created in this batch. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ## Response Returns HTTP **200** when all users were allocated or skipped. Returns HTTP **207 Multi-Status** when at least one user was rejected due to capacity limits. | Field | Type | Description | | - | - | - | | `allocated` | `string[]` | `externalUserId` values inserted this call | | `skipped` | `string[]` | Already active — not re-inserted | | `rejected` | `string[]` | Would exceed `capacity_units` — not inserted | | `capacity.activeCount` | `number` | Active seat count after this operation | | `capacity.capacityUnits` | `number` | Total seat limit on the subscription | | `message` | `string` | Present when users were rejected — explains the limit | ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/capacity/bulk-allocate" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "requestingEntityId": "workspace_123", "users": [ { "externalUserId": "user_1", "email": "alice@acme.com", "name": "Alice" }, { "externalUserId": "user_2", "email": "bob@acme.com", "name": "Bob" }, { "externalUserId": "user_3", "email": "carol@acme.com", "name": "Carol" } ], "metadata": { "addedBy": "admin_789" } }' ``` ```typescript Node.js SDK theme={null} const result = await crovver.capacity.bulkAllocate({ requestingEntityId: "workspace_123", users: [ { externalUserId: "user_1", email: "alice@acme.com", name: "Alice" }, { externalUserId: "user_2", email: "bob@acme.com", name: "Bob" }, { externalUserId: "user_3", email: "carol@acme.com", name: "Carol" }, ], metadata: { addedBy: "admin_789" }, }); console.log(`Allocated: ${result.allocated.length}`); console.log(`Skipped: ${result.skipped.length}`); console.log(`Rejected: ${result.rejected.length}`); if (result.rejected.length > 0) { // Upgrade capacity, then retry result.rejected console.warn(result.message); } ``` ```php PHP SDK theme={null} use Crovver\Types\BulkAllocateSeatsRequest; use Crovver\Types\BulkAllocateSeatUser; $result = $client->bulkAllocateSeats(new BulkAllocateSeatsRequest( requestingEntityId: 'workspace_123', users: [ new BulkAllocateSeatUser('user_1', 'alice@acme.com', 'Alice'), new BulkAllocateSeatUser('user_2', 'bob@acme.com', 'Bob'), new BulkAllocateSeatUser('user_3', 'carol@acme.com', 'Carol'), ], metadata: ['addedBy' => 'admin_789'], )); echo count($result->allocated) . ' allocated'; echo count($result->skipped) . ' skipped'; echo count($result->rejected) . ' rejected'; if (count($result->rejected) > 0) { // Upgrade capacity, then retry $result->rejected echo $result->message; } ``` ```json 200 All allocated theme={null} { "success": true, "data": { "allocated": ["user_1", "user_2", "user_3"], "skipped": [], "rejected": [], "capacity": { "activeCount": 8, "capacityUnits": 10 } } } ``` ```json 207 Partial — capacity limit reached theme={null} { "success": true, "data": { "allocated": ["user_1", "user_2"], "skipped": [], "rejected": ["user_3"], "capacity": { "activeCount": 10, "capacityUnits": 10 }, "message": "2 user(s) allocated. 1 user(s) rejected — capacity limit of 10 reached." } } ``` ```json 400 Duplicate IDs in batch theme={null} { "success": false, "error": "Duplicate externalUserId values found within the batch" } ``` ```json 400 Batch too large theme={null} { "success": false, "error": "Batch size exceeds limit. Maximum 100 users per request." } ``` ```json 404 No active subscription theme={null} { "success": false, "error": "No active subscription found for this tenant" } ``` # Get Seat Count Source: https://docs.crovver.com/api-reference/capacity/count POST /api/public/capacity/count Get the current active seat count and capacity for a tenant. Returns the number of active seat allocations for a tenant, their total purchased capacity, and utilization percentage. ## Request Body **requestingEntityId** `string` *required* The external tenant ID from your application ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/capacity/count" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "requestingEntityId": "workspace_123" }' ``` ```json 200 theme={null} { "success": true, "data": { "activeCount": 8, "capacityUnits": 10, "utilizationPercentage": 80, "billingMode": "recurring", "exceeded": false } } ``` ```json 404 No active subscription theme={null} { "success": false, "error": "No active subscription found for this tenant" } ``` # Proration Checkout Source: https://docs.crovver.com/api-reference/capacity/proration-checkout POST /api/public/capacity/proration-checkout Create a checkout session for a mid-cycle seat upgrade with proration. When a tenant needs more seats mid-billing cycle, this endpoint calculates the prorated charge for the remaining days and creates a Stripe checkout session for that amount. The actual capacity upgrade happens **after payment confirmation** via the Stripe webhook (`event_type: seat_proration`). For ConnectIPS, the customer pays a proration invoice through the gateway, and the seats are added once it is verified. On a [tiered plan](/guides/seat-based-billing#tiered-seat-pricing), the charge is the difference between the new band's price and the current band's, for the days left. A count that stays in the current band costs nothing: the seats apply at once, `subscription.updated` is sent, and the response has `requiresPayment: false` and `prorationId: null`. A count no band holds is refused with `422 NO_BAND_FOR_QUANTITY`. On any plan, a `newCapacity` that is not above the current count is refused with `400 CAPACITY_NOT_INCREASED`. ## Request Body **externalTenantId** `string` *required* The external tenant/workspace ID from your application **newCapacity** `integer` *required* The new total seat count (must be greater than current `capacityUnits`) **planId** `string` The plan ID to upgrade. Defaults to the tenant's current active plan. **successUrl** `string` URL to redirect to after payment. Defaults to the org's configured success URL. **cancelUrl** `string` URL to redirect to if the user cancels. Defaults to the org's configured cancel URL. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/capacity/proration-checkout" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "externalTenantId": "workspace_123", "newCapacity": 15, "successUrl": "https://app.com/settings?upgraded=1", "cancelUrl": "https://app.com/settings/seats" }' ``` ```json 200 Stripe checkout created theme={null} { "success": true, "data": { "prorationId": "uuid", "checkoutUrl": "https://checkout.stripe.com/pay/cs_...", "requiresPayment": true, "prorationAmount": 1750, "prorationDetails": { "description": "Prorated charge for 5 additional seats", "calculation": "5 seats × $1.00/seat × 17/30 days" }, "message": "Checkout session created. Capacity will be upgraded after payment confirmation." } } ``` ```json 200 Invoice generated (non-Stripe) theme={null} { "success": true, "data": { "prorationId": "uuid", "checkoutUrl": null, "requiresPayment": false, "prorationAmount": 1750, "message": "Invoice generated. Capacity will be updated after payment confirmation." } } ``` ```json 200 Tiered plan, same band theme={null} { "success": true, "data": { "prorationId": null, "checkoutUrl": null, "invoiceId": null, "requiresPayment": false, "prorationAmount": 0, "prorationDetails": { "description": "11–50 seats: no charge for the rest of this period", "calculation": "USD 250 − 250", "amount": 0 }, "message": "Capacity updated. No payment is due." } } ``` # Create Checkout Token Source: https://docs.crovver.com/api-reference/checkout/checkout-token POST /api/public/auth/checkout-token Mint a short-lived JWT to initiate the checkout redirect flow. Creates a signed JWT that the portal uses to identify the tenant during checkout. The React SDK calls this automatically when you invoke `redirectToCheckout()`. ## Request Headers **x-public-key** `string` *required* Your public key (`pk_live_...`) ## Request Body **externalTenantId** `string` *required* The tenant ID from your application **returnUrl** `string` *required* URL to return to after checkout completes **externalUserId** `string` The user ID from your application. Used for D2C tenant auto-provisioning. **externalTenantName** `string` Display name for the tenant. Used when auto-provisioning a new tenant. **requiredFeature** `string` Pre-selects a plan that includes this feature on the pricing page. **requiredPlan** `string` Pre-selects a specific plan ID on the pricing page. **metadata** `object` Additional context passed into the JWT. Supports `userEmail`, `userName`, and custom fields. ## Response **data.token** `string` Signed JWT (valid for 10 minutes) **data.expiresAt** `string` ISO 8601 expiry timestamp **meta.checkoutUrl** `string` The full portal URL with token appended — redirect the user here ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/auth/checkout-token" \ -H "x-public-key: pk_live_..." \ -H "Content-Type: application/json" \ -d '{ "externalTenantId": "workspace_123", "returnUrl": "https://app.com/dashboard" }' ``` ```json 201 theme={null} { "success": true, "data": { "token": "eyJhbGciOiJIUzI1NiJ9...", "expiresAt": "2025-01-01T00:10:00Z" }, "meta": { "checkoutUrl": "https://portal.crovver.com/pricing?token=eyJhbGci...", "expiresIn": 600 } } ``` # Create Checkout Session Source: https://docs.crovver.com/api-reference/checkout/create-session POST /api/public/checkout Create a payment provider checkout session for a tenant. Creates a checkout session with the configured payment provider (Stripe or ConnectIPS) and returns a URL to redirect the user to. ## Request Body **planId** `string` *required* The Crovver plan ID to subscribe to **externalUserId** `string` The user ID from your application. For a D2C product, it is the customer's identity. **externalTenantId** `string` The workspace/tenant ID. Required for B2B orgs. **provider** `string` Payment provider: `stripe` or `connectips`. Not needed for a free plan. Defaults to the org's configured provider. **currency** `string` 3-letter ISO currency code (e.g. `USD`, `NPR`). Defaults to the plan's first active price currency. **totalCapcityUnits** `integer` Number of seats to purchase. Required for seat-based plans. **userEmail** `string` Pre-fills the payment provider's checkout form with this email. **userName** `string` Pre-fills the payment provider's checkout form with this name. **successUrl** `string` URL to redirect to after successful payment. Defaults to the org's configured success URL. **cancelUrl** `string` URL to redirect to if the user cancels checkout. Defaults to the org's configured cancel URL. **metadata** `object` Arbitrary key-value pairs passed through to the payment provider. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL (D2C) theme={null} curl -X POST "https://app.crovver.com/api/public/checkout" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "externalUserId": "user_123", "planId": "7b79a62c-e82e-405f-9719-7314f3d6e7f2", "provider": "stripe", "successUrl": "https://app.com/welcome", "cancelUrl": "https://app.com/pricing" }' ``` ```bash cURL (B2B) theme={null} curl -X POST "https://app.crovver.com/api/public/checkout" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "externalTenantId": "company_acme_123", "externalUserId": "user_admin_456", "planId": "7b79a62c-e82e-405f-9719-7314f3d6e7f2", "provider": "stripe", "successUrl": "https://app.com/welcome", "cancelUrl": "https://app.com/pricing" }' ``` ```json 201 theme={null} { "success": true, "data": { "checkoutUrl": "https://checkout.stripe.com/pay/cs_test_...", "sessionId": "cs_test_...", "subscriptionId": "sub_crovver_abc" } } ``` # Create Portal Token Source: https://docs.crovver.com/api-reference/checkout/portal-token POST /api/public/auth/portal-token Mint a short-lived JWT to redirect the user to the billing portal. Creates a signed JWT for accessing the self-service billing portal — where tenants can view invoices, update payment methods, manage seats, and cancel their subscription. The tenant must already exist (i.e. have gone through checkout at least once). Returns `404` if the tenant is not found. ## Request Headers **x-public-key** `string` *required* Your public key (`pk_live_...`) ## Request Body **externalTenantId** `string` *required* The tenant ID from your application **returnUrl** `string` *required* URL to return to when the user exits the portal. Must be a valid URL. **metadata** `object` Optional context stored with the token. Supports `userEmail`, `userName`. ## Response **data.token** `string` Signed JWT (valid for 10 minutes) **meta.portalUrl** `string` The full portal URL with token — redirect the user here ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/auth/portal-token" \ -H "x-public-key: pk_live_..." \ -H "Content-Type: application/json" \ -d '{ "externalTenantId": "workspace_123", "returnUrl": "https://app.com/settings/billing" }' ``` ```json 201 theme={null} { "success": true, "data": { "token": "eyJhbGciOiJIUzI1NiJ9...", "expiresAt": "2025-01-01T00:10:00Z" }, "meta": { "portalUrl": "https://portal.crovver.com/billing?token=eyJhbGci...", "expiresIn": 600 } } ``` ```json 404 Tenant not found theme={null} { "success": false, "data": null, "error": { "message": "Tenant not found. Use the checkout flow to create a subscription first.", "code": "TENANT_NOT_FOUND" } } ``` # Get Credit Balance Source: https://docs.crovver.com/api-reference/credits/balance GET /api/public/credits/balance Fetch the current credit balance for all pools on a tenant's active subscription. Returns a breakdown of base (plan-included) and add-on credits remaining per pool, along with expiry and limit info. Returns an empty object `{}` if the tenant has no active subscription. ## Query Parameters **tenantId** `string` *required* The external tenant ID from your application **productSlug** `string` Scope the lookup to the tenant's active subscription for this product (e.g. `ats`). A tenant holds at most one active subscription per product, so this is the recommended way to disambiguate multi-product tenants. Without it, the most recently created active subscription is used. **subscriptionId** `string` Scope the lookup to an exact subscription ID. Takes effect together with `productSlug` if both are passed (they must refer to the same subscription). **publicKey** `string` Your public key (`pk_live_...`). Alternative to the `Authorization` bearer header — use one or the other. ## Authentication Requires one of: * **Bearer header** — `Authorization: Bearer sk_live_...` (secret key, server-side) * **Query param** — `?publicKey=pk_live_...` (public key, client-side) ## Response Returns an object keyed by `pool_key`. **data.\[poolKey].poolKey** `string` The pool key (e.g. `api_calls`, `ai_tokens`) **data.\[poolKey].displayName** `string` Human-readable pool name **data.\[poolKey].baseRemaining** `integer` Credits remaining from the plan's base allocation **data.\[poolKey].addonRemaining** `integer` Credits remaining from add-on purchases **data.\[poolKey].total** `integer` Total remaining credits (`baseRemaining + addonRemaining`) **data.\[poolKey].limit** `integer` The pool's `limit_per_period` as defined on the plan **data.\[poolKey].limitBehavior** `string` `hard` or `soft` — whether the pool blocks consumption at zero or allows overage **data.\[poolKey].nextExpiry** `string | null` ISO timestamp of the earliest upcoming credit expiry, or `null` if none **data.\[poolKey].usagePercent** `integer` Percentage of credits consumed so far (`0–100`) ```bash cURL (public key) theme={null} curl "https://app.crovver.com/api/public/credits/balance?tenantId=workspace_123&publicKey=pk_live_..." ``` ```bash cURL (secret key) theme={null} curl "https://app.crovver.com/api/public/credits/balance?tenantId=workspace_123" \ -H "Authorization: Bearer sk_live_..." ``` ```json 200 theme={null} { "success": true, "data": { "api_calls": { "poolKey": "api_calls", "displayName": "API Calls", "baseRemaining": 850, "addonRemaining": 500, "total": 1350, "limit": 1000, "limitBehavior": "soft", "nextExpiry": "2025-02-01T00:00:00Z", "usagePercent": 15 } } } ``` ```json 200 No active subscription theme={null} { "success": true, "data": {} } ``` # Consume Credits Source: https://docs.crovver.com/api-reference/credits/consume POST /api/public/credits/consume Deduct credits from a tenant's credit pool. Idempotent. Deducts credits from a tenant's pool. Credits are deducted FIFO — base credits first, then add-on credits, earliest-expiry first. Passing the same `idempotencyKey` twice returns the original result without double-deducting. ## Request Body **tenantId** `string` *required* The external tenant ID from your application (e.g. `workspace_123`) **poolKey** `string` *required* The credit pool to deduct from (e.g. `api_calls`, `ai_tokens`). Must match a pool defined on the tenant's active plan. **amount** `integer` *required* Number of credits to consume. Must be a positive integer. **idempotencyKey** `string` *required* Unique key for this consumption event. Duplicate calls with the same key return the original result — no double deduction. **productSlug** `string` Scope consumption to the tenant's active subscription for this product (e.g. `ats`). A tenant holds at most one active subscription per product, so this is the recommended way to disambiguate multi-product tenants. Without it, the most recently created active subscription is used. **subscriptionId** `string` Scope consumption to an exact subscription ID. Takes effect together with `productSlug` if both are passed (they must refer to the same subscription). **metadata** `object` Optional context stored on the event for auditing (e.g. `{ "endpoint": "/api/export", "userId": "u_123" }`). ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ## Response **data.result** `string` Outcome: `allowed`, `warning`, or `blocked`. * `allowed` — credits deducted successfully * `warning` — credits deducted, but this pool only tracks usage and is now over its allowance * `blocked` — not enough credits on a pool that blocks; nothing was deducted, and `remaining` is what is still left **data.remaining** `integer` Credits remaining in the pool after this deduction. **data.alreadyProcessed** `boolean` `true` if this `idempotencyKey` was already processed. No deduction occurred on this call. **data.poolKey** `string` The pool key that was targeted. ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/credits/consume" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "tenantId": "workspace_123", "poolKey": "api_calls", "amount": 1, "idempotencyKey": "consume-1778423112701", "metadata": { "endpoint": "/api/export" } }' ``` ```typescript Node.js theme={null} const res = await fetch("https://app.crovver.com/api/public/credits/consume", { method: "POST", headers: { "Authorization": "Bearer sk_live_...", "Content-Type": "application/json", }, body: JSON.stringify({ tenantId: "workspace_123", poolKey: "api_calls", amount: 1, idempotencyKey: `consume-${Date.now()}`, }), }); const { data } = await res.json(); if (data.result === "blocked") { // hard limit hit — surface upgrade prompt } ``` ```json 200 Allowed theme={null} { "success": true, "data": { "result": "allowed", "remaining": 849, "alreadyProcessed": false, "poolKey": "api_calls" } } ``` ```json 200 Blocked (asked for 50, 12 left) theme={null} { "success": true, "data": { "result": "blocked", "remaining": 12, "alreadyProcessed": false, "poolKey": "api_calls" } } ``` ```json 200 Already processed theme={null} { "success": true, "data": { "result": "allowed", "remaining": 849, "alreadyProcessed": true, "poolKey": "api_calls" } } ``` ```json 402 No active subscription theme={null} { "success": false, "data": null, "error": { "message": "No active subscription found for this tenant", "code": "NO_SUBSCRIPTION" } } ``` # Check Feature Access Source: https://docs.crovver.com/api-reference/features/can-access POST /api/public/can-access Check if a tenant has access to a specific feature or has an active subscription for a product. Returns whether the tenant's active plan includes the requested feature. For multi-product orgs, pass `productSlug` to scope the check to a specific product's subscription. If the feature is backed by a credit pool, also returns the available credit balance. ## Request Body **requestingEntityId** `string` *required* The external tenant ID from your application **featureKey** `string` The feature key to check (must match a key in `plan.features`). Optional when `productSlug` is provided — omitting it performs a **subscription-existence check** (returns `true` if the tenant has any active/trial subscription for that product). **productSlug** `string` Scope the check to a specific product (e.g. `product-a`). Required for multi-product orgs. At least one of `featureKey` or `productSlug` must be provided. **amount** `integer` For credit-backed features: number of credits needed. Defaults to `0` (balance check only). ## Authentication Requires a **public key** (`x-public-key: pk_live_...`) or **secret key** (`Authorization: Bearer sk_live_...`). ## Response **data.canAccess** `boolean` Whether the tenant can access the feature or has an active subscription for the product **data.featureKey** `string` Echoed feature key (absent when only `productSlug` was provided) **data.productSlug** `string` Echoed product slug (when provided) **data.requestingEntityId** `string` The tenant ID that was checked **data.credits** `object` Only present when the feature maps to a credit pool. **available** `integer` Credits remaining in the pool **sufficient** `boolean` Whether available credits meet the requested `amount` ```bash Feature check (single-product) theme={null} curl -X POST "https://app.crovver.com/api/public/can-access" \ -H "x-public-key: pk_live_..." \ -H "Content-Type: application/json" \ -d '{ "requestingEntityId": "workspace_123", "featureKey": "advanced-analytics" }' ``` ```bash Feature check scoped to a product theme={null} curl -X POST "https://app.crovver.com/api/public/can-access" \ -H "x-public-key: pk_live_..." \ -H "Content-Type: application/json" \ -d '{ "requestingEntityId": "workspace_123", "featureKey": "advanced-analytics", "productSlug": "product-a" }' ``` ```bash Subscription-existence check (no featureKey) theme={null} curl -X POST "https://app.crovver.com/api/public/can-access" \ -H "x-public-key: pk_live_..." \ -H "Content-Type: application/json" \ -d '{ "requestingEntityId": "workspace_123", "productSlug": "product-a" }' ``` ```json 200 Has Access theme={null} { "success": true, "data": { "canAccess": true, "featureKey": "advanced-analytics", "requestingEntityId": "workspace_123" } } ``` ```json 200 Scoped to product theme={null} { "success": true, "data": { "canAccess": true, "featureKey": "advanced-analytics", "productSlug": "product-a", "requestingEntityId": "workspace_123" } } ``` ```json 200 Subscription-existence check theme={null} { "success": true, "data": { "canAccess": true, "productSlug": "product-a", "requestingEntityId": "workspace_123" } } ``` ```json 200 No Access theme={null} { "success": true, "data": { "canAccess": false, "featureKey": "advanced-analytics", "requestingEntityId": "workspace_123" } } ``` # API Reference Source: https://docs.crovver.com/api-reference/overview Complete reference for the Crovver API. ## Base URL ``` https://app.crovver.com ``` Every endpoint in this reference lives under `/api/public/`. ## Authentication Every endpoint needs a key. See [Authentication](/authentication/overview) for details. ```bash theme={null} # Public key: browser, React SDK. Only the endpoints listed on the Public keys page. x-public-key: pk_live_... # Secret key: your backend. Every endpoint. Authorization: Bearer sk_live_... ``` A public key sent to a secret-key endpoint is refused with `401`, including in the `Authorization` header. ## Response Format All responses follow this envelope: ```json theme={null} { "success": true, "data": { ... }, "error": null, "meta": { ... } } ``` ### Error Response ```json theme={null} { "success": false, "data": null, "error": { "message": "Human-readable error message", "code": "ERROR_CODE" } } ``` ## Common Error Codes | Code | HTTP | Description | | - | - | - | | `MISSING_PUBLIC_KEY` | 400 | `publicKey` query param not provided | | `INVALID_PUBLIC_KEY` | 401 | Public key not found or inactive | | `TENANT_NOT_FOUND` | 404 | No tenant with the given external ID | | `NO_SUBSCRIPTION` | 402 | The customer has no live subscription, on credit endpoints | | `SUBSCRIPTION_ENDING` | 409 | Checkout for a product whose canceled subscription is still in its paid period | | `CURRENCY_NOT_SUPPORTED` | 422 | The plan or add-on has no price in that currency | | `MISSING_REQUIRED_FIELDS` | 400 | Required body/query params missing | # List Plans Source: https://docs.crovver.com/api-reference/plans/list GET /api/public/plans Get every plan your organization currently sells. Returns every published plan of every published product in your organization. Use it to build your own pricing page. Drafts, archived plans and hidden plans are not listed. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). Call it from your backend. The hosted pricing page needs no call from you. ## Query Parameters **productSlug** `string` Only list the plans of this product. ```bash cURL theme={null} curl "https://app.crovver.com/api/public/plans" \ -H "Authorization: Bearer sk_live_..." ``` ```json 200 theme={null} { "success": true, "data": { "plans": [ { "id": "plan_starter", "name": "Starter", "description": "For small teams", "pricing": { "interval": "monthly", "isSeatBased": false, "currency": "USD", "amount": null }, "prices": [], "seatTiers": [], "trial": { "days": 0, "available": false }, "features": { "basic-analytics": true }, "creditPools": [], "product": { "id": "prod_abc", "name": "My SaaS", "description": null, "type": "b2b" }, "paymentProviders": [{ "provider_type": "stripe", "is_active": true }], "isFree": true, "isSeatBased": false, "test_mode": false }, { "id": "plan_pro", "name": "Pro", "description": "For growing teams", "pricing": { "interval": "monthly", "isSeatBased": true, "currency": "USD", "basePrice": 29, "includedSeats": 5, "perSeatPrice": 5, "minSeats": 1, "maxSeats": null }, "prices": [ { "currency": "USD", "amount": null, "basePrice": 29, "perSeatPrice": 5 }, { "currency": "NPR", "amount": null, "basePrice": 3900, "perSeatPrice": 675 } ], "seatTiers": [], "trial": { "days": 14, "available": true }, "features": { "basic-analytics": true, "advanced-analytics": true }, "creditPools": [ { "poolKey": "api_calls", "displayName": "API Calls", "limitPerPeriod": 10000, "refillBehavior": "reset", "rolloverCap": null, "limitBehavior": "hard" } ], "product": { "id": "prod_abc", "name": "My SaaS", "description": null, "type": "b2b" }, "paymentProviders": [{ "provider_type": "stripe", "is_active": true }], "isFree": false, "isSeatBased": true, "test_mode": false } ], "organization": { "id": "uuid", "name": "My SaaS", "type": "b2b" } } } ``` Prices are numbers in the currency's normal unit: `29` means 29.00. A free plan has `isFree: true`, no `prices`, and `pricing.amount: null`. Extra billing periods and country prices set in the dashboard are not listed here. `seatTiers` lists the seat bands of a [tiered plan](/concepts/plans#plan-types), for every currency, ordered by currency then `minQuantity`: ```json theme={null} "seatTiers": [ { "currency": "USD", "minQuantity": 1, "maxQuantity": 10, "price": "80.00" }, { "currency": "USD", "minQuantity": 11, "maxQuantity": 50, "price": "250.00" }, { "currency": "USD", "minQuantity": 51, "maxQuantity": null, "price": "400.00" } ] ``` Each band's `price` (a two-decimal string) is the whole period's price for any seat count from `minQuantity` to `maxQuantity`; `null` marks the open top band. A tiered plan has `basePrice` and `perSeatPrice` of 0, and checkout refuses a seat count no band holds with `422 NO_BAND_FOR_QUANTITY`. `seatTiers` is `[]` for every other plan. > [!NOTE] > > `plans[].product.type` (`b2b` or `d2c`) is the customer type of the plan's product, and decides whether checkout keys > the tenant on `externalTenantId` or `externalUserId`. `organization.type` is **deprecated**: one organization may sell > both kinds of product, so it carries the products' shared type, and `b2b` when they differ. The 2.0.0 SDKs no longer expose it. # List Supported Providers Source: https://docs.crovver.com/api-reference/providers/supported GET /api/public/supported-providers The payment providers Crovver supports, with their currencies and capabilities. Lists every payment provider Crovver supports, whether or not your organization has connected it. Use it if you build your own pricing page and want to offer only the providers that handle a currency. No key is needed. ```bash cURL theme={null} curl "https://app.crovver.com/api/public/supported-providers" ``` ```typescript Node.js theme={null} const { providers } = await crovver.getSupportedProviders(); ``` ```json 200 theme={null} { "success": true, "data": { "providers": [ { "id": "018f3a0e-d4cb-44b9-ae0e-391e698090f2", "code": "stripe", "name": "Stripe", "description": "Global payment processor with full subscription support, webhooks, and automatic billing.", "supportsRecurringBilling": true, "supportsWebhooks": true, "capabilities": { "recurring": true, "one_time": true, "refunds": true } }, { "id": "0b68ccbd-6f2d-4552-ab2c-0c684ca069e1", "code": "connectips", "name": "ConnectIPS (NCHL)", "supportsRecurringBilling": false, "supportsWebhooks": false, "capabilities": { "recurring": false, "one_time": true, "currencies": ["NPR"] } } ] } } ``` Each provider also carries setup notes for the dashboard. Only `code`, `name` and `capabilities` matter to your app. # Cancel Subscription Source: https://docs.crovver.com/api-reference/subscriptions/cancel POST /api/public/subscriptions/{subscriptionId}/cancel Cancel an active subscription. Cancels a subscription. For **recurring** (Stripe-managed) subscriptions, the status moves to `pending_cancel` and access continues until the end of the current billing period. For **manual** billing subscriptions, the status moves to `canceled` immediately. ## Path Parameters **subscriptionId** `string` *required* The Crovver subscription ID ## Request Body **externalTenantId** `string` *required* The external tenant ID from your application. Used to verify the subscription belongs to this tenant. **reason** `string` *required* Cancellation reason. One of: `too_expensive`, `missing_features`, `switching_provider`, `not_using`, `other` **feedback** `string` Optional free-text feedback from the user ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/subscriptions/56e0d8e3-6731-4b1c-b01a-73b561b1cd47/cancel" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "externalTenantId": "workspace_123", "reason": "too_expensive", "feedback": "Would come back at a lower price point" }' ``` ```json 200 Recurring subscription (access continues until period end) theme={null} { "success": true, "data": { "subscriptionId": "56e0d8e3-6731-4b1c-b01a-73b561b1cd47", "status": "pending_cancel", "canceledAt": "2026-05-18T12:00:00Z", "currentPeriodEnd": "2026-06-10T05:12:21.000Z" } } ``` ```json 200 Manual billing subscription (canceled immediately) theme={null} { "success": true, "data": { "subscriptionId": "56e0d8e3-6731-4b1c-b01a-73b561b1cd47", "status": "canceled", "canceledAt": "2026-05-18T12:00:00Z", "currentPeriodEnd": "2026-06-10T05:12:21.000Z" } } ``` ```json 400 Already canceled theme={null} { "success": false, "error": { "message": "Subscription is already canceled or pending cancellation", "code": "ALREADY_CANCELED" } } ``` # List Subscriptions Source: https://docs.crovver.com/api-reference/subscriptions/list GET /api/public/subscriptions A customer's live subscriptions, with each plan's features and credit allowances. Returns the customer's subscriptions that are `trial`, `active` or `past_due`, plus canceled ones still inside their paid period (`pending_cancel`). A customer holds at most one per product. ## Query Parameters **requestingEntityId** `string` *required* Your ID for the customer: the `externalTenantId`, or the user ID for a D2C customer. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl "https://app.crovver.com/api/public/subscriptions?requestingEntityId=workspace_123" \ -H "Authorization: Bearer sk_live_..." ``` ```typescript Node.js theme={null} const { subscriptions } = await crovver.getSubscriptions("workspace_123"); ``` ```php PHP theme={null} $result = $client->getSubscriptions('workspace_123'); ``` ```json 200 theme={null} { "success": true, "data": { "subscriptions": [ { "id": "26ddd9e7-cd75-4635-bf2a-a06986d51aba", "status": "active", "capacity": { "units": 1, "used": 0, "billing_mode": "recurring" }, "billing": { "current_period_start": "2026-10-13T18:13:55.000Z", "current_period_end": "2026-11-13T18:13:55.000Z", "next_billing_date": "2026-11-13T18:13:55.000Z" }, "trial": { "is_active": false, "ends_at": null }, "plan": { "id": "56bf4835-e69f-4580-8df5-ee546b26be23", "name": "Starter", "pricing": { "currency": "USD", "interval": "monthly", "isSeatBased": false, "amount": 29 }, "features": { "basic-reporting": true, "data-export": true }, "creditPools": [ { "pool_key": "api_calls", "display_name": "API calls", "limit_per_period": 1000, "refill_behavior": "reset", "limit_behavior": "hard" } ] }, "product": { "name": "Acme Workspace" }, "metadata": { "provider": "stripe" } } ], "tenant": { "id": "439b8b31-19b8-4aac-bcc9-b5e98ad37a90", "external_tenant_id": "workspace_123", "name": "Acme Corp" }, "organization": { "id": "88de74e1-82dd-4920-b216-5df786ad5495", "name": "Acme Inc" } } } ``` ```json 404 theme={null} { "success": false, "data": null, "error": { "message": "Tenant not found" } } ``` # Renew Subscription Source: https://docs.crovver.com/api-reference/subscriptions/renew POST /api/public/subscriptions/renew Start the payment for the next period of a ConnectIPS subscription. Subscriptions paid through ConnectIPS do not renew on their own: one payment covers one period. This endpoint issues a renewal invoice and returns a `checkoutUrl` where the customer pays it. The subscription is extended, and its credits refilled, only once the gateway confirms the payment. Stripe subscriptions renew automatically and never need this call. Customers can also renew from their billing page. ## Request Body **externalTenantId** `string` Your ID for a B2B customer. **externalUserId** `string` Your user ID, for a D2C customer. **provider** `string` *required* `connectips`. **productSlug** `string` Which product's subscription to renew, when the customer has more than one. **periodMonths** `number` How many months to pay for. Defaults to the plan's billing period. **successUrl** `string` Where the customer lands after paying. **cancelUrl** `string` Where the customer lands if they abandon the payment. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/subscriptions/renew" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "externalTenantId": "workspace_123", "provider": "connectips", "successUrl": "https://yourapp.com/billing?renewed=1", "cancelUrl": "https://yourapp.com/billing" }' ``` ```json 200 theme={null} { "success": true, "data": { "checkoutUrl": "https://app.crovver.com/api/public/checkout/connectips/...", "invoiceId": "b3c1e0d2-...", "ref": "..." } } ``` An abandoned renewal leaves the subscription untouched. The unpaid renewal invoice is voided automatically after a while. # Get Subscription Status Source: https://docs.crovver.com/api-reference/subscriptions/status GET /api/public/subscriptions/status Get the current subscription status for a tenant. Returns the active subscription, plan details, and tenant info for the given tenant. ## Authentication Pass your public key as a query parameter (`?publicKey=pk_live_...`). No bearer token required or accepted. ## Request **publicKey** `string` *required* Your public key (`pk_live_...`) **tenantId** `string` *required* The external tenant ID from your application **productSlug** `string` Scope the lookup to a specific product (e.g. `product-a`, `product-b`). Required for multi-product orgs where a tenant holds one subscription per product. Omit for single-product orgs — returns the most recently created active subscription. ## Response **success** `boolean` **data** `object` **active** `boolean` Whether the subscription is active or trial **status** `string` One of: `active`, `trial`, `past_due`, `canceled`, `expired`, `none` **tenant** `object` **id** `string` **name** `string` **isActive** `boolean` **subscription** `object | null` **id** `string` **status** `string` **trialEndsAt** `string | null` **currentPeriodStart** `string` **currentPeriodEnd** `string` **capacityUnits** `number` Seat count (seat-based plans) **usedCapacity** `number` Active seat allocations **plan** `object | null` **id** `string` **name** `string` **productId** `string | null` ID of the product this plan belongs to **productName** `string | null` Display name of the product **productSlug** `string | null` URL-safe product identifier (e.g. `ats`). Use this to scope subsequent `can-access` calls to the same product. **billingInterval** `string` **features** `string[]` Feature keys included in this plan **isSeatBased** `boolean` **isFree** `boolean` **creditPools** `object[]` The plan's meter allowances: `poolKey`, `displayName`, `limitPerPeriod`, `refillBehavior`, `limitBehavior` ```bash Single-product org theme={null} curl "https://app.crovver.com/api/public/subscriptions/status?publicKey=pk_live_...&tenantId=workspace_123" ``` ```bash Multi-product: scope to a specific product theme={null} curl "https://app.crovver.com/api/public/subscriptions/status?publicKey=pk_live_...&tenantId=workspace_123&productSlug=product-a" ``` ```json 200 Active theme={null} { "success": true, "data": { "active": true, "status": "active", "tenant": { "id": "workspace_123", "name": "Acme Corp", "isActive": true }, "subscription": { "id": "sub_uuid", "status": "active", "trialEndsAt": null, "currentPeriodStart": "2026-05-01T00:00:00Z", "currentPeriodEnd": "2026-06-01T00:00:00Z", "capacityUnits": 10, "usedCapacity": 7 }, "plan": { "id": "plan_uuid", "name": "Growth", "productId": "prod_uuid", "productName": "Product A", "productSlug": "product-a", "billingInterval": "monthly", "features": ["basic-reporting", "data-export"], "isSeatBased": false, "isFree": false, "creditPools": [ { "poolKey": "api_calls", "displayName": "API calls", "limitPerPeriod": 10000, "refillBehavior": "reset", "rolloverCap": null, "limitBehavior": "hard" } ] } } } ``` ```json 200 No active subscription theme={null} { "success": true, "data": { "active": false, "status": "none", "tenant": { "id": "workspace_123", "name": "Acme Corp", "isActive": true }, "subscription": null, "plan": null } } ``` # Create Tenant Source: https://docs.crovver.com/api-reference/tenants/create POST /api/public/tenants Create a tenant — a workspace (B2B) or an individual customer (D2C). Creates a new billing tenant in Crovver, listed as a **Customer** in the dashboard. For a **B2B** product, call this when a new workspace/organization is created in your app. For a **D2C** product, omit `externalTenantId`: the tenant is keyed on `externalUserId`, the same row a D2C checkout creates on its own if you skip this call. ## Request Body **externalTenantId** `string` The workspace/org ID from your application. Omit it for a D2C customer: the tenant is keyed on `externalUserId`. **name** `string` *required* Display name for the tenant **externalUserId** `string` *required* The external user ID of the billing owner **ownerEmail** `string` Email address of the billing owner. It also becomes the customer's email in the dashboard; an email set there is never overwritten. **ownerName** `string` Display name of the billing owner **slug** `string` URL-friendly slug. Auto-generated from `name` if not provided. **metadata** `object` Arbitrary key-value pairs stored on the tenant. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/tenants" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "externalTenantId": "workspace_abc123", "name": "Acme Corp", "externalUserId": "user_123", "ownerEmail": "admin@acme.com", "ownerName": "Jane Smith" }' ``` ```json 201 theme={null} { "success": true, "data": { "tenant": { "id": "uuid", "externalTenantId": "workspace_abc123", "name": "Acme Corp", "slug": "acme-corp", "isActive": true, "createdAt": "2025-01-01T00:00:00Z" }, "owner": { "id": "uuid", "externalUserId": "user_123", "email": "admin@acme.com", "name": "Jane Smith" }, "message": "Tenant created successfully" } } ``` ```json 403 D2C organization theme={null} { "success": false, "error": "This endpoint is restricted to B2B organizations." } ``` ```json 409 Duplicate theme={null} { "success": false, "error": "Tenant ID or Slug already exists" } ``` # Get Tenant(s) Source: https://docs.crovver.com/api-reference/tenants/list GET /api/public/tenants Retrieve tenants for your organization. Returns tenant information in three modes depending on which query parameters you provide: * **No params** → returns all tenants in your org. * **`externalTenantId`** → returns a single tenant with its members list. * **`externalUserId`** → returns all tenants that user belongs to. ## Query Parameters **externalTenantId** `string` The tenant ID from your SaaS application. Returns a single tenant with its members. **externalUserId** `string` The user ID from your SaaS application. Returns all tenants this user belongs to. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). Public keys (`pk_*`) are **not** accepted by this endpoint. ```bash List all tenants theme={null} curl "https://app.crovver.com/api/public/tenants" \ -H "Authorization: Bearer sk_live_..." ``` ```bash Fetch by tenant ID theme={null} curl "https://app.crovver.com/api/public/tenants?externalTenantId=company_acme_123" \ -H "Authorization: Bearer sk_live_..." ``` ```bash Fetch by user ID theme={null} curl "https://app.crovver.com/api/public/tenants?externalUserId=user_admin_456" \ -H "Authorization: Bearer sk_live_..." ``` ```json 200 (all tenants / by externalUserId) theme={null} { "success": true, "data": { "tenants": [ { "id": "uuid", "externalTenantId": "company_acme_123", "name": "Acme Corporation", "slug": "acme-corp", "isActive": true, "metadata": {}, "createdAt": "2025-01-01T00:00:00Z", "updatedAt": "2025-01-01T00:00:00Z" } ], "count": 1 } } ``` ```json 200 (by externalTenantId) theme={null} { "success": true, "data": { "tenant": { "id": "uuid", "externalTenantId": "company_acme_123", "name": "Acme Corporation", "slug": "acme-corp", "isActive": true, "metadata": {}, "createdAt": "2025-01-01T00:00:00Z", "updatedAt": "2025-01-01T00:00:00Z" }, "members": [ { "externalUserId": "user_admin_456", "email": "admin@acmecorp.com", "name": "Admin User", "role": "owner" } ], "organization": { "id": "uuid", "name": "My SaaS" } } } ``` # Check Usage Limit (Deprecated) Source: https://docs.crovver.com/api-reference/usage/check-limit POST /api/public/check-usage-limit Deprecated. Use credits/balance + credits/consume instead. > [!WARNING] > > This endpoint is deprecated. It still answers from the customer's credit balance, but it has no product scoping and no idempotent counterpart. Use [`GET /api/public/credits/balance`](/api-reference/credits/balance) to read remaining credits and [`POST /api/public/credits/consume`](/api-reference/credits/consume) to deduct them. Returns the tenant's current usage for a metric and whether they're within the limit defined by their plan. ## Request Body **requestingEntityId** `string` *required* The external tenant ID **metric** `string` *required* The metric to check (e.g., `api_calls`, `storage_gb`) **productSlug** `string` Scope the check to a specific product's subscription. Required for multi-product orgs. ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/check-usage-limit" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "requestingEntityId": "workspace_123", "metric": "api_calls" }' ``` ```json 200 Within Limit theme={null} { "success": true, "data": { "allowed": true, "current": 4821, "limit": 10000, "remaining": 5179, "percentage": 48, "metric": "api_calls" } } ``` ```json 200 Over Limit theme={null} { "success": true, "data": { "allowed": false, "current": 10203, "limit": 10000, "remaining": 0, "percentage": 102, "metric": "api_calls" } } ``` # Record Usage (Deprecated) Source: https://docs.crovver.com/api-reference/usage/record POST /api/public/record-usage Deprecated. Use POST /api/public/credits/consume instead. > [!WARNING] > > This endpoint is deprecated and **usage sent to it is never counted**: it writes to a log that nothing reads, so it neither reduces a customer's allowance nor blocks them. Use [`POST /api/public/credits/consume`](/api-reference/credits/consume) instead. It deducts from the customer's credits, is idempotent through `idempotencyKey`, and returns the remaining balance in one call. Records a usage event for a tenant. Kept only so older integrations don't fail. ## Request Body **requestingEntityId** `string` *required* The external tenant ID **metric** `string` *required* The metric to record (must match a key in `plan.limits`) **value** `number` Amount to add. Defaults to `1`. **metadata** `object` Optional context (e.g., which user triggered the event) ## Authentication Requires a **secret key** (`Authorization: Bearer sk_live_...`). ```bash cURL theme={null} curl -X POST "https://app.crovver.com/api/public/record-usage" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "requestingEntityId": "workspace_123", "metric": "api_calls", "value": 1, "metadata": { "endpoint": "/api/export", "userId": "user_456" } }' ``` ```json 201 theme={null} { "success": true, "data": { "message": "Usage recorded", "metric": "api_calls", "recordedValue": 1 } } ``` # Secret keys Source: https://docs.crovver.com/authentication/api-keys Server-side keys with full access to your organization's API. A secret key gives full API access to your organization. Keep it on your servers only. ``` sk_live_ ``` ## Usage Send it as a Bearer token: ```bash theme={null} POST /api/public/tenants Authorization: Bearer sk_live_... Content-Type: application/json { "externalTenantId": "workspace_abc123", "name": "Acme Corp", "externalUserId": "user_123", "ownerEmail": "admin@acme.com" } ``` The Node and PHP SDKs take it once, when you create the client: ```typescript theme={null} const crovver = new CrovverClient({ apiKey: process.env.CROVVER_SECRET_KEY! }); ``` ## What it can do Everything the public API offers, including: * create customers * create checkout sessions * consume credits * allocate seats and create proration checkouts * cancel and renew subscriptions * list plans, subscriptions and invoices ## Keep it secret > [!WARNING] > > Never put a secret key in browser code, in an environment variable prefixed `NEXT_PUBLIC_`, or in any file that is bundled for the browser. ```bash theme={null} # server-only environment CROVVER_SECRET_KEY=sk_live_... ``` ## Creating and rotating keys In the dashboard, go to **Developers → API Keys**. A key is shown once, when it is created, so store it right away. If you lose one, create a new key and revoke the old one. # Authentication overview Source: https://docs.crovver.com/authentication/overview A public key for the browser and a secret key for your backend. Your app talks to Crovver with two kinds of key. Both are created in the dashboard under **Developers → API Keys**. | Key | Prefix | Used from | Sent as | | - | - | - | - | | Public key | `pk_live_` | The browser, through the React SDK | `x-public-key` header or `?publicKey=` | | Secret key | `sk_live_` | Your backend, through the Node or PHP SDK | `Authorization: Bearer sk_live_…` | ## Which key to use > [accordion] Calling from the browser > > Use the **public key**. It can read a customer's subscription status, check feature access and credit balances, list add-ons, and start checkout or the billing page. It cannot create customers, consume credits or cancel anything. > > ```tsx theme={null} > > ``` > [accordion] Calling from your backend > > Use the **secret key**. It can do everything the API offers. Keep it on the server only. > > ```bash theme={null} > Authorization: Bearer sk_live_… > ``` A public key sent to a backend-only endpoint is refused with `401`, even in the `Authorization` header. ## Testing Every key has the `live` prefix. Whether a payment is real depends on the payment provider credentials you connect, not on the key. To test without real charges, see [Test mode](/guides/test-mode). ## Rotating keys You can have several keys at once. To rotate one, create a new key, deploy it, then **Disable** or **Revoke** the old key. A disabled key can be enabled again. A revoked key stops working for good. # Public keys Source: https://docs.crovver.com/authentication/public-keys The browser-safe key the React SDK uses. A public key identifies your organization from browser code. It is safe to ship in your frontend bundle. ``` pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` ## What a public key can do | Endpoint | What it does | | - | - | | `POST /api/public/auth/checkout-token` | Starts hosted checkout | | `POST /api/public/auth/portal-token` | Opens the customer's billing page | | `GET /api/public/subscriptions/status` | Reads a customer's subscription status | | `POST /api/public/can-access` | Checks a feature | | `GET /api/public/credits/balance` | Reads credit balances | | `GET /api/public/tenants/{id}/addons/available` | Lists add-ons the customer can buy | | `GET /api/public/tenants/{id}/addons/active` | Lists the customer's add-on credits | Every other endpoint needs a [secret key](/authentication/api-keys) and refuses a public key with `401`. Because the browser decides which customer ID it sends, treat these reads as hints for your UI. Before doing protected work, check access again from your backend with the secret key. ## Usage The React SDK sends the key for you: ```tsx theme={null} ``` To call an endpoint directly, send it as a header or a query parameter: ```bash theme={null} GET /api/public/can-access?featureKey=data-export&requestingEntityId=workspace_123 x-public-key: pk_live_... ``` ## Billing page sign-in A public key can open the billing page for any customer ID, so the billing page asks the customer to prove who they are. It emails a one-time sign-in link to the customer's billing email before it shows invoices or allows a cancellation. You don't need to do anything for this, beyond giving each customer an email. See [Customers](/concepts/tenants#the-billing-email). ## Creating keys In the dashboard, go to **Developers → API Keys**. Your first public and secret keys are shown when you create your organization. # Add-ons Source: https://docs.crovver.com/concepts/addons Extra credits a customer buys on top of their plan. An **add-on** is something a customer buys on top of their subscription, such as an "AI Token Pack" that adds 1,000 `ai_tokens`. Use add-ons to let customers top up a metered resource without changing plan. ## How add-ons work 1. Create the add-on in your product under **Product catalog → Catalog → Add-ons**. An add-on belongs to one product. 2. Give it an **entitlement**: the meter it tops up and how much it grants. 3. Set its price in each currency you sell in. 4. Make it **compatible** with the plans that may buy it. A customer only sees add-ons compatible with their current plan. 5. Publish it. ## Fixed fee or per unit | Pricing | The customer buys | Example | | - | - | - | | **Fixed fee** | A fixed pack for one price | 1,000 tokens for \$15 | | **Per unit bought** | Any quantity, priced per unit | \$0.02 per token | ## Expiry | Setting | The add-on's credits expire | | - | - | | Ends with the billing period | At the end of the customer's current period | | Expires after a number of days | That many days after purchase | | Never expires | Never | ## Prices An add-on is bought in the currency of the customer's subscription, so give it a price in every currency your plans use. A plan can **override** an add-on's price. For example, Pro customers can pay $10 for a pack that costs $15 elsewhere. Customers on that plan are charged the override. A price of 0 is allowed. A free add-on calls no payment provider: its credits are granted at once, and the purchase returns `requiresPayment: false` with no `checkoutUrl`. ## What cannot be published yet The public API describes an add-on as one meter and one quantity. Until it can describe more, two kinds of add-on stay in draft: * an add-on that grants a **feature** instead of credits * an add-on that tops up **more than one meter** The dashboard explains the refusal when you try to publish one. ## Selling add-ons from the dashboard From a subscription in the dashboard, **Buy add-on** invoices the customer for an add-on their plan supports. The credits are granted when the invoice is paid. A free add-on is granted at once. ## Selling add-ons in your app Customers can buy add-ons on their billing page. To sell them inside your own app, use the [add-ons guide](/guides/addons). # Credits Source: https://docs.crovver.com/concepts/credits How metered allowances are granted, consumed and refilled for each customer. **Credits** are how Crovver meters usage. When a plan gives a [meter allowance](/concepts/plans#entitlements), such as 10,000 `api_calls` a month, each subscriber gets that many credits in a **pool** keyed by the meter. Your backend consumes credits as the customer uses the resource. ## Where credits come from ``` Balance = plan allowance + add-on credits ``` | Source | Granted | Expires | | - | - | - | | **Plan allowance** | When the subscription activates, then at the start of every billing period | At the end of the period | | **Add-on credits** | When an [add-on](/concepts/addons) purchase is paid, or at once if it is free | As the add-on says: end of period, after a number of days, or never | ## Refills Allowances reset at the start of every billing period: the customer gets the full allowance again, and unused plan credits are dropped. Add-on credits are not touched by a refill. A subscription paid for several periods in advance, such as a monthly plan paid a year ahead, still refills once a month. Crovver refills each period on its own schedule, so the customer never gets the whole year's credits at once. > [!NOTE] > > Pools created before the current dashboard may be set to **roll over** unused credits, up to a cap. They keep working that way. New allowances always reset. ## Consuming credits Call [`POST /api/public/credits/consume`](/api-reference/credits/consume) from your backend with a secret key: ```bash theme={null} curl -X POST "https://app.crovver.com/api/public/credits/consume" \ -H "Authorization: Bearer sk_live_..." \ -H "Content-Type: application/json" \ -d '{ "tenantId": "workspace_123", "poolKey": "ai_tokens", "amount": 50, "idempotencyKey": "gen-8f2c1e" }' ``` | Result | Meaning | | - | - | | `allowed` | Credits were deducted | | `warning` | Credits were deducted, but the pool tracks usage only and is now over its allowance | | `blocked` | Not enough credits on a pool that blocks usage. Nothing was deducted, and `remaining` says what is left | The plan allowance is used first, then add-on credits, starting with the ones that expire soonest. Every call needs an `idempotencyKey`. Sending the same key again returns the first result and deducts nothing, so retries are safe. Derive the key from the action, such as a request or job ID, never from the current time. ## Checking the balance ```bash theme={null} GET /api/public/credits/balance?tenantId=workspace_123 Authorization: Bearer sk_live_... ``` The response lists each pool with its plan credits, add-on credits, total and limit. See [Get credit balance](/api-reference/credits/balance). ## More than one product Credits belong to one subscription. If a customer holds subscriptions to two products, pass `productSlug` on balance and consume calls to choose the product. Without it, Crovver uses the customer's most recent live subscription. ## Canceled subscriptions A canceled subscription that is still inside its paid period keeps its credits until the period ends. After that, consumption returns `402 NO_SUBSCRIPTION`. > [!WARNING] > > `record-usage` and `check-usage-limit` are deprecated. `record-usage` writes to a table nothing reads, so usage recorded through it is never counted. Use `credits/consume` and `credits/balance` instead. # Entitlements Source: https://docs.crovver.com/concepts/entitlements Check if a tenant has access to a feature based on their active plan. **Entitlements** are how Crovver decides whether a customer can use a feature. Crovver finds the customer's live subscription and checks whether its plan grants the feature. ## How It Works When you call `canAccess`: 1. Crovver looks up the customer's live subscription. Pass `productSlug` if you sell more than one product. 2. It checks whether that subscription's plan grants the feature. 3. If the key is also a meter with an allowance on the plan, the customer must have credits left too. 4. It returns `canAccess: true` or `false`. | Subscription status | `canAccess` | | - | - | | `trial` or `active` | `true` when the plan grants the feature | | `pending_cancel` | `true` until the paid period ends, then `false` | | `past_due`, `canceled`, `expired`, or no subscription | `false` | Archiving a plan never removes access from its existing subscribers. > [!NOTE] > > Feature keys created in the dashboard use hyphens, such as `data-export`. Pass the key exactly as it appears under **Product catalog → Catalog → Features**. ## Checking Access — Frontend Use the `useFeatureAccess` hook: ```tsx theme={null} import { useFeatureAccess } from 'crovver-react'; function ExportButton() { const { hasAccess, redirectToUpgrade } = useFeatureAccess('data-export'); if (!hasAccess) { return ; } return ; } ``` ## Checking Access — API ```bash theme={null} POST /api/public/can-access x-public-key: pk_live_... Content-Type: application/json { "requestingEntityId": "workspace_123", "featureKey": "data-export" } ``` ```json theme={null} { "success": true, "data": { "canAccess": true, "featureKey": "data-export", "requestingEntityId": "workspace_123" } } ``` A frontend check only hides UI. Repeat the check on your backend before doing the protected work, with `canAccess` from the Node or PHP SDK and your secret key. ## Blocking UI with FeatureGuard The `` component handles the gate declaratively: ```tsx theme={null} import { FeatureGuard } from 'crovver-react'; } > ``` ## Metered / Credit-Based Limits Entitlements handle boolean feature access. For **consumable resources**, such as API calls, AI tokens or SMS messages, use credits instead: 1. **Check balance** before the action — [`GET /api/public/credits/balance`](/api-reference/credits/balance) 2. **Consume credits** after the action — [`POST /api/public/credits/consume`](/api-reference/credits/consume) (idempotent) ```bash theme={null} # 1. Read balance GET /api/public/credits/balance?tenantId=workspace_123 # 2. Consume POST /api/public/credits/consume { "tenantId": "workspace_123", "poolKey": "api_calls", "amount": 1, "idempotencyKey": "consume-1778423112701" } ``` See [Credits](/concepts/credits) for the full model. # Multi-currency Source: https://docs.crovver.com/concepts/multi-currency Sell one plan in several currencies, and re-price it for specific countries. A plan has one price per currency you sell it in. There is no base currency: USD, EUR and NPR prices of the same plan are equal peers. ``` Plan "Pro" ├── USD 29.00 ├── EUR 27.00 └── NPR 3,900.00 ``` Prices are in the currency's normal unit, not in cents: `29` means \$29.00. ## The currency is locked at subscription When a customer subscribes, the subscription takes one currency and keeps it for life. Renewals, seat changes and add-on purchases are all charged in that currency. ## How checkout picks the currency 1. The `currency` you pass to checkout, if the plan has a price in it. 2. Otherwise, the plan's first currency. A currency the plan has no price for is refused with `422 CURRENCY_NOT_SUPPORTED`. ## Per-seat plans A per-seat plan has a base price and a per-seat price in each currency: | Currency | Base price | Per extra seat | | - | - | - | | USD | 50.00 | 5.00 | | NPR | 6,000.00 | 600.00 | ## Country prices A plan can also have a different price for buyers in a specific country, in one of its currencies. For example, Pro can cost 19.00 USD for buyers in India and 29.00 USD elsewhere. A customer gets the country price when their country is set on the customer and the plan has a price for that country in the checkout currency. The country is fixed on the subscription when it is created. > [!NOTE] > > `GET /api/public/plans` and the hosted pricing page show the plan's regular price. A customer with a country price is charged the country price at checkout. ## Add-ons Add-ons are bought in the subscription's currency, so give each add-on a price in every currency your plans use. A plan can override an add-on's price per currency. See [Add-ons](/concepts/addons#prices). ## Payment providers by currency | Currency | Providers | | - | - | | USD, EUR and other card currencies | Stripe | | NPR | ConnectIPS | ## Setting prices Set a plan's currencies and country prices in its **Set price** flow, under **Product catalog**. Set an add-on's prices on the add-on, and a plan's overrides on the plan's **Compatible add-ons** card. # Organizations Source: https://docs.crovver.com/concepts/organizations Your company's account in Crovver, which owns everything else. An **organization** is the account you create when you sign up for Crovver. It represents your company. It owns your products and plans, your payment provider connections, your API keys, your team and your customers. ## What belongs to an organization ``` Organization ├── Products ← what you sell, each B2B or D2C │ └── Plans ← prices and entitlements ├── Features and meters ← what plans grant ├── Add-ons ← extras sold on top of a plan ├── Payment providers ← Stripe, ConnectIPS ├── API keys and webhooks ← how your app talks to Crovver ├── Team ← people who use the dashboard └── Customers ← your customers └── Subscriptions ← what each customer pays for ``` ## B2B or D2C is set per product Whether your customers are companies or individuals is a property of each **product**, not of the organization. One organization can sell a B2B product and a D2C product side by side. See [Products](/concepts/products). ## Your team Invite teammates under **Settings → Team**. Each member has a role that decides what they can see and change in the dashboard. A member can belong to more than one organization and switch between them from the sidebar. ## API keys Every organization has two kinds of key: | Key | Prefix | Where it lives | | - | - | - | | Public key | `pk_live_` | Your frontend, through the React SDK | | Secret key | `sk_live_` | Your backend only | Crovver shows both keys once, when they are created. Manage them under **Developers → API Keys**. See [Authentication](/authentication/overview). ## Your Crovver subscription Your organization subscribes to Crovver itself, the same way your customers subscribe to you. The dashboard asks you to choose a Crovver plan before it opens, and you manage it from **Settings → Billing**. # Plans Source: https://docs.crovver.com/concepts/plans What a customer pays and what they get, inside one product. A **plan** belongs to one [product](/concepts/products). It has a **price**, which says what the customer pays, and **entitlements**, which say what the customer gets. You build both in the dashboard, under **Product catalog**, with the plan's **Set price** flow. ## Plan types | Type | What the customer pays | Payment provider | | - | - | - | | **Free** | Nothing | None. The subscription activates at once. | | **Flat Rate** | A fixed price every billing cycle | Required | | **Per Seat** | A base price that covers a number of seats, plus a price for each extra seat | Required | A per-seat plan counts seats with a **provisioned meter**, such as `seats`, that you pick in the flow. Its price is: ``` total = base price + max(0, seats − included seats) × price per extra seat ``` For example, a base of $50 that includes 5 seats, plus $10 per extra seat, costs \$80 for 8 seats. A per-seat plan can instead be priced in **tiers**: bands of seats, each with one flat price for the whole period. The price is the band that holds the seat count, not seats × a rate: | Band | Price per period | | - | - | | 1–10 seats | \$80 | | 11–50 seats | \$250 | | 51+ seats | \$400 | So 11 seats cost $250, and 40 seats cost $250 too. The bands must start at 1 and end with an open top band. The plans API lists them in `seatTiers`, and a tiered plan's `basePrice` and `perSeatPrice` are 0. See [Seat-based billing](/guides/seat-based-billing#tiered-seat-pricing). ## Billing period, trial and currencies * **Billing period**: monthly or annual. The flow also lets you list extra periods with a discount. Checkout and renewals currently charge the plan's main period only. * **Free trial**: a number of days before the first charge. A subscription in trial has full access. * **Currencies**: give the plan a price in each currency you sell in. You can also re-price it for buyers in specific countries. See [Multi-currency](/concepts/multi-currency). ## Entitlements Entitlements are what a plan grants. There are two kinds: **Features** are on/off. A plan either grants `advanced-reporting` or it doesn't. Your app checks them with [`canAccess`](/concepts/entitlements). **Meter allowances** give the customer a quantity of a metered meter each billing period, such as 10,000 `api_calls`. Each allowance has an enforcement setting: | Enforcement | When the allowance runs out | | - | - | | **Block** | Further consumption is refused with `blocked` | | **Track** | Consumption still succeeds and returns `warning`, so you can alert or bill for it yourself | Allowances reset to the full amount at the start of every billing period. Unused credits do not carry over. See [Credits](/concepts/credits). ## Feature and meter keys The key is what your code passes to Crovver, so it must match exactly. | Kind | Format | Example | | - | - | - | | Feature | lowercase letters, digits and single hyphens | `advanced-reporting` | | Meter | lowercase letters, digits and single underscores | `api_calls` | A key cannot be changed after it is created. Plans created before the current dashboard may use older keys, and those keep working exactly as they are. ## Visibility A plan can be hidden from customers. A hidden plan is not listed on the pricing page or by `GET /api/public/plans`. Use it for deals you set up by hand from the dashboard. ## Changing a plan that has subscribers Once a plan has subscribers, its pricing is locked, so nobody is silently charged a new price. To change the price, create a new plan, publish it and archive the old one. Existing subscribers stay on the old plan and keep renewing. ## Lifecycle Plans are drafts until published, and only a published plan of a published product is sold. See [Products](/concepts/products#lifecycle-draft-published-archived). # Products Source: https://docs.crovver.com/concepts/products The things you sell, each with its own plans, type and lifecycle. A **product** is one thing you sell, such as "Acme Workspace" or "Acme Analytics". Every plan belongs to exactly one product. Most companies start with one product. Add more when parts of your app are bought separately. ## Product type: B2B or D2C Each product has a type that decides who the customer is: | Type | The customer is | How a customer is created | | - | - | - | | **B2B** | A company or workspace. Many of your users can share one subscription. | Your backend creates it with [`createTenant`](/api-reference/tenants/create) when a workspace is created in your app. | | **D2C** | An individual user, who is their own customer. | The first checkout creates it from the signed-in user. You can also create it ahead with `createTenant`. | You choose the type when you create the product. It is fixed once the product has a subscription. ## The product slug Each product has a **slug**, such as `acme-workspace`. If you sell more than one product, pass it as `productSlug` to scope a call to one product: * the hosted pricing page shows only that product's plans * `canAccess`, credit balances and credit consumption look only at that product's subscription A customer can hold one live subscription per product, so a customer can subscribe to two products at once. ## Lifecycle: draft, published, archived Products, plans and add-ons share one lifecycle: | Status | Listed and sold? | Existing subscribers | | - | - | - | | **Draft** | No. Invisible to the API, the pricing page and checkout. | Not applicable | | **Published** | Yes | Keep access | | **Archived** | No. Stops new sales. | Keep their subscription and access, and still renew | Publishing a product publishes all of its draft plans with it, in one step. If any draft plan has no price yet, nothing is published and the dashboard names the plan to fix. Unarchiving returns an item to draft, so it is reviewed before it is sold again. > [!WARNING] > > A plan is only sold when both the plan **and** its product are published. If a plan is missing from the pricing page or `GET /api/public/plans`, check both statuses first. # Subscriptions Source: https://docs.crovver.com/concepts/subscriptions A customer's binding to a plan, from checkout to renewal and cancellation. A **subscription** links one customer to one plan. It records the billing period, the currency, the seat count and the payment state. A customer can hold one live subscription per [product](/concepts/products). Every change is written to the subscription's activity history, which you can see in the dashboard. ## How a subscription starts | Path | How it activates | | - | - | | **Checkout, free plan** | At once. No payment provider is involved. | | **Checkout, Stripe** | When Stripe confirms the payment. Stripe then renews and charges it automatically. | | **Checkout, ConnectIPS** | When Crovver verifies the payment with the gateway. ConnectIPS does not renew on its own: the customer pays each period through a renewal. | | **Created in the dashboard** | **Subscriptions → Create subscription** creates it without checkout, for customers you invoice yourself, for example by bank transfer. You record its payments against its invoices in the dashboard. | The currency is fixed when the subscription is created and never changes. ## Statuses | Status | Meaning | Has access | | - | - | - | | `pending` | Created, waiting for the first payment | No | | `trial` | In a free trial | Yes | | `active` | Paid and current | Yes | | `past_due` | A renewal payment failed | No | | `pending_cancel` | Canceled, but the paid period has not ended | Yes, until the period ends | | `canceled` | Ended | No | | `expired` | Ended without being renewed | No | ## Renewal * **Stripe** subscriptions renew automatically. Each successful payment starts a new period and refills the plan's credits. * **Gateway and dashboard** subscriptions renew through a renewal invoice. The period is extended when that invoice is paid. * A subscription can be **paid ahead** for several periods, for example a monthly plan paid for a year. Credits still refill once per period. They are not granted all at once. ## Cancellation | Billing | What cancel does | | - | - | | Stripe | The subscription becomes `pending_cancel` and keeps access until the end of the period already paid. Stripe does not charge again. | | Gateway or dashboard | The subscription is `canceled` at once. | The customer can cancel from their billing page. You can cancel from the dashboard or from your backend with [`POST /api/public/subscriptions/{id}/cancel`](/api-reference/subscriptions/cancel). ## Changing plans There is no in-place plan change yet. To move a customer to another plan of the same product, cancel the current subscription, then start a new one through checkout. While a canceled Stripe subscription is still in its paid period, checkout refuses a new subscription for the same product with `409 SUBSCRIPTION_ENDING`. The customer can subscribe again once that period ends. > [!WARNING] > > Canceling a gateway or dashboard subscription ends it at once, and the unused part of the period is not credited back. ## Checking status On the frontend, use the React SDK: ```tsx theme={null} import { useSubscription } from "crovver-react"; function Dashboard() { const { isActive, subscription } = useSubscription(); if (!isActive) return ; return ; } ``` On your backend, list a customer's subscriptions with the Node or PHP SDK's `getSubscriptions`, or call [`GET /api/public/subscriptions/status`](/api-reference/subscriptions/status). To react to changes as they happen, register a webhook endpoint. See [Outgoing webhooks](/guides/outgoing-webhooks). # Customers (tenants) Source: https://docs.crovver.com/concepts/tenants The billing unit that subscribes to a plan. The API calls it a tenant. A **customer** is whoever pays you: a workspace for a B2B product, or a person for a D2C product. The dashboard calls them **Customers**. The API and SDKs call them **tenants**. They are the same thing. ## Customer, not user Crovver does not know about the individual users inside a workspace. It only knows the billing unit. Your app decides which of its users belong to which customer. | Product type | A customer is | Example | | - | - | - | | B2B | A company, workspace or team | "Acme Corp" | | D2C | One person | Jane's personal account | ## Your ID for the customer Every customer carries **your** ID for it, the `externalTenantId`, such as your workspace ID. You pass that ID on every call: to `CrovverProvider` as `tenantId`, to `canAccess`, to checkout and to credits. Crovver never asks you to store its own IDs. ## Creating customers **B2B:** create the customer from your backend when a workspace is created in your app. Then it exists with the right name and owner before it ever reaches checkout. If you skip this, the first checkout through the React SDK creates it from the provider's `tenantName`, `userId` and `metadata.userEmail`. ```typescript theme={null} await crovver.createTenant({ externalTenantId: "workspace_abc123", name: "Acme Corp", externalUserId: "user_123", // the billing owner in your app ownerEmail: "admin@acme.com", ownerName: "Jane Smith", }); ``` **D2C:** the first checkout creates the customer from the signed-in user, keyed on the user's ID. You can also create it ahead of time with `createTenant` and no `externalTenantId`. ## The billing email A customer's email is where Crovver sends billing messages, and it is how the customer signs in to their billing page. Before the billing page shows invoices or lets anyone cancel, it emails a one-time sign-in link to that address. Set the email when the customer is created: pass `ownerEmail` to `createTenant`, or let the first checkout create the customer with the user's email. You or your team can also set it on the customer in the dashboard. An email added later from the browser, to a customer that was created without one, is stored but not trusted for sign-in. Otherwise anyone holding your public key could attach their own address to a customer. For a customer that already exists without one, set the email in the dashboard, under **Customers**. > [!WARNING] > > A customer with no billing email cannot open their billing page. Always pass the owner's email when you create a customer. ## Owner The **owner** is the person in your app responsible for paying, identified by your user ID, `externalUserId`. For a D2C customer, the owner is the customer. ## When a customer counts as subscribed A customer is subscribed while it has a subscription in `trial` or `active`, or a canceled one still inside its paid period. `useSubscription().isActive` tells your frontend. # Add-ons Source: https://docs.crovver.com/guides/addons Let tenants purchase extra credit packs on top of their subscription. Add-ons are extra credits a customer buys on top of their subscription, for example to top up AI tokens without changing plan. You create add-ons in the dashboard and mark which plans they are compatible with. See [Add-ons](/concepts/addons). Customers can buy them on their billing page without any work from you. To sell them inside your own app, use the three endpoints below. ## 1. Show Available Add-ons Fetch the add-ons this customer can buy: those compatible with their current plan, priced in their subscription's currency. Call it with the public key from your frontend, or the secret key from your backend. ```bash theme={null} GET /api/public/tenants/{tenantId}/addons/available x-public-key: pk_live_... ``` ```json theme={null} { "success": true, "data": [ { "id": "addon_abc", "display_name": "AI Token Pack", "description": "500 extra AI tokens", "pool_key": "ai_tokens", "credit_qty": 500, "expiry_type": "days", "expiry_days": 30, "currency": "USD", "amount": 15, "current_balance": 250, "pool_limit": 1000 } ] } ``` `amount` is in the currency's normal unit: 15 means 15.00. If the customer's plan overrides the add-on's price, `amount` is the override. `current_balance` is what the customer already has in that pool, useful for showing "you have X left". ## 2. Initiate a Purchase Call this from your **backend** with the secret key. It returns a `checkoutUrl` where the customer pays. ```bash theme={null} POST /api/public/tenants/{tenantId}/addons/purchase Authorization: Bearer sk_live_... { "addonId": "addon_abc", "currency": "USD", "idempotencyKey": "purchase_workspace123_addon_abc_1717842000", "successUrl": "https://app.com/billing?success=1", "cancelUrl": "https://app.com/billing" } ``` ```json theme={null} { "success": true, "data": { "purchaseId": "purchase_xyz", "checkoutUrl": "https://checkout.stripe.com/...", "requiresPayment": true, "addonName": "AI Token Pack", "creditQty": 500, "amount": 15, "currency": "USD" } } ``` Redirect the customer to `checkoutUrl`. The credits are granted once the payment is confirmed. Crovver also sends an `addon.purchased` webhook. A free add-on, priced at 0, needs no payment. The response has `requiresPayment: false` and `checkoutUrl: null`, and the credits are already granted. For an add-on priced per unit, pass `qty` with the number of units, within the add-on's `min_qty` and `max_qty`. > [!WARNING] > > Use a unique `idempotencyKey` per purchase attempt. Passing the same key twice returns the original result without creating a duplicate charge. ## 3. Check Active Add-on Credits Fetch the customer's remaining add-on credits, not counting the plan's allowance. The public key works here too. ```bash theme={null} GET /api/public/tenants/{tenantId}/addons/active x-public-key: pk_live_... ``` ```json theme={null} { "success": true, "data": [ { "pool_key": "ai_tokens", "addon_remaining": 500, "active_addon_grants": 1, "next_addon_expiry": "2025-07-08T00:00:00Z" } ] } ``` Use this to show tenants how many add-on credits they have and when they expire. ## Currency Matching A customer can only buy an add-on in **the same currency as their subscription**. Pass that `currency` in the purchase request. Any other currency returns `422`. # Checkout flow Source: https://docs.crovver.com/guides/checkout-flow How a customer subscribes, from your Upgrade button to an active subscription. There are two ways to start a checkout: * **Hosted pricing page**: your frontend sends the customer to Crovver's pricing page, where they pick a plan and pay. This needs only the React SDK. * **Backend checkout**: your backend creates a checkout for a plan you choose and redirects the customer to pay. Use this when you build your own pricing page. ## Hosted pricing page ```mermaid theme={null} flowchart TD A["Customer clicks Upgrade"] --> B["React SDK requests a checkout token\nwith your public key"] B --> C["Browser goes to Crovver's pricing page"] C --> D["Customer picks a plan"] D --> E{"Free plan?"} E -- yes --> F["Subscription is active at once"] E -- no --> G["Customer pays on Stripe or a local gateway"] G --> H["Crovver confirms the payment\nand activates the subscription"] F --> I["Customer returns to your app"] H --> I ``` ### 1. Send the customer to the pricing page ```tsx theme={null} import { useBillingRedirect } from "crovver-react"; const { redirectToCheckout } = useBillingRedirect(); redirectToCheckout(); // every published plan redirectToCheckout({ productSlug: "acme-workspace" }); // one product's plans redirectToCheckout({ requiredFeature: "data-export" }); // pre-select a plan with this feature ``` The SDK asks Crovver for a short-lived checkout token, valid for 10 minutes, and redirects to the pricing page with it. The token carries your organization and the customer, so the page shows your published plans. If the customer does not exist yet, this first checkout creates it from the provider's `tenantId`, `tenantName`, `userId` and `metadata.userEmail`. ### 2. The customer picks a plan and pays * **Free plan**: the subscription is active immediately. No payment provider is involved. * **Stripe**: the customer pays on Stripe's checkout page. Crovver activates the subscription when Stripe confirms the payment, usually within seconds. * **ConnectIPS**: the customer pays on the gateway's page, then comes back. Crovver confirms the payment with the gateway before activating. ### 3. The customer comes back The customer lands on Crovver's confirmation page, then returns to your app. Refresh the subscription when they arrive: ```tsx theme={null} const { refresh, isActive } = useSubscription(); useEffect(() => { refresh(); }, []); ``` Don't treat the return itself as proof of payment. Rely on `isActive`, `canAccess`, or the `subscription.activated` [webhook](/guides/outgoing-webhooks). ## Backend checkout Create the checkout from your backend with the secret key, then redirect the customer to the returned URL: ```typescript theme={null} const checkout = await crovver.createCheckoutSession({ externalTenantId: "workspace_123", externalUserId: "user_123", userEmail: "jane@acme.com", planId: "6f1c…", // the plan's ID from getPlans() provider: "stripe", successUrl: "https://yourapp.com/billing/success", cancelUrl: "https://yourapp.com/pricing", }); // crovver-node 1.8.0's types don't include the free-plan fields yet const result = checkout as typeof checkout & { isFree?: boolean; successUrl?: string }; if (result.isFree) { redirect(result.successUrl!); // already active } else { redirect(result.checkoutUrl!); // pay first } ``` For a per-seat plan, pass the seat count as `totalCapacityUnits`. For a D2C product, omit `externalTenantId`: the customer is keyed on `externalUserId`. A free plan needs no `provider`. Its response has `isFree: true` and a `successUrl` instead of a `checkoutUrl`. ## When checkout is refused | Response | Why | | - | - | | `409` | The customer already has a live subscription to this product. Cancel it first. See [Changing plans](/concepts/subscriptions#changing-plans). | | `409 SUBSCRIPTION_ENDING` | The customer canceled a subscription to this product that is still in its paid period. They can subscribe again when it ends. | | `404` | The plan does not exist, or it or its product is not published. | | `422 CURRENCY_NOT_SUPPORTED` | The plan has no price in the requested currency. | ## The billing page Once subscribed, customers manage billing on Crovver's billing page: invoices, cancellation, seats and add-ons. Send them there with `redirectToBilling()` from `useBillingRedirect`. The first time a customer opens the billing page in a browser, Crovver emails a one-time sign-in link to the customer's billing email. The link is valid for 15 minutes, and the sign-in lasts 7 days in that browser. A customer without a billing email sees a message asking them to contact you, so always set one. See [Customers](/concepts/tenants#the-billing-email). Checkout itself never asks for this sign-in. # Credits Source: https://docs.crovver.com/guides/credits *** title: Credits description: Track and gate metered feature usage with Crovver credit pools. ---------------------------------------------------------------------------- Credits let you meter consumable resources, such as AI tokens, SMS messages or API calls, against a customer's plan. Crovver tracks the balance, refills it every billing period, and refuses consumption on an allowance that blocks once it runs out. ## 1. Check a Tenant's Credit Balance Call this from your frontend with the public key, or from your backend with the secret key. ```bash theme={null} # Frontend GET /api/public/credits/balance?tenantId=workspace_123 x-public-key: pk_live_... # Backend GET /api/public/credits/balance?tenantId=workspace_123 Authorization: Bearer sk_live_... ``` ```json theme={null} { "success": true, "data": { "ai_tokens": { "poolKey": "ai_tokens", "displayName": "AI Tokens", "baseRemaining": 750, "addonRemaining": 500, "total": 1250, "limit": 1000, "limitBehavior": "hard", "nextExpiry": "2025-02-01T00:00:00Z", "usagePercent": 0 } } } ``` `baseRemaining` comes from the plan allocation; `addonRemaining` comes from purchased add-on packs. Use `total` for display and gating. > [!NOTE] > > **Multi-product tenants:** if your org sells multiple products, a tenant can hold one active subscription per product. Pass `productSlug` (on both `credits/balance` and `credits/consume`) to target the right product's pools — e.g. `?tenantId=workspace_123&productSlug=ats`. Without it, the tenant's most recently created active subscription is used. ## 2. Consume Credits Call this from your **backend** after the tenant performs a metered action. Requires a secret key. ```bash theme={null} POST /api/public/credits/consume Authorization: Bearer sk_live_... { "tenantId": "workspace_123", "poolKey": "ai_tokens", "amount": 50, "idempotencyKey": "req_abc123" } ``` ```json theme={null} { "success": true, "data": { "result": "allowed", "remaining": 1200, "alreadyProcessed": false, "poolKey": "ai_tokens" } } ``` | `result` | Meaning | | - | - | | `allowed` | Credits were deducted | | `warning` | Credits were deducted, but this pool only tracks usage and is now over its allowance | | `blocked` | Not enough credits on a pool that blocks. Nothing was deducted, and `remaining` says what is left | > [!WARNING] > > Pass one `idempotencyKey` per action, derived from something stable such as a request or job ID. Sending the same key again returns the first result and deducts nothing, so retries are safe. ## 3. Gate actions before consuming To refuse an action before doing the work, read the balance first and compare `total` with what the action will cost. Then consume once the work is done. On a pool that blocks, `consume` still refuses if the balance ran out in between, so the balance check is only for a better user experience. > [!WARNING] > > `check-usage-limit` and `record-usage` are deprecated. Usage sent to `record-usage` is never counted. Use `credits/balance` and `credits/consume`. ## Limit behaviors | `limitBehavior` | Set in the dashboard as | What happens when credits run out | | - | - | - | | `hard` | Block | `consume` returns `blocked` and deducts nothing. Block the action | | `soft` | Track | `consume` deducts and returns `warning`. Warn the user, alert yourself or bill it yourself | ## When Credits Refill Base credits refill automatically at the start of each billing period — you never trigger a refill manually. Add-on credits expire on their own schedule, set by the add-on's `expiry_type` (`period`, `days`, or `never`). **When** the refill happens depends on how the subscription is billed: | Billing | When base credits are granted | | - | - | | Provider-billed (Stripe) | On each successful charge, alongside `subscription.renewed` | | Manual, renewed on time or late | At payment, before `subscription.renewed` is sent | | Manual, renewed **early** | Not at payment — later, at each window boundary | > [!WARNING] > > Paying a manual renewal **early** extends the period without granting credits yet. The contract now > covers several credit windows, and each is granted at its own boundary — so the > `subscription.renewed` you receive at payment time carries **pre-refill** balances. > > Each later grant arrives as its own > [`credits.refilled`](/guides/outgoing-webhooks#credits-refilled) event. If you mirror balances in > your own database, sync from that event rather than from the renewal. A late renewal grants one window, not the whole gap. It does not back-fill unpaid months. Older pools set to roll over still carry their unused balance forward across the lapse, up to their cap. > [!NOTE] > > Reading `qty_granted` from a webhook payload? It is the **contract-lifetime total**, not the current > window's grant, so it will usually far exceed the balance. See > [Credit Balances](/guides/outgoing-webhooks#credit-balances). # Multi-Currency Pricing Source: https://docs.crovver.com/guides/multi-currency Accept payments in multiple currencies without duplicating your plans. Crovver lets a single plan carry prices in multiple currencies. The tenant's currency is chosen at checkout and locked for the lifetime of their subscription — all renewals and add-on purchases use the same currency automatically. ## How It Works You set per-currency prices on each plan in the dashboard, for example USD paid through Stripe and NPR paid through ConnectIPS. As a SaaS developer, the only thing you need to do is pass the correct `currency` and `provider` when creating a checkout session. ## Initiating Checkout in a Specific Currency ```bash theme={null} POST /api/public/checkout Authorization: Bearer sk_live_... { "externalTenantId": "workspace_123", "externalUserId": "user_123", "planId": "6f1c…", "currency": "NPR", "provider": "connectips", "successUrl": "https://app.com/welcome", "cancelUrl": "https://app.com/pricing" } ``` If you omit `currency`, Crovver uses the plan's first currency. If you pass a currency that has no price configured, you'll get a `422 CURRENCY_NOT_SUPPORTED` error. ## Currency is Locked After Checkout Once a tenant subscribes, their currency cannot change. You don't need to track or pass currency for subsequent API calls — Crovver resolves it from the subscription automatically. This also applies to add-on purchases: a customer on an NPR subscription can only buy add-ons that have an NPR price. ## Checking Supported Providers by Currency Different providers support different currencies. You can ask Crovver which providers it supports: ```bash theme={null} GET /api/public/supported-providers ``` The hosted pricing page already offers the right providers. You only need this if you build your own pricing page. Use this to show only relevant payment options in your UI before redirecting to checkout. # Outgoing Webhooks Source: https://docs.crovver.com/guides/outgoing-webhooks Receive real-time subscription events on your own server. Crovver can push subscription lifecycle events to HTTP endpoints you register. When a subscription is created, activated, renewed, or canceled — whether triggered manually from your dashboard or by a payment provider — Crovver signs a JSON payload and POSTs it to every active endpoint you've configured. ## Setting Up an Endpoint 1. Go to **Developers → Webhooks** in your Crovver dashboard. 2. Click **Add endpoint**. 3. Enter your HTTPS URL, such as `https://api.your-app.com/webhooks/crovver`. 4. Copy the signing secret. **It is shown only once and cannot be retrieved again.** An endpoint receives every event type. Ignore the types you don't need. The URL must be reachable from the public internet. Addresses on private networks, loopback and cloud metadata addresses are refused, both when you save the endpoint and when Crovver delivers to it. Redirects are not followed. Your endpoint must respond with a `2xx` status within **5 seconds**. Any other response or a timeout counts as a failed delivery and is retried. See Delivery & Retries below. ## Event Envelope Every event shares the same top-level structure: ```json theme={null} { "id": "a1b2c3d4-e5f6-...", "type": "subscription.activated", "created_at": "2026-06-07T10:00:00.000Z", "org_id": "org_...", "data": { "id": "sub_...", "status": "active", "plan_id": "plan_...", "billing_mode": "recurring", "external_tenant_id": "your_user_id_123", "tenant_name": "Acme Corp", "plan_name": "Business", "product_name": "Acme ATS", "product_slug": "acme-ats", "current_period_start": "2026-06-07T00:00:00Z", "current_period_end": "2026-07-07T00:00:00Z", "capacity_units": 5, "created_at": "2026-06-01T00:00:00Z", "updated_at": "2026-06-07T10:00:00Z" } } ``` > [!NOTE] > > `data.external_tenant_id` is the ID you provided when creating the tenant — use this to identify the user or workspace in your own system. `data.tenant_name` is the human-readable name for quick identification. Every event that names a subscription also carries the plan and product it belongs to, so you never have to resolve a UUID to route the event: | Field | Use | | - | - | | `plan_name` | Human-readable plan, e.g. `Business` | | `product_name` | Human-readable product | | `product_slug` | Stable machine identifier — **key your routing on this**, not the display names | > [!TIP] > > If you sell more than one product, `product_slug` is what disambiguates an event. Two products > can define the same credit `pool_key`, so a `credits.refilled` naming only the pool is not enough > on its own to decide which product's balance moved. ## Events Reference | Event | When it fires | | - | - | | `subscription.created` | A subscription is created from the dashboard | | `subscription.activated` | A subscription goes live for the first time — a Stripe checkout completes, a ConnectIPS payment is verified, or an invoice is marked paid | | `subscription.updated` | Status, billing period, or seat count changes | | `subscription.renewed` | A recurring billing cycle payment succeeds and the period advances | | `subscription.canceled` | Subscription is canceled by an admin, the tenant, or the payment provider | | `subscription.expiring` | A subscription's period ends within 7 days and it will not auto-renew — see [Expiry warnings](#expiry-warnings) | | `credits.refilled` | A new credit window began on a contract that was already paid for — see [Credit balances](#credit-balances) | | `addon.purchased` | An add-on purchase completed and its credits were granted | | `tenant.at_risk` | Crovver's daily risk check flags a customer as likely to churn, or raises its risk level. `data` carries `tenant_id`, `risk_level`, `signals`, `mrr_amount`, `currency` and `days_until_renewal` | | `webhook.test` | Sent when you click **Send Test** from the dashboard | > [!NOTE] > > When a free trial ends and the first charge succeeds, both `subscription.updated` (status: `trial → active`) and `subscription.renewed` (payment received) fire in sequence. These represent distinct state changes — handle them independently and use the top-level `id` to deduplicate if needed. > [!NOTE] > > ConnectIPS checkouts verify the payment server-side after the > browser returns, then emit `subscription.activated` with the tenant's freshly granted credits. If > you integrated against these gateways before, note that this event is newly emitted — previously > an activation through them produced no webhook at all. > [!WARNING] > > A **free plan** checkout activates the subscription without sending `subscription.activated`. Until that is added, check the customer's status from your backend when they return from checkout. ## Expiry Warnings `subscription.expiring` is an early warning, not a state change: nothing has happened to the subscription yet. It fires for subscriptions that will lapse unless someone acts — the ones that do **not** auto-renew. A subscription is selected when all of these hold: * `current_period_end` is in the future but within **7 days** * Status is `active`, `trial`, `pending_cancel` or `past_due` * Billing is `manual` — *or* the status is `pending_cancel` (a provider-billed subscription that was already told to stop) * The plan is not free Provider-billed subscriptions are otherwise excluded, because Stripe renews them on its own. ```json theme={null} { "type": "subscription.expiring", "data": { "id": "sub_...", "tenant_id": "...", "external_tenant_id": "workspace_123", "status": "active", "billing_mode": "manual", "current_period_end": "2026-08-25T00:00:00.000Z", "capacity_units": 5, "currency": "NPR", "milestone": "expiring", "days_until_expiry": 6, "plan_name": "Seed Starter", "product_name": "Seed ATS", "product_slug": "seed-ats", "credits": [ { "pool_key": "exports", "qty_remaining": 500, "qty_granted": 1750 } ] } } ``` `days_until_expiry` is the real remaining days, so it varies run to run. `milestone` labels which warning this is; today `expiring` is the only value, reserved so additional milestones (T-3, T-1) can be added later as deliberate extra sends. > [!NOTE] > > **Sent once per subscription per period.** The dedupe key is > (subscription, period end, channel), so a subscription warned on the first daily run that sees it > is never warned again for that period — even though the 7-day window keeps matching it. Renewing > and reaching a new period end makes it eligible again. > [!TIP] > > The `credits` block tells you what balance is about to lapse alongside the period, which is what > makes this event useful in a renewal nudge rather than just a date reminder. ## Credit Balances Every event that names a subscription carries a `credits` array with the tenant's per-pool balances, so you can keep your own mirror in sync without an extra API call. ```json theme={null} "credits": [ { "pool_key": "exports", "qty_remaining": 500, "qty_granted": 1750 } ] ``` | Field | Meaning | | - | - | | `qty_remaining` | Live spendable balance right now — **this is the field to sync** | | `qty_granted` | Total ever granted for this pool on the current contract — a running audit total, **not** this window's grant | > [!WARNING] > > `qty_granted` is cumulative, so it will usually be much larger than `qty_remaining` and the two > are not meant to reconcile against each other. A pool granting 500 per window shows > `qty_granted: 1750` and `qty_remaining: 500` in its fourth window — 1,750 handed out across the > contract's history, 500 available today. To show "500 of 500 left" in your UI, compare > `qty_remaining` against the plan's per-period limit, not against `qty_granted`. Because `qty_remaining` is a full snapshot rather than a delta, **set** your stored balance from it rather than incrementing. A receiver that sets self-corrects after a missed delivery. On `addon.purchased`, the **top-level** `qty_granted` is that one purchase's delta ("this purchase added 500"), while `qty_granted` inside `credits` is the running total. ### `credits.refilled` Recurring subscriptions refill when the provider charges them, and that is already covered by `subscription.renewed`. But a **manually billed** contract can be paid for several credit windows up front — a monthly plan prepaid for a year — and those later windows open with no payment and no status change. Nothing else would tell you the credits arrived. `credits.refilled` is that signal. It fires from a scheduled job at each window boundary: ```json theme={null} { "type": "credits.refilled", "data": { "subscription_id": "...", "tenant_id": "...", "external_tenant_id": "workspace_123", "tenant_name": "Slate Consulting", "billing_period": 4, "current_period_start": "2026-04-28T15:36:25.264Z", "current_period_end": "2027-05-28T15:36:25.264Z", "reason": "period_refill", "credits": [ { "pool_key": "exports", "qty_remaining": 500, "qty_granted": 1750 } ] } } ``` `billing_period` is the window ordinal within the contract — window 4 of a prepaid year. `current_period_start` and `current_period_end` are the **contract** bounds, not the window's; a refill never moves them. It is **not** sent when the plan defines no credit pools, when a concurrent run already advanced that window, or for provider-billed subscriptions. ### Early renewals refill later, not at payment This is the case most integrations get wrong, so handle it explicitly. > [tab] Early renewal > > Paid **before** the current period ends. Crovver extends `current_period_end` and keeps the > original period start, so the contract now spans more credit windows. > > No credits are granted at payment time. The `subscription.renewed` you receive carries > **pre-refill** balances — accurate at that instant, but not the post-renewal figure. > > Each newly paid-for window is granted later, at its real boundary, and arrives as > `credits.refilled`. **Sync balances from that event, not from the renewal.** > [tab] On-time or late renewal > > Paid on or after the period end. Crovver moves both period start and end, restarting the > window schedule for the renewed contract. > > Credits refill immediately, before the webhook is dispatched — so `subscription.renewed` > carries post-refill balances and no `credits.refilled` follows. > > A late renewal does not back-fill the unpaid gap: one renewal grants one window. Rollover > pools still carry their unused balance forward across the lapse. > [!NOTE] > > Webhooks cover every grant, but not consumption — your backend drives that, and > `POST /api/public/credits/consume` returns the new `remaining` in its response. Write through > from there, set from the `credits` block on events, and read > [credit balance](/guides/credits) when you need certainty. ## Verifying Signatures Every request includes an `X-Crovver-Signature` header. **Always verify it before processing the event.** ``` X-Crovver-Signature: sha256= X-Crovver-Event: subscription.activated User-Agent: Crovver-Webhook/1.0 ``` The signature is `HMAC-SHA256` of the **raw request body** using your endpoint's signing secret. ```typescript Node.js theme={null} import crypto from "crypto"; import express from "express"; const app = express(); // Use raw body middleware — do NOT parse JSON before verifying app.post( "/webhooks/crovver", express.raw({ type: "application/json" }), (req, res) => { const sig = req.headers["x-crovver-signature"] as string; const expected = "sha256=" + crypto .createHmac("sha256", process.env.WEBHOOK_SECRET!) .update(req.body) // raw Buffer — not re-serialized JSON .digest("hex"); const valid = sig?.length === expected.length && crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected)); if (!valid) { return res.status(401).json({ error: "Invalid signature" }); } const event = JSON.parse(req.body.toString()); switch (event.type) { case "subscription.activated": // Grant access for event.data.external_tenant_id break; case "subscription.renewed": // Extend access period break; case "subscription.canceled": // Revoke access break; } // Always respond 200 quickly res.status(200).json({ received: true }); } ); ``` ```php PHP theme={null} 'Invalid signature']); exit; } $event = json_decode($payload, true); switch ($event['type']) { case 'subscription.activated': // Grant access for $event['data']['external_tenant_id'] break; case 'subscription.canceled': // Revoke access break; } http_response_code(200); echo json_encode(['received' => true]); ``` > [!WARNING] > > Always verify the signature against the **raw request body bytes** — not a re-serialized version. JSON parsers may reorder keys, which will break the HMAC comparison. ## Delivery & Retries If your endpoint is down, times out or returns a non-2xx status, Crovver retries the delivery automatically. Retries wait 1 minute, 5 minutes, 30 minutes, 2 hours and 8 hours, so an event is attempted up to 6 times over about 11 hours. After that it stays failed. In **Developers → Webhooks**, open an endpoint to see its deliveries: * the full JSON payload that was sent * the HTTP status and response body your server returned * the attempt count and time Click **Retry** on a failed delivery to send it again by hand. It keeps the same `id`, so your server can deduplicate. > [!TIP] > > Use the top-level `id` field as an idempotency key. Store processed event IDs and skip duplicates. Retries mean the same event can arrive more than once. ## Testing Locally Open an endpoint and use **Send Test** to send a sample event of the type you pick, or a `webhook.test` event. The delivery and its payload appear in the endpoint's deliveries at once. Test deliveries are not retried. To receive events on your local machine, expose it with a tunneling tool like [ngrok](https://ngrok.com): ```bash theme={null} ngrok http 3000 # → https://abc123.ngrok-free.app ``` Register the generated HTTPS URL as your endpoint — e.g. `https://abc123.ngrok-free.app/webhooks/crovver` — then use **Send Test** to verify your handler end-to-end before deploying. ## Security Notes | Concern | How it's handled | | - | - | | Signature forgery | HMAC-SHA256 per-endpoint secret — compare with `timingSafeEqual` | | Secret exposure | Signing secret shown once at creation, never returned again | | Sensitive fields | Provider IDs, admin-only fields, and internal credentials are stripped from all payloads | | Delivery errors | Never surface to the API caller — your subscription action always completes regardless | # Seat-based billing Source: https://docs.crovver.com/guides/seat-based-billing Charge B2B customers per seat, and prorate when a team grows mid-period. Seat-based billing charges a workspace for the seats it holds. Crovver tracks who holds a seat and prorates the charge when a customer adds seats partway through a billing period. ## 1. Create a per-seat plan In the dashboard, open your product's plan and choose **Set price → Per Seat**: 1. Pick the **provisioned meter** that counts seats, such as `seats`. Create it first under **Product catalog → Catalog → Meters**, with the source set to provisioned. 2. Set the **provisioned quantity**: the seats included in the base price. 3. Under **Per user**, set the base price and the price for each extra seat. **Pricing example:** a base of $50 for 10 seats, plus $5 per extra seat. | Seats | Price | | - | - | | 8 | \$50 | | 15 | $50 + 5 × $5 = \$75 | | 25 | $50 + 15 × $5 = \$125 | ### Tiered seat pricing Choose **Tiered** instead of **Per user** to price seats in bands. Each band has one flat price for the whole period, whatever the seat count inside it: | Seats | Band | Price | | - | - | - | | 8 | 1–10 | \$80 | | 11 | 11–50 | \$250 | | 40 | 11–50 | \$250 | | 60 | 51+ | \$400 | The plans API returns the bands in `seatTiers`, one list per currency. Price a plan at a seat count with the SDK's `planPeriodCharge(plan, seats)` (Node) or `$plan->periodCharge($seats)` (PHP) instead of reading `perSeatPrice`, which is 0 on a tiered plan. ## 2. Check out with a seat count On the hosted pricing page, the customer picks the number of seats. For a backend checkout, pass `totalCapacityUnits`: ```bash theme={null} POST /api/public/checkout Authorization: Bearer sk_live_... { "externalTenantId": "workspace_123", "externalUserId": "user_123", "planId": "6f1c…", "provider": "stripe", "totalCapacityUnits": 20, "successUrl": "https://app.com/welcome", "cancelUrl": "https://app.com/pricing" } ``` ## 3. Assign seats to users Tell Crovver which of your users hold a seat. Each call is keyed on the workspace, `requestingEntityId`: ```bash theme={null} POST /api/public/capacity/bulk-allocate Authorization: Bearer sk_live_... { "requestingEntityId": "workspace_123", "users": [ { "externalUserId": "user_123", "email": "jane@acme.com" }, { "externalUserId": "user_456", "email": "sam@acme.com" } ] } ``` List who holds a seat with [`GET /api/public/capacity/allocations`](/api-reference/capacity/allocations), and how many are used with [`GET /api/public/capacity/count`](/api-reference/capacity/count). ## 4. Add seats mid-period, with proration When a workspace needs more seats than it pays for: ```bash theme={null} POST /api/public/capacity/proration-checkout Authorization: Bearer sk_live_... { "externalTenantId": "workspace_123", "newCapacity": 30, "successUrl": "https://app.com/settings?upgraded=1", "cancelUrl": "https://app.com/settings/seats" } ``` Crovver charges only for the remaining days of the current period and returns a `checkoutUrl`. After payment, the subscription's seat count rises to the new number. From the next period on, the customer pays the full price for the new seat count. On a tiered plan, the charge is the step between the two bands for the days left: going from 10 to 11 seats halfway through a month on the ladder above charges ($250 − $80) × ½ = \$85. A new seat count that stays in the current band costs nothing now. It applies at once, and the response has `requiresPayment: false`, `prorationId: null` and no `checkoutUrl`. Seat counts only go up mid-period. To lower them, renew at the smaller count. Customers can also add seats themselves on their billing page. # Test mode Source: https://docs.crovver.com/guides/test-mode Run the full checkout and billing flow without real charges. Whether a payment is real depends on the payment provider credentials your organization is connected to. Crovver keys always start with `pk_live_` and `sk_live_`, so there is no separate test key to switch to. ## Use a separate test organization The simplest setup keeps test data apart from production: 1. Create a second organization, such as "Acme (test)". You can switch between organizations from the dashboard sidebar. 2. Build the same products and plans there. Use the same feature and meter keys as production, so your code works against both. 3. Connect Stripe with your **Stripe test keys** (`sk_test_…` and `pk_test_…`). 4. Use that organization's public and secret keys in your development and staging environments. Checkouts in the test organization go through Stripe's test mode, so no card is charged. When you go live, swap in the production organization's keys. ## Stripe test cards | Card number | Result | | - | - | | `4242 4242 4242 4242` | Payment succeeds | | `4000 0000 0000 0002` | Card declined | | `4000 0025 0000 3155` | Requires 3D Secure | | `4000 0000 0000 9995` | Insufficient funds | Use any future expiry date and any 3-digit CVC. ## Stripe webhooks while testing Crovver registers its Stripe webhook when you connect your test keys, so test payments activate subscriptions on their own. Nothing runs on your machine for this. If the provider card shows **Webhook setup needed**, add the endpoint by hand. See [Payment provider webhooks](/guides/webhooks#do-i-need-to-configure-anything). ## Receiving Crovver's webhooks locally To receive [outgoing webhooks](/guides/outgoing-webhooks) on your laptop, expose your local server with a tunnel such as ngrok, and register the tunnel's HTTPS URL as an endpoint in the test organization. ## Free plans and manual subscriptions You don't need a payment provider to test everything else. A free plan activates at once at checkout. From the dashboard you can also create a subscription for a test customer directly, with **Subscriptions → Create subscription**, then exercise feature gates, credits and seats against it. # Webhooks Source: https://docs.crovver.com/guides/webhooks How Crovver handles payment provider events to keep subscriptions in sync. Crovver automatically registers and handles webhook events from your payment provider. When you connect a provider in the Crovver dashboard, the webhook endpoint is registered for you — no manual setup in Stripe required. ## How It Works When you connect a payment provider in **Settings → Connections → Payment Providers**, Crovver registers its webhook endpoint with that provider automatically. All subscription lifecycle events flow through Crovver's webhook handler, which keeps your subscription states up to date. ## Events Processed | Event | What Crovver Does | | - | - | | `checkout.session.completed` | Activates subscription (`pending` → `active` or `trial`) | | `customer.subscription.created` | Links provider subscription ID to Crovver record | | `customer.subscription.updated` | Handles trial end and cancel-at-period-end | | `customer.subscription.deleted` | Cancels subscription | | `invoice.payment_succeeded` | Renews billing period | | `invoice.payment_failed` | Moves subscription to `past_due` | ## Idempotency Crovver deduplicates webhook events using the provider event ID. Replaying events is safe. ## Do I need to configure anything? Usually not. Crovver registers its webhook with Stripe when you connect, and stores the signing secret itself. If Stripe refuses the registration, the connection still succeeds and the provider card shows **Webhook setup needed** with Crovver's webhook URL. Then: 1. In the Stripe dashboard, go to **Developers → Webhooks** and add an endpoint with that URL. 2. Select the six events in the table above. 3. Copy the endpoint's signing secret, `whsec_…`, and paste it into the provider card in Crovver. Until this is done, Crovver cannot see Stripe's payment events, so Stripe subscriptions do not activate or renew. ## ConnectIPS ConnectIPS does not send webhooks. The customer is redirected back after paying, and Crovver confirms the payment with the gateway server to server before activating anything. Its success and failure URLs must be registered with NCHL. The provider card shows both after you connect. Payments that are abandoned midway are checked again later and settled or voided automatically. ## Webhooks to your own app This page covers the events Crovver receives from payment providers. To receive Crovver's own events in your app, such as a subscription starting or renewing, see [Outgoing webhooks](/guides/outgoing-webhooks). # What is Crovver? Source: https://docs.crovver.com/introduction Subscription infrastructure for SaaS — without building it yourself. Crovver is a **subscription management layer** that sits between your SaaS application and your payment providers. It handles billing logic, subscription state, feature entitlements, seat tracking, and usage limits — so you don't have to. ## Why Crovver? Building billing is slow, fragile, and a distraction from your core product. Crovver gives you: > [card] Payment Provider Agnostic > > Use Stripe, or ConnectIPS for NPR, without changing your > application code. > [card] Entitlement Engine > > Gate features by plan in one line. No custom permission logic needed. > [card] Seat-Based Billing > > Built-in capacity tracking with proration on upgrades. Works for B2B > workspaces out of the box. > [card] Metered Credits > > Give each plan an allowance of API calls, AI tokens or messages. Crovver > meters it, refills it every period and blocks usage when it runs out. ## How It Works Crovver exposes a set of APIs your app calls, a React SDK for the frontend, and a webhook receiver for payment provider events. Your app never talks to Stripe directly — Crovver does. ```mermaid theme={null} flowchart LR App["Your SaaS App"] --> API["Crovver API"] API --> Provider["Stripe / ConnectIPS"] SDK["React SDK (browser)"] --> API ``` **Crovver never stores payment credentials.** All provider secrets are managed through a secrets manager (Infisical or Vault). ## Key Primitives | Concept | Description | | - | - | | **Organization** | Your company, which owns everything else | | **Product** | Something you sell, to companies (B2B) or individuals (D2C) | | **Plan** | A price, plus the features and meter allowances it grants | | **Customer** | Who pays you: a workspace or a person. The API calls it a tenant | | **Subscription** | A customer subscribed to a plan | | **Entitlement** | Whether a customer can use a feature | | **Credits** | A customer's remaining allowance on a meter | ## Next Steps > [card] [Quickstart](/quickstart) > > Get your first subscription running in under 10 minutes. > [card] [Core Concepts](/concepts/organizations) > > Understand the data model before you integrate. > [card] [React SDK](/react-sdk/installation) > > Add paywalls and feature gates to your frontend. > [card] [API Reference](/api-reference/overview) > > Full reference for every endpoint. # Node.js SDK Source: https://docs.crovver.com/node-sdk/installation Integrate Crovver into your Node.js backend. ## Installation ```bash theme={null} npm install crovver-node # or pnpm add crovver-node # or yarn add crovver-node ``` **Requirements:** Node.js 18+. TypeScript is optional but fully supported. ### Upgrading to 2.0 2.0 removes calls that were deprecated in 1.x: * `recordUsage()`: use [`credits.consume`](#consume-credits). * `Plan.payment_providers`, `Plan.created_at` and `Plan.updated_at`: use `paymentProviders`, `createdAt` and `updatedAt`. * `organization.type` on the plans, tenant and subscriptions responses: read `plans[].product.type`. It also adds `Plan.seatTiers` and `planPeriodCharge()` for [tiered seat plans](/guides/seat-based-billing#tiered-seat-pricing), and `prorationId` on `createProrationCheckout` can be `null`. ## Initialize the Client ```typescript theme={null} import { CrovverClient } from "crovver-node"; const crovver = new CrovverClient({ apiKey: process.env.CROVVER_SECRET_KEY!, }); ``` ### Configuration Options | Option | Type | Default | Description | | - | - | - | - | | `apiKey` | string | required | Your secret API key (`sk_live_...`) | | `baseUrl` | string | `https://app.crovver.com` | Override the API URL | | `timeout` | number | `30000` | Request timeout in milliseconds | | `maxRetries` | number | `3` | Retry attempts for server errors | | `debug` | boolean | `false` | Log requests and responses | | `logger` | function | `undefined` | Custom logger: `(message, data?) => void` | ## Tenant Management ```typescript theme={null} // Create a tenant (B2B: workspace or user) const tenant = await crovver.createTenant({ externalTenantId: "workspace_abc123", name: "Acme Corp", externalUserId: "user_123", ownerEmail: "admin@acme.com", }); // Retrieve a tenant const tenant = await crovver.getTenant("workspace_abc123"); ``` The ID you pass as `externalTenantId` is your own ID for the customer. The dashboard lists the tenant under **Customers**. Pass `ownerEmail`: it becomes the customer's billing email, which the customer needs to sign in to their billing page. An email set in the dashboard is never overwritten. ## Plans ```typescript theme={null} const { plans } = await crovver.getPlans(); for (const plan of plans) { // One period's price at a seat count, by the rules Crovver charges: flat, per seat or tiered. // Amounts are in the currency's normal unit: 29 means 29.00. null = that seat count is not sold. const price = planPeriodCharge(plan, 10); console.log(`${plan.name}: ${plan.pricing.currency} ${price}/${plan.pricing.interval}`); } ``` `planPeriodCharge` is exported next to `CrovverClient` (`import { CrovverClient, planPeriodCharge } from "crovver-node"`). Use it rather than reading `perSeatPrice`, which is 0 on a tiered plan. ## Subscriptions ```typescript theme={null} const { subscriptions } = await crovver.getSubscriptions("workspace_abc123"); // status: active | trial | past_due | pending_cancel | canceled | expired console.log(subscriptions[0].status); // Cancel a subscription await crovver.cancelSubscription(subscriptionId, "workspace_abc123", "User requested cancellation"); ``` ## Feature Entitlements ```typescript theme={null} // Single-product org const canAccess = await crovver.canAccess("workspace_abc123", "advanced-analytics"); // Multi-product: scope to a specific product const canAccess = await crovver.canAccess("workspace_abc123", "advanced-analytics", "product-a"); // Subscription-existence check — does this tenant have any active sub for product-a? const hasProduct = await crovver.canAccess("workspace_abc123", undefined, "product-a"); ``` ## Credits Credits meter usage against a plan's allowances. Each pool is keyed by a meter key, such as `ai_tokens`. ### Check balance ```typescript theme={null} const balance = await crovver.credits.balance({ tenantId: "workspace_abc123" }); for (const pool of Object.values(balance)) { console.log(`${pool.poolKey}: ${pool.total} of ${pool.limit} left`); } ``` The result is keyed by pool. Each pool has `baseRemaining` (plan credits), `addonRemaining`, `total`, `limit`, `limitBehavior` and `nextExpiry`. ### Consume credits `consume` is idempotent. Sending the same `idempotencyKey` twice returns the first result and deducts nothing. ```typescript theme={null} const result = await crovver.credits.consume({ tenantId: "workspace_abc123", poolKey: "ai_tokens", amount: 50, idempotencyKey: `generate-${job.id}`, // stable per action metadata: { feature: "summarise" }, // optional }); if (result.result === "blocked") { // The allowance ran out. Nothing was deducted; result.remaining says what is left. // Offer an add-on or an upgrade. } else if (result.result === "warning") { // Deducted, but this tracked pool is now over its allowance. } ``` **`ConsumeInput` fields:** | Field | Type | Required | Description | | - | - | - | - | | `tenantId` | string | Yes | Your ID for the customer | | `poolKey` | string | Yes | The meter key, such as `ai_tokens` | | `amount` | number | Yes | Positive whole number of units to deduct | | `idempotencyKey` | string | Yes | Unique per action; prevents double deduction | | `subscriptionId` | string | No | Target one subscription, for customers with more than one | | `metadata` | object | No | Stored with the consumption event | **`ConsumeResponse` fields:** | Field | Type | Description | | - | - | - | | `result` | `"allowed" \| "warning" \| "blocked"` | Outcome of the deduction | | `remaining` | number | Credits left in the pool | | `alreadyProcessed` | boolean | `true` when the idempotency key was already seen | | `poolKey` | string | Echoed pool key | To scope a balance or consume call to one product by its slug, call the REST endpoints with `productSlug`. See [Consume credits](/api-reference/credits/consume). *** ## Add-ons Add-ons let customers buy extra credits without changing plan. ### List available add-ons ```typescript theme={null} const addons = await crovver.addons.listAvailable("workspace_abc123"); for (const addon of addons) { console.log(`${addon.display_name}: ${addon.credit_qty} credits for ${addon.currency} ${addon.amount}`); } ``` Only add-ons compatible with the customer's current plan are listed, priced in the subscription's currency. ### Purchase an add-on ```typescript theme={null} const purchase = await crovver.addons.purchase("workspace_abc123", { addonId: addon.id, currency: addon.currency, idempotencyKey: `addon-${order.id}`, successUrl: "https://yourapp.com/billing/success", cancelUrl: "https://yourapp.com/billing/cancel", }); if (purchase.requiresPayment) { // Send the customer to pay redirect(purchase.checkoutUrl!); } else { // A free add-on: the credits are already granted console.log(`${purchase.creditQty} credits added`); } ``` ### Get active add-on credits ```typescript theme={null} const active = await crovver.addons.getActive("workspace_abc123"); for (const pool of active) { console.log(`${pool.pool_key}: ${pool.addon_remaining} add-on credits left`); } ``` *** ## Seats For per-seat plans, record which of your users hold a seat, and charge for more seats when a team grows. ```typescript theme={null} // Give users seats on the customer's subscription await crovver.capacity.bulkAllocate({ requestingEntityId: "workspace_abc123", users: [ { externalUserId: "user_123", email: "jane@acme.com" }, { externalUserId: "user_456", email: "sam@acme.com" }, ], }); // List who holds a seat const allocations = await crovver.capacity.getAllocations({ requestingEntityId: "workspace_abc123" }); // Buy more seats, prorated for the rest of the period const upgrade = await crovver.createProrationCheckout({ externalTenantId: "workspace_abc123", newCapacity: 12, successUrl: "https://yourapp.com/team?seats=added", cancelUrl: "https://yourapp.com/team", }); if (upgrade.requiresPayment) redirect(upgrade.checkoutUrl!); // else: the seats applied at once. On a tiered plan, a count inside the current band costs nothing now. ``` See [Seat-based billing](/guides/seat-based-billing) for the full flow. *** ## Usage limits (deprecated) > [!WARNING] > > `checkUsageLimit` is deprecated and `recordUsage` was removed in 2.0: usage sent through it was never counted. Use [`credits.consume`](#consume-credits) and [`credits.balance`](#check-balance) instead. ```typescript theme={null} // ❌ Deprecated — use credits.balance() instead const limit = await crovver.checkUsageLimit("workspace_abc123", "api_calls"); console.log(`${limit.current} / ${limit.limit}`); ``` *** ## Checkout ```typescript theme={null} const session = await crovver.createCheckoutSession({ externalTenantId: "workspace_abc123", externalUserId: "user_123", planId: plan.id, provider: "stripe", successUrl: "https://yourapp.com/billing/success", cancelUrl: "https://yourapp.com/billing/cancel", }); // Redirect the customer to session.checkoutUrl. // For a free plan, see the checkout guide: the response carries isFree and successUrl instead. ``` ## Invoices ```typescript theme={null} const { invoices } = await crovver.getInvoices("workspace_abc123"); ``` ## Error Handling ```typescript theme={null} import { CrovverClient, CrovverError } from "crovver-node"; try { const canAccess = await crovver.canAccess("workspace_abc123", "advanced-analytics"); } catch (error) { if (error instanceof CrovverError) { error.message; // Human-readable message error.statusCode; // HTTP status code error.code; // API error code string error.isRetryable; // Whether the SDK already retried } } ``` > [!NOTE] > > 5xx errors, 429, and 408 responses are retried automatically with exponential backoff. Checkout endpoints are **never** retried to prevent duplicate charges. # PHP SDK Source: https://docs.crovver.com/php-sdk/installation Integrate Crovver into your PHP backend. ## Installation ```bash theme={null} composer require crovver/crovver-php ``` **Requirements:** PHP 8.0+, Composer. ### Upgrading to 2.0 2.0 removes `recordUsage()` and `checkUsageLimit()`, which were deprecated in 1.x and whose usage was never counted. Use [`consumeCredits()`](#credits) and `getCreditsBalance()`. It also adds `Plan::$seatTiers` and `Plan::periodCharge()` for [tiered seat plans](/guides/seat-based-billing#tiered-seat-pricing), and `ProrationCheckoutResponse::$prorationId` can be `null`. ## Initialize the Client ```php theme={null} use Crovver\CrovverClient; use Crovver\CrovverConfig; $client = new CrovverClient(new CrovverConfig( apiKey: getenv('CROVVER_SECRET_KEY'), )); ``` ### Configuration Options | Option | Type | Default | Description | | - | - | - | - | | `apiKey` | string | required | Your secret API key (`sk_live_...`) | | `timeout` | int | `30` | Request timeout in seconds | | `maxRetries` | int | `3` | Retry attempts for server errors | | `debug` | bool | `false` | Log requests and responses | | `logger` | callable | `null` | Custom logger: `fn($msg, $ctx)` | ## Tenant Management ```php theme={null} use Crovver\Types\CreateTenantRequest; // Create a tenant (B2B: workspace or user) $tenant = $client->createTenant(new CreateTenantRequest( externalTenantId: 'workspace_abc123', name: 'Acme Corp', externalUserId: 'user_123', ownerEmail: 'admin@acme.com', )); // Retrieve a tenant $tenant = $client->getTenant('workspace_abc123'); ``` The ID you pass as `externalTenantId` is your own ID for the customer. The dashboard lists the tenant under **Customers**. Pass `ownerEmail`: it becomes the customer's billing email, which the customer needs to sign in to their billing page. An email set in the dashboard is never overwritten. ## Plans ```php theme={null} $plans = $client->getPlans(); foreach ($plans->plans as $plan) { // One period's price at a seat count, by the rules Crovver charges: flat, per seat or tiered. // Amounts are in the currency's normal unit: 29 means 29.00. null = that seat count is not sold. $price = $plan->periodCharge(seats: 10); echo $plan->name . ': ' . $plan->pricing->currency . ' ' . $price . '/' . $plan->pricing->interval; } ``` Use `periodCharge()` rather than reading `perSeatPrice`, which is 0 on a [tiered plan](/guides/seat-based-billing#tiered-seat-pricing). The bands are in `$plan->seatTiers`. ## Subscriptions ```php theme={null} $result = $client->getSubscriptions('workspace_abc123'); foreach ($result->subscriptions as $sub) { echo $sub->status; // active, trial, past_due, pending_cancel, canceled, expired } ``` ## Feature Entitlements ```php theme={null} // Single-product org $canAccess = $client->canAccess('workspace_abc123', 'advanced-analytics'); // Multi-product: scope to a specific product $canAccess = $client->canAccess('workspace_abc123', 'advanced-analytics', 'product-a'); // Subscription-existence check — does this tenant have any active sub for product-a? $hasProduct = $client->canAccess('workspace_abc123', '', 'product-a'); ``` ## Credits Credits meter usage against a plan's allowances. Each pool is keyed by a meter key, such as `ai_tokens`. ### Check balance ```php theme={null} $balance = $client->getCreditsBalance('workspace_abc123'); // Keyed by pool. Each pool has baseRemaining, addonRemaining, total, limit, limitBehavior and nextExpiry. foreach ($balance as $poolKey => $pool) { echo $poolKey . ': ' . $pool['total'] . ' of ' . $pool['limit'] . ' left'; } // More than one product: choose the product's subscription by its slug $balance = $client->getCreditsBalance('workspace_abc123', productSlug: 'acme-workspace'); ``` ### Consume credits `consumeCredits` is idempotent — passing the same `$idempotencyKey` twice returns the original result without double-deducting. ```php theme={null} $result = $client->consumeCredits( tenantId: 'workspace_abc123', poolKey: 'ai_tokens', amount: 50, idempotencyKey: 'generate-' . $job->id, // stable per action metadata: ['feature' => 'summarise'], // optional ); if ($result->result === 'blocked') { // The allowance ran out. Nothing was deducted; $result->remaining says what is left. // Offer an add-on or an upgrade. } elseif ($result->result === 'warning') { // Deducted, but this tracked pool is now over its allowance. } ``` **`consumeCredits` parameters:** | Parameter | Type | Required | Description | | - | - | - | - | | `tenantId` | string | Yes | Your ID for the customer | | `poolKey` | string | Yes | The meter key, such as `ai_tokens` | | `amount` | int | Yes | Positive whole number of units to deduct | | `idempotencyKey` | string | Yes | Unique per action; prevents double deduction | | `metadata` | array\|null | No | Stored with the consumption event | | `subscriptionId` | string\|null | No | Target one subscription | | `productSlug` | string\|null | No | Target the customer's subscription to one product | **`ConsumeResponse` fields:** | Field | Type | Description | | - | - | - | | `result` | string | `"allowed"`, `"warning"` or `"blocked"` | | `remaining` | int | Credits left in the pool after deduction | | `alreadyProcessed` | bool | `true` when the idempotency key was already seen | | `poolKey` | string | Echoed pool key | *** ## Add-ons Add-ons let tenants purchase extra credit packs without changing their base plan. ### List available add-ons ```php theme={null} $addons = $client->listAvailableAddons('workspace_abc123'); foreach ($addons as $addon) { echo $addon['display_name'] . ': ' . $addon['credit_qty'] . ' credits for ' . $addon['currency'] . ' ' . $addon['amount']; } ``` ### Purchase an add-on ```php theme={null} $purchase = $client->purchaseAddon( externalTenantId: 'workspace_abc123', addonId: 'addon_uuid', currency: 'USD', idempotencyKey: bin2hex(random_bytes(16)), successUrl: 'https://yourapp.com/billing/success', cancelUrl: 'https://yourapp.com/billing/cancel', ); if ($purchase->requiresPayment) { // Send the customer to pay header('Location: ' . $purchase->checkoutUrl); exit; } else { // A free add-on: the credits are already granted echo $purchase->creditQty . ' credits added'; } ``` **`AddonPurchaseResponse` fields:** | Field | Type | Description | | - | - | - | | `purchaseId` | string | Unique purchase record ID | | `checkoutUrl` | string\|null | Where the customer pays. `null` for a free add-on | | `requiresPayment` | bool | `true` when a checkout session was created | | `addonName` | string | Display name of the add-on | | `creditQty` | int | Credits that will be added on completion | | `amount` | float | Charge amount in major currency units | | `currency` | string | Currency code (e.g. `"USD"`) | | `alreadyProcessed` | bool | `true` when the idempotency key was already seen | ### Get active add-on credits ```php theme={null} $active = $client->getActiveAddonCredits('workspace_abc123'); foreach ($active as $pool) { echo $pool['pool_key'] . ': ' . $pool['addon_remaining'] . ' add-on credits left'; } ``` *** ## Checkout ```php theme={null} use Crovver\Types\CreateCheckoutSessionRequest; $session = $client->createCheckoutSession(new CreateCheckoutSessionRequest( externalTenantId: 'workspace_abc123', planId: 'plan_pro', currency: 'USD', // optional; defaults to plan's first price successUrl: 'https://yourapp.com/billing/success', cancelUrl: 'https://yourapp.com/billing/cancel', )); // Redirect user to $session->checkoutUrl ``` ## Seat Management Use these methods on seat-based plans to track which users occupy seats. Seat allocation is for per-user billing, not credit consumption. ### Get Seat Count ```php theme={null} $count = $client->getSeatCount('workspace_abc123'); echo $count->activeCount; // Active allocated seats echo $count->capacityUnits; // Total seats in subscription echo $count->utilizationPercentage; // activeCount / capacityUnits × 100 echo $count->billingMode; // recurring | manual | free echo $count->exceeded ? 'Over limit' : 'Within limit'; ``` ### Allocate a Seat Call this when a user joins a workspace to record their seat allocation. ```php theme={null} use Crovver\Types\AllocateSeatRequest; $result = $client->allocateSeat(new AllocateSeatRequest( requestingEntityId: 'workspace_abc123', externalUserId: 'user_456', email: 'alice@acme.com', name: 'Alice', )); if ($result->success) { echo 'Seat allocated. Active seats: ' . $result->capacity->activeCount; } ``` If the workspace is at capacity and the plan is seat-based, Crovver returns a proration preview instead of allocating the seat: ```php theme={null} $result = $client->allocateSeat(new AllocateSeatRequest( requestingEntityId: 'workspace_abc123', externalUserId: 'user_789', )); if ($result->requiresProration) { // Show the user the upgrade cost before proceeding echo 'Adding this seat costs ' . $result->proration->amount . ' ' . $result->proration->currency; echo ' for ' . $result->proration->daysRemaining . ' remaining days in the billing period.'; // Then call createProrationCheckout to start payment $checkout = $client->createProrationCheckout( externalTenantId: 'workspace_abc123', newCapacity: $result->proration->newSeats, successUrl: 'https://yourapp.com/seats?upgraded=1', cancelUrl: 'https://yourapp.com/seats', ); // Redirect to $checkout->checkoutUrl } ``` #### `AllocateSeatRequest` Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `requestingEntityId` | string | yes | Your tenant/workspace ID | | `externalUserId` | string | yes | Your user ID. Must be non-empty. The call is idempotent — re-allocating the same ID updates the record rather than creating a duplicate. | | `email` | string | no | User's email for audit records | | `name` | string | no | User's display name for audit records | | `metadata` | array | no | Arbitrary key/value pairs stored with the allocation | #### `AllocateSeatResponse` Fields | Field | Type | Description | | - | - | - | | `success` | bool | `true` when a seat was recorded | | `requiresProration` | bool | `true` when capacity is full and a prorated upgrade is needed | | `requiresCheckout` | bool | `true` when proration was already confirmed but payment is still pending (rare) | | `capacity` | `AllocateSeatCapacity\|null` | Present on success: `activeCount`, `capacityUnits`, `exceeded` | | `proration` | `AllocateSeatProration\|null` | Present when `requiresProration` is true | #### `GetSeatCountResponse` Fields | Field | Type | Description | | - | - | - | | `activeCount` | int | Number of active seat allocations | | `capacityUnits` | int | Total seats included in the subscription | | `utilizationPercentage` | int | `activeCount / capacityUnits × 100` | | `billingMode` | string | `recurring`, `manual`, or `free` | | `exceeded` | bool | Whether `activeCount > capacityUnits` | ### Bulk Allocate Seats Allocate up to 100 users in one atomic call. Users beyond `capacity_units` are returned in `rejected` — no proration is triggered. Already-active users are silently skipped (idempotent). > [!WARNING] > > `bulkAllocateSeats` is **never retried automatically** to prevent duplicate allocations on network errors. ```php theme={null} use Crovver\Types\BulkAllocateSeatsRequest; use Crovver\Types\BulkAllocateSeatUser; $result = $client->bulkAllocateSeats(new BulkAllocateSeatsRequest( requestingEntityId: 'workspace_abc123', users: [ new BulkAllocateSeatUser('user_1', 'alice@acme.com', 'Alice'), new BulkAllocateSeatUser('user_2', 'bob@acme.com', 'Bob'), new BulkAllocateSeatUser('user_3', 'carol@acme.com', 'Carol'), ], metadata: ['addedBy' => 'admin_789'], // optional )); echo count($result->allocated) . ' allocated'; echo count($result->skipped) . ' skipped (already active)'; echo count($result->rejected) . ' rejected (over capacity)'; echo $result->capacity->activeCount . ' / ' . $result->capacity->capacityUnits . ' seats'; if (count($result->rejected) > 0) { // Call createProrationCheckout to upgrade capacity, then retry $result->rejected echo $result->message; } ``` Returns HTTP **207** when at least one user was rejected; **200** otherwise. #### `BulkAllocateSeatsRequest` Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `requestingEntityId` | string | yes | Your tenant/workspace ID | | `users` | `BulkAllocateSeatUser[]` | yes | Max 100 per call. Each `externalUserId` must be unique within the batch. | | `metadata` | array | no | Attached to every allocation created in this batch | #### `BulkAllocateSeatUser` Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `externalUserId` | string | yes | Your app's user ID | | `email` | string | no | User's email | | `name` | string | no | User's display name | #### `BulkAllocateSeatsResponse` Fields | Field | Type | Description | | - | - | - | | `allocated` | `string[]` | User IDs inserted this call | | `skipped` | `string[]` | Already active — not re-inserted | | `rejected` | `string[]` | Would exceed capacity — not inserted | | `capacity->activeCount` | int | Active seat count after this operation | | `capacity->capacityUnits` | int | Total seat limit on the subscription | | `message` | `string\|null` | Present when users were rejected | *** ### List Allocations Returns a paginated list of users allocated to the tenant's active subscription, along with a real-time capacity summary. ```php theme={null} // Active users, first page (defaults) $result = $client->getAllocations('workspace_abc123'); foreach ($result->allocations as $user) { echo $user->externalUserId . ' — ' . $user->email . ' (' . $user->status . ')'; echo ' since ' . $user->allocatedAt; } // Capacity summary echo $result->capacity->activeCount . ' / ' . $result->capacity->capacityUnits . ' seats'; echo $result->capacity->utilizationPercentage . '% utilized'; if ($result->capacity->exceeded) { // Prompt upgrade } // Pagination echo $result->pagination->total . ' total — page ' . $result->pagination->page . ' of ' . $result->pagination->totalPages; // Page through all users including removed $page2 = $client->getAllocations( requestingEntityId: 'workspace_abc123', status: 'all', // 'active' | 'removed' | 'all' page: 2, limit: 25, // max 100, default 50 ); ``` #### `getAllocations` Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `requestingEntityId` | string | required | Your tenant/workspace ID | | `status` | string | `'active'` | `'active'`, `'removed'`, or `'all'` | | `page` | int | `1` | 1-based page number | | `limit` | int | `50` | Page size, max 100 | #### `AllocationUser` Fields | Field | Type | Description | | - | - | - | | `externalUserId` | string | Your app's user ID | | `email` | `string\|null` | User's email | | `name` | `string\|null` | User's display name | | `status` | string | `'active'` or `'removed'` | | `allocatedAt` | string | ISO 8601 timestamp of seat assignment | | `removedAt` | `string\|null` | ISO 8601 timestamp of deallocation | | `metadata` | array | Metadata stored at allocation time | *** ### Proration Checkout Call this whenever a tenant needs more seats — proactively from a settings page, or after presenting the preview returned by `allocateSeat()`. Crovver calculates the prorated charge for the remaining days in the billing period and creates a checkout session using the same payment provider as the tenant's original subscription. ```php theme={null} $checkout = $client->createProrationCheckout( externalTenantId: 'workspace_abc123', newCapacity: 25, successUrl: 'https://yourapp.com/seats?upgraded=1', cancelUrl: 'https://yourapp.com/seats', ); if ($checkout->requiresPayment) { // Redirect to the provider's checkout page header('Location: ' . $checkout->checkoutUrl); } else { // Seat count was updated without payment (e.g. a tiered plan's count stayed inside its band) echo $checkout->message; } ``` #### `createProrationCheckout` Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `externalTenantId` | string | yes | Your tenant/workspace ID | | `newCapacity` | int | yes | The new total seat count (must exceed current `capacityUnits`) | | `planId` | string | no | Plan ID if also switching plans at the same time | | `successUrl` | string | no | Redirect URL after successful payment | | `cancelUrl` | string | no | Redirect URL if the user cancels | #### `ProrationCheckoutResponse` Fields | Field | Type | Description | | - | - | - | | `prorationId` | string\|null | Unique ID for this proration calculation; `null` when nothing is due | | `requiresPayment` | bool | `true` when a checkout session was created | | `checkoutUrl` | string\|null | Stripe checkout URL — redirect the user here when `requiresPayment` is `true` | | `prorationAmount` | float | Amount charged in the plan's currency (in major units, e.g. `17.50`) | | `prorationDetails` | array | Breakdown: `description`, `calculation` and `amount` | | `invoiceId` | string\|null | The pending invoice a Khalti, eSewa or ConnectIPS proration settles | | `message` | string | Human-readable summary of the proration | > [!NOTE] > > Proration checkout is **never** retried automatically to prevent duplicate Stripe sessions. ## Error Handling ```php theme={null} use Crovver\CrovverError; try { $result = $client->getSubscriptions('workspace_abc123'); } catch (CrovverError $e) { $e->getMessage(); // Human-readable message $e->getStatusCode(); // HTTP status code (null for network errors) $e->getErrorCode(); // API error code string $e->isRetryable(); // Whether the SDK already retried } ``` > [!NOTE] > > 5xx errors, 429, and 408 responses are retried automatically with exponential backoff. Checkout endpoints are **never** retried to prevent duplicate charges. # Quickstart Source: https://docs.crovver.com/quickstart From sign-up to a gated feature, a paid checkout and metered credits. This is the whole integration, in the order you do it. Steps 1 to 6 happen in the [Crovver dashboard](https://app.crovver.com). Steps 7 to 11 happen in your app. ## 1. Sign up and create your organization Sign up at [app.crovver.com](https://app.crovver.com) and confirm your email with the code we send. Then create your **organization**, which owns everything else: products, plans, keys, payment providers and your customers. When the organization is created, Crovver shows its **public key** (`pk_live_…`) and **secret key** (`sk_live_…`) once. Copy both before you close the dialog. You can create more keys later under **Developers → API Keys**. > [!NOTE] > > The dashboard asks you to choose a Crovver plan for your organization before it opens. ## 2. Create a product Go to **Product catalog → All Products → New product**. A product is one thing you sell, such as "Acme Workspace". Pick its type: * **B2B**: your customers are companies or workspaces. You create each customer from your backend. * **D2C**: your customers are individuals. Checkout creates the customer on first purchase. The type is fixed once the product has a subscription. The product's **slug** is what your code passes as `productSlug` if you sell more than one product. ## 3. Define features and meters Under **Product catalog → Catalog**: * **Features** are on/off capabilities, such as `advanced-reporting` or `sso`. Feature keys use lowercase letters, digits and hyphens. * **Meters** are things you count. A **metered** meter counts usage, such as `api_calls` or `ai_tokens`. A **provisioned** meter counts what a customer holds, such as `seats`. Meter keys use lowercase letters, digits and underscores. The key is what your code checks, so choose it once and keep it. It cannot be changed later. ## 4. Create plans Open your product and add a plan. **Set price** walks you through four choices: | Plan type | What the customer pays | | - | - | | **Free** | Nothing. No payment provider is involved. | | **Flat Rate** | A fixed price every billing cycle. | | **Per Seat** | A base price that covers a number of seats, plus a price per extra seat. You pick the provisioned meter that counts seats. | You can also set a monthly or annual billing period, a free trial and prices in more than one currency. In the same flow, under **Entitlements**, grant the plan its features and give it an allowance for each meter, such as 10,000 `api_calls` a month. Each allowance either **blocks** usage once it runs out or only **tracks** it. ## 5. Publish Products and plans start as **drafts**. A draft is invisible to your app: it is not listed and cannot be bought. Click **Publish** on the product. That publishes it together with all of its draft plans in one step. If any draft plan has no price yet, nothing is published and the dialog names the plan to fix. Archiving a plan or product later stops new sales only. Existing subscribers keep their subscription and access. ## 6. Connect a payment provider Go to **Settings → Connections → Payment Providers** and connect Stripe with your Stripe secret and publishable keys. Crovver stores them in a secrets manager, never in its database, and registers the Stripe webhook it needs for you. You can skip this step if you only offer free plans or subscriptions you invoice yourself. ## 7. Install the SDKs ```bash Frontend theme={null} npm install crovver-react ``` ```bash Node.js backend theme={null} npm install crovver-node ``` ```bash PHP backend theme={null} composer require crovver/crovver-php ``` Put the public key in your frontend environment and the secret key in your backend only. A secret key never goes to the browser, and a public key is refused on backend endpoints. ## 8. Create the customer from your backend For a B2B product, create a customer whenever a workspace is created in your app. Pass the billing owner's email: the customer uses it to sign in to their billing page later. ```typescript theme={null} import { CrovverClient } from "crovver-node"; const crovver = new CrovverClient({ apiKey: process.env.CROVVER_SECRET_KEY! }); await crovver.createTenant({ externalTenantId: workspace.id, // your own ID for the workspace name: workspace.name, externalUserId: owner.id, ownerEmail: owner.email, }); ``` For a D2C product you can skip this. The first checkout creates the customer from the signed-in user. ## 9. Wrap your app and gate a feature ```tsx theme={null} // app/providers.tsx import { CrovverProvider } from "crovver-react"; export function Providers({ children, workspace, user }) { return ( {children} ); } ``` ```tsx theme={null} import { FeatureGuard } from "crovver-react"; export function Reports() { return ( }> ); } ``` A customer with no subscription sees the fallback. Enforce the same check on your backend with `canAccess`, because a frontend gate alone can be bypassed. ## 10. Send customers to checkout ```tsx theme={null} import { useBillingRedirect } from "crovver-react"; export function UpgradeButton() { const { redirectToCheckout } = useBillingRedirect(); return ; } ``` The customer picks a plan on Crovver's hosted pricing page and pays. A free plan activates at once. A paid plan activates when the payment provider confirms the payment, and the customer returns to your app. See [Checkout flow](/guides/checkout-flow). ## 11. Meter usage with credits When a customer uses something you meter, consume credits from your backend. Use a stable idempotency key per action, so a retry never charges twice. ```bash theme={null} curl -X POST "https://app.crovver.com/api/public/credits/consume" \ -H "Authorization: Bearer $CROVVER_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "tenantId": "workspace_abc123", "poolKey": "api_calls", "amount": 1, "idempotencyKey": "export-7f3a9c" }' ``` A `blocked` result means the allowance ran out on a meter that blocks usage. Allowances refill at the start of each billing period. See [Credits](/guides/credits). ## Next steps > [card] [Receive webhooks](/guides/outgoing-webhooks) > > Keep your app in sync when subscriptions start, renew or end. > [card] [Test without real charges](/guides/test-mode) > > Run the whole flow against Stripe test keys. > [card] [Seat-based billing](/guides/seat-based-billing) > > Charge per seat, with proration when a team grows. > [card] [Add-ons](/guides/addons) > > Sell top-up packs on top of a plan. # FeatureGuard Source: https://docs.crovver.com/react-sdk/components/feature-guard Conditionally render content based on access to a specific feature. `` checks a feature key against the tenant's plan and renders either the protected content or a fallback. ## Usage ```tsx theme={null} import { FeatureGuard } from 'crovver-react'; }> ``` ## Props | Prop | Type | Required | Description | | - | - | - | - | | `featureKey` | `string` | ✅ | Feature to check against the tenant's plan | | `children` | `ReactNode` | ✅ | Rendered when access is granted | | `fallback` | `ReactNode` | | Rendered when access is denied | | `loadingComponent` | `ReactNode` | | Rendered while checking | | `checkRemote` | `boolean` | | When `true`, verifies access via the API instead of local context. Defaults to `false`. | ## Fallback with Upgrade CTA ```tsx theme={null} import { FeatureGuard, useBillingRedirect } from 'crovver-react'; function UpgradePrompt() { const { redirectToCheckout } = useBillingRedirect(); return (

This feature requires a higher plan.

); } }> ``` ## vs `useFeatureAccess` Use `` for **declarative** JSX gating. Use `useFeatureAccess` when you need to control behavior imperatively (e.g., disable a button, redirect programmatically). # Paywall Source: https://docs.crovver.com/react-sdk/components/paywall Block content behind an active subscription requirement. `` renders its children only when the tenant has an active subscription. Otherwise it shows a customizable upgrade prompt. ## Usage ```tsx theme={null} import { Paywall } from 'crovver-react'; ``` ## Props | Prop | Type | Default | Description | | - | - | - | - | | `children` | `ReactNode` | — | Content shown when subscribed | | `fallback` | `(redirectToCheckout: () => void) => ReactNode` | Built-in upgrade prompt | Render prop called with `redirectToCheckout` when not subscribed | | `loadingComponent` | `ReactNode` | `null` | Content shown while loading | | `autoRedirect` | `boolean` | `true` | Automatically redirect to checkout when no subscription is detected | | `style` | `CSSProperties` | — | Inline styles applied to the default paywall card | ## Custom Fallback `fallback` is a **render prop** — it receives `redirectToCheckout` so you can wire your own CTA: ```tsx theme={null} (

Subscribe to access this feature

)} >
``` ## Behavior | Subscription Status | What renders | | - | - | | Loading | `loadingComponent` | | `active` or `trial` | `children` | | `past_due`, `canceled`, `expired`, `none` | `fallback` | # SubscriptionBadge Source: https://docs.crovver.com/react-sdk/components/subscription-badge Display the current subscription status as a styled badge. `` renders a small badge showing the tenant's current subscription status. Useful in headers, settings pages, or user menus. ## Usage ```tsx theme={null} import { SubscriptionBadge } from 'crovver-react'; ``` ## Output Examples | Status | Badge | | - | - | | `active` | `Active` (green) | | `trial` | `Trial` (blue) | | `past_due` | `Past Due` (yellow) | | `canceled` | `Canceled` (red) | | `none` | `No Plan` (gray) | ## Props `` accepts no props. The plan name and badge styling are determined automatically from the tenant's active subscription. # CrovverProvider Source: https://docs.crovver.com/react-sdk/crovver-provider Root context provider that powers all SDK hooks and components. `CrovverProvider` initializes the SDK, fetches the tenant's subscription status, and makes it available to all child components via context. ## Props ```tsx theme={null} {children} ``` ### `config` | Prop | Type | Required | Default | Description | | - | - | - | - | - | | `publicKey` | `string` | ✅ | — | Your public API key (`pk_live_...`) | | `tenantId` | `string` | ✅ | — | The current user/workspace ID from your app | | `tenantName` | `string` | | — | Display name of the tenant (e.g. org or workspace name). Passed to checkout/portal so Crovver can show it in the UI | | `userId` | `string` | | — | The logged-in user's ID. Used to deduplicate tenant owner records across checkout sessions. Recommended. | | `apiUrl` | `string` | | SDK default | Override the Crovver API base URL | | `portalUrl` | `string` | | SDK default | Override the billing portal URL | | `pollInterval` | `number` | | `0` | Auto-refresh interval in ms. `0` = disabled | | `debug` | `boolean` | | `false` | Log SDK activity to the console | | `onUnauthenticated` | `() => void` | | — | Called when subscription is inactive | | `metadata.userEmail` | `string` | | — | User's email, passed to checkout/portal token requests | | `metadata.userName` | `string` | | — | User's display name, passed to checkout/portal token requests | ## Example ```tsx theme={null} router.push('/pricing'), }} > ``` ## Dynamic `tenantId` If your user can switch between workspaces, you can change `tenantId` dynamically. The provider will re-fetch the subscription for the new tenant when the value changes: ```tsx theme={null} ``` ## Server Components (Next.js) `CrovverProvider` is a client component. If your root layout is a server component, wrap the provider in a `"use client"` file: ```tsx theme={null} // components/CrovverClientProvider.tsx "use client"; import { CrovverProvider } from 'crovver-react'; export function CrovverClientProvider({ tenantId, userId, children }) { return ( {children} ); } ``` # useBillingRedirect Source: https://docs.crovver.com/react-sdk/hooks/use-billing-redirect Redirect users to checkout or the billing portal. Handles redirects to the Crovver checkout flow and billing portal. Internally calls the Crovver API to generate a short-lived JWT, then redirects the user. ## Usage ```tsx theme={null} import { useBillingRedirect } from 'crovver-react'; function UpgradeButton() { const { redirectToCheckout, isRedirecting } = useBillingRedirect(); return ( ); } ``` ## Return Value ```typescript theme={null} { redirectToCheckout: (options?: CheckoutOptions) => void; redirectToBilling: () => void; isRedirecting: boolean; } ``` > [!NOTE] > > `isRedirecting` is currently always `false`. Do not rely on it to show a loading state — both redirect functions trigger a full page navigation, so the component unmounts before any state update would take effect. ## `redirectToCheckout(options?)` Redirects the user to the Crovver pricing/checkout page. Internally: 1. Calls `POST /api/public/auth/checkout-token` with the tenant's public key 2. Receives a signed JWT token 3. Redirects to Crovver's hosted pricing page, `{portalUrl}/pricing?token={jwt}` ### Options ```typescript theme={null} { requiredFeature?: string; // Pre-selects a plan that includes this feature requiredPlan?: string; // Pre-selects a specific plan ID productSlug?: string; // Scopes the pricing page to a single product } ``` | Option | Type | Description | | - | - | - | | `requiredFeature` | `string` | Shows a banner on the pricing page indicating which feature the user needs. Does not filter plans. | | `requiredPlan` | `string` | Hints which plan the user should select. | | `productSlug` | `string` | Scopes the pricing page to only show plans for the given product. Use this in multi-product orgs where different parts of your app sell different plan sets. The slug must match a product slug configured in your Crovver org. | ### Examples ```tsx theme={null} // Basic upgrade redirectToCheckout(); // Upgrade prompted by a specific locked feature redirectToCheckout({ requiredFeature: 'advanced-analytics' }); // Redirect to a specific plan redirectToCheckout({ requiredPlan: 'plan_enterprise' }); // Scope pricing page to a single product (multi-product orgs) redirectToCheckout({ productSlug: 'marketing' }); ``` ## `redirectToBilling()` Redirects the user to the billing portal to manage their subscription (view invoices, update payment method, cancel). 1. Calls `POST /api/public/auth/portal-token` 2. Redirects to `{portalUrl}/billing?token={jwt}` ```tsx theme={null} function BillingSettings() { const { redirectToBilling } = useBillingRedirect(); return ( ); } ``` # useFeatureAccess Source: https://docs.crovver.com/react-sdk/hooks/use-feature-access Check if the current tenant has access to a specific feature or product. Checks whether the tenant's active plan includes a given feature key. Supports multi-product orgs via a `productSlug` option and an optional remote API check. ## Usage ```tsx theme={null} import { useFeatureAccess } from 'crovver-react'; function ExportButton() { const { hasAccess, isLoading, redirectToUpgrade } = useFeatureAccess('data-export'); if (isLoading) return null; return hasAccess ? : ; } ``` ## Parameters | Param | Type | Default | Description | | - | - | - | - | | `feature` | `string` | — | Feature key to check. Optional when `productSlug` is provided — omitting it performs a subscription-existence check. | | `opts.checkRemote` | `boolean` | `false` | Check via API instead of local plan data. Required when using `productSlug`. | | `opts.productSlug` | `string` | — | Scope the check to a specific product. Overrides the provider-level `productSlug` for this call. | ## Return Value ```typescript theme={null} { hasAccess: boolean; // true if the plan includes this feature canAccess: boolean; // alias for hasAccess isLoading: boolean; error: Error | null; redirectToUpgrade: () => void; refresh: () => Promise; } ``` ## How Access Is Determined By default this is a **local check** — no API call is made. The subscription data fetched by `CrovverProvider` on mount is used: 1. No active subscription → `hasAccess: false` 2. Feature not in `plan.features` → `hasAccess: false` 3. `plan.features[featureKey] === true` → `hasAccess: true` When `checkRemote: true`, the hook calls `POST /api/public/can-access` on every render cycle change, which supports `productSlug` scoping. ## Examples ### Disable a button instead of hiding it ```tsx theme={null} const { hasAccess } = useFeatureAccess('bulk_operations'); ``` ### Multi-product: scope to a specific product ```tsx theme={null} // Feature gate scoped to a product (requires remote check) const { hasAccess } = useFeatureAccess('job_posting', { checkRemote: true, productSlug: 'product-a', }); ``` ### Subscription-existence check ```tsx theme={null} // Does this tenant have any active subscription for product-a? const { hasAccess: hasProductA } = useFeatureAccess(undefined, { checkRemote: true, productSlug: 'product-a', }); ``` ### Check multiple features ```tsx theme={null} const analytics = useFeatureAccess('advanced-analytics'); const exports = useFeatureAccess('data-export'); const api = useFeatureAccess('api-access'); ``` # useSubscription Source: https://docs.crovver.com/react-sdk/hooks/use-subscription Read the current tenant's subscription status and plan. Returns the current subscription state for the tenant passed to `CrovverProvider`. ## Usage ```tsx theme={null} import { useSubscription } from 'crovver-react'; function Dashboard() { const { isActive, isLoading, plan, subscription } = useSubscription(); if (isLoading) return ; if (!isActive) return ; return (

Plan: {plan?.name}

Renews: {new Date(subscription?.currentPeriodEnd).toLocaleDateString()}

); } ``` ## Return Value ```typescript theme={null} { subscription: SubscriptionStatus | null; isLoading: boolean; error: Error | null; isActive: boolean; // true while the customer has access: "active", "trial", or canceled but still in the paid period plan: PlanDetails | null; tenant: TenantDetails | null; subscriptionDetails: SubscriptionDetails | null; refresh: () => Promise; } ``` ### `SubscriptionStatus` ```typescript theme={null} { active: boolean; status: 'active' | 'trial' | 'past_due' | 'canceled' | 'expired' | 'none'; tenant: { id: string; name: string; isActive: boolean; }; subscription: { id: string; status: string; trialEndsAt?: string; currentPeriodStart?: string; currentPeriodEnd?: string; canceledAt?: string; capacityUnits?: number; // seat count (seat-based plans) usedCapacity?: number; } | null; plan: { id: string; name: string; billingInterval: string; features: string[]; isSeatBased?: boolean; limits: Record; } | null; } ``` ## Examples ### Show trial banner ```tsx theme={null} const { subscription } = useSubscription(); const daysLeft = subscription?.subscription?.trialEndsAt ? Math.ceil((new Date(subscription.subscription.trialEndsAt).getTime() - Date.now()) / 86400000) : null; {daysLeft !== null && Trial ends in {daysLeft} days} ``` ### Manually refresh after upgrade ```tsx theme={null} const { refresh } = useSubscription(); async function onPaymentComplete() { await refresh(); // Re-fetch from Crovver API } ``` ### Gate entire pages ```tsx theme={null} const { isActive, isLoading } = useSubscription(); if (isLoading) return ; if (!isActive) redirect('/pricing'); ``` # Installation Source: https://docs.crovver.com/react-sdk/installation Add the Crovver React SDK to your app. ## Install ```bash theme={null} npm install crovver-react # or pnpm add crovver-react # or yarn add crovver-react ``` **Peer dependencies:** React 18+ or React 19+. ## Setup Wrap your application with `CrovverProvider`. In a Next.js app this goes in your root layout: ```tsx theme={null} // app/layout.tsx import { CrovverProvider } from 'crovver-react'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` > [!NOTE] > > `tenantId` is the workspace or org ID from your app — the same value you use as `externalTenantId` when creating tenants or initiating checkout. `userId` is the individual user's ID and is used to deduplicate owner records across sessions. ## Environment Variables ```bash theme={null} # .env.local NEXT_PUBLIC_CROVVER_PUBLIC_KEY=pk_live_... ``` ## What's Exported ```tsx theme={null} // Provider import { CrovverProvider } from 'crovver-react'; // Hooks import { useSubscription, useFeatureAccess, useBillingRedirect } from 'crovver-react'; // Components import { Paywall, FeatureGuard, SubscriptionBadge } from 'crovver-react'; ``` ## Next Steps > [card] [CrovverProvider](/react-sdk/crovver-provider) > > Full config reference for the provider. > [card] [useSubscription](/react-sdk/hooks/use-subscription) > > Read subscription status and plan data. > [card] [useFeatureAccess](/react-sdk/hooks/use-feature-access) > > Gate features by plan. > [card] [useBillingRedirect](/react-sdk/hooks/use-billing-redirect) > > Trigger checkout and portal redirects.