# MonetizeKit — Full LLM Corpus This document contains the concise integration brief, the complete hashed documentation index, and the normalized body of every agent-readable page. Registry SHA-256: `a79b5a0360c35bdfb0b4a05e2797b2ab6f7624347f0a55d576df5f1661b28069` --- # MonetizeKit — Agent Guide You are integrating with MonetizeKit, a monetization control plane (plans, entitlements, metering, credits, subscriptions). Use this guide to call the API. ## Base URL https://app.monetizekit.app ## Authentication All API requests require an API key via the `Authorization` header: Authorization: Bearer mk_live_xxx Create keys in the dashboard (Settings → API Keys). Keys are workspace-scoped and carry scopes (e.g. `catalog:view`, `customers:create`, `usage:write`). Requests are rate limited; responses include `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` headers. Mutations accept an `Idempotency-Key` header. ## Core REST endpoints (`/api/v1`) - Catalog (read+write): `/catalog/products`, `/catalog/meters`, `/catalog/addons`, `/catalog/promotions`, `/plans`, `/features` — GET (list), POST (create), GET/PATCH/DELETE on `/{id}`. - Customers: GET/POST `/customers`, GET/PATCH/DELETE `/customers/{id}`. - Subscriptions: POST `/subscriptions`, PATCH/DELETE `/subscriptions/{id}`. - Entitlements: GET `/entitlements/{customerId}` and `/entitlements/{customerId}/{featureKey}` (single check). - Usage: POST `/usage/events` (record), GET `/usage/{customerId}/{meterId}`. - Credits: GET `/credits/{customerId}`, POST `/credits/grant`, `/credits/debit`. - Budgets: GET/POST `/budgets`, GET/PATCH/DELETE `/budgets/{id}`. - Webhooks: GET/POST `/webhooks/endpoints`, `/webhooks/endpoints/{id}`, GET `/webhooks/deliveries`. - Contracts, integrations, members, audit, activity are also exposed under `/api/v1`. ## Discoverability - OpenAPI 3.1 spec: `GET https://app.monetizekit.app/api/v1/openapi.json` - GraphQL endpoint: `POST https://app.monetizekit.app/api/graphql` (same API-key auth) - MCP (JSON-RPC) endpoint: `POST https://app.monetizekit.app/api/mcp` - Concise agent brief: https://learning.monetizekit.app/llms.txt - Complete hashed route index: https://learning.monetizekit.app/llms-index.txt - Full normalized documentation corpus: https://learning.monetizekit.app/llms-full.txt - Task bundles: - quickstarts: https://learning.monetizekit.app/llms-bundles/quickstarts - errors: https://learning.monetizekit.app/llms-bundles/errors - webhooks: https://learning.monetizekit.app/llms-bundles/webhooks - sdk-node: https://learning.monetizekit.app/llms-bundles/sdk-node - metering: https://learning.monetizekit.app/llms-bundles/metering ## Webhooks Outbound events are signed. Verify with HMAC-SHA256 over `"{timestamp}.{rawBody}"` using your endpoint secret; compare against the `X-MonetizeKit-Signature` (`sha256=...`) header. The `@monetizekit/node` SDK exports `verifyWebhookSignature`. ## SDKs & tooling - Node SDK: `npm install @monetizekit/node` - CLI: `npm install -g @monetizekit/cli` then `mk` (catalog, customers, usage, etc.) ## Typical flow 1. Create a product, features, and a plan in the catalog. 2. Create a customer and a subscription to the plan. 3. Check entitlements: `GET /api/v1/entitlements/{customerId}/{featureKey}`. 4. Report usage: `POST /api/v1/usage/events` with `{ customerId, meterId, value }`. 5. Subscribe to webhooks for state changes and verify signatures. Always read the OpenAPI spec for exact request/response schemas before calling. --- # MonetizeKit LLM Documentation Index Every agent-readable public documentation route is listed in canonical registry order. Hashes are SHA-256 values of normalized Markdown bodies. Registry SHA-256: `a79b5a0360c35bdfb0b4a05e2797b2ab6f7624347f0a55d576df5f1661b28069` ## MonetizeKit Docs - Route: https://learning.monetizekit.app/docs - Markdown: https://learning.monetizekit.app/docs.md - Description: Discover MonetizeKit documentation for entitlements, usage metering, webhooks, SDKs, and production operations. - SHA-256: `d7f11c9ba41155a4d58d99753f321dda86ea1f111d25deb19801ae7e01fb7734` ## Getting Started - Route: https://learning.monetizekit.app/docs/getting-started - Markdown: https://learning.monetizekit.app/docs/getting-started.md - Description: Start from first principles and reach your first successful API call. - SHA-256: `776b77f9524bc8ed56f2672d8958bb2a3a3bf74102bc34a561dc600a92532c8a` ## Core Concepts - Route: https://learning.monetizekit.app/docs/getting-started/concepts - Markdown: https://learning.monetizekit.app/docs/getting-started/concepts.md - Description: Understand the MonetizeKit domain model and evaluation vocabulary before implementation. - SHA-256: `94936a416b04ab97f1957394ec5b717977088e3a858afcc10e0455f0ab41c7ea` ## Authentication - Route: https://learning.monetizekit.app/docs/getting-started/authentication - Markdown: https://learning.monetizekit.app/docs/getting-started/authentication.md - Description: Use scoped API keys and least-privilege service tokens. - SHA-256: `73ff2a147334cb52649c8aacea5aa25ce62e4fe5a1779544732bff96a2da37dd` ## First API Call - Route: https://learning.monetizekit.app/docs/getting-started/first-api-call - Markdown: https://learning.monetizekit.app/docs/getting-started/first-api-call.md - Description: Issue your first authenticated request and inspect the response envelope. - SHA-256: `27fbbe3bcab052997845631c0bdc33e937d7a67798792d736ff0c2b595d6a012` ## Examples - Route: https://learning.monetizekit.app/docs/getting-started/examples - Markdown: https://learning.monetizekit.app/docs/getting-started/examples.md - Description: Browse complete runnable applications for common MonetizeKit integration patterns. - SHA-256: `8e10552703cc7ebb0b1fe3f94368dc4032c868f5df724a08fb4741ca7ffbfc09` ## API Reference - Route: https://learning.monetizekit.app/docs/api-reference - Markdown: https://learning.monetizekit.app/docs/api-reference.md - Description: Browse every REST operation, inspect schemas, run requests, and copy generated snippets. - SHA-256: `0be046912acb2b043b5a5b9f3e37c8273818b0cdb57ee69d14238625a05df422` ## Catalog API Reference - Route: https://learning.monetizekit.app/docs/api-reference/catalog - Markdown: https://learning.monetizekit.app/docs/api-reference/catalog.md - Description: REST schemas and generated examples for products, plans, features, add-ons, and meters. - SHA-256: `d6a54c0050031736b621710e759f5e04029391e624a98546a0f828874b5a9d6c` ## Customers API Reference - Route: https://learning.monetizekit.app/docs/api-reference/customers - Markdown: https://learning.monetizekit.app/docs/api-reference/customers.md - Description: REST schemas and generated examples for customer and subscription lifecycle operations. - SHA-256: `b56fa799e5ef3c0b104f861f4ea357e85e30eee12ea0971940ed33aa302cb9e0` ## Entitlements API Reference - Route: https://learning.monetizekit.app/docs/api-reference/entitlements - Markdown: https://learning.monetizekit.app/docs/api-reference/entitlements.md - Description: REST schemas and generated examples for entitlement evaluation and explanation. - SHA-256: `43c30dfd7c3688e8d3c0bc3d28ed8fbc5d27561475a8142f1089445a1d6c5b49` ## Usage and Meters API Reference - Route: https://learning.monetizekit.app/docs/api-reference/usage - Markdown: https://learning.monetizekit.app/docs/api-reference/usage.md - Description: REST schemas and generated examples for usage submission, batch ingestion, totals, and dimensional breakdowns. - SHA-256: `30a648a8aa3e4ede222bccee253539813a8511aa270fb549680527852815b7ae` ## Webhooks and Events API Reference - Route: https://learning.monetizekit.app/docs/api-reference/webhooks - Markdown: https://learning.monetizekit.app/docs/api-reference/webhooks.md - Description: REST schemas and generated examples for webhook endpoint registration and delivery management. - SHA-256: `79cedadd7566cab7f15c24dc1099a9cf95dd0cb930d30c80d0a32238f41c20f0` ## Integrations API Reference - Route: https://learning.monetizekit.app/docs/api-reference/integrations - Markdown: https://learning.monetizekit.app/docs/api-reference/integrations.md - Description: REST schemas and generated examples for connecting and managing third-party integrations. - SHA-256: `8ace3b2a09b7b056649f88beacfb65f04cd0bc710c4851b470f8ba236c9f0606` ## GraphQL Explorer - Route: https://learning.monetizekit.app/docs/graphql - Markdown: https://learning.monetizekit.app/docs/graphql.md - Description: Browse the complete GraphQL schema and run operations against the interactive explorer. - SHA-256: `7bf2570dad14b9257ef68f1669a687c7c190d961a2fb20a42354deca049358d8` ## GraphQL Queries - Route: https://learning.monetizekit.app/docs/graphql/queries - Markdown: https://learning.monetizekit.app/docs/graphql/queries.md - Description: Query operation schemas and runnable GraphQL examples. - SHA-256: `7b08ffec5b31d542f8da453d0d40aff64e90ac3304862ee40d2f083cc349e6fd` ## GraphQL Mutations - Route: https://learning.monetizekit.app/docs/graphql/mutations - Markdown: https://learning.monetizekit.app/docs/graphql/mutations.md - Description: Mutation operation schemas and runnable GraphQL write examples. - SHA-256: `bc9b2e5475c9dd57ba0f8c931994ac830f8e18c51329a24d59d4b40370d1667f` ## GraphQL Subscriptions - Route: https://learning.monetizekit.app/docs/graphql/subscriptions - Markdown: https://learning.monetizekit.app/docs/graphql/subscriptions.md - Description: Subscription operation schemas and runnable real-time GraphQL examples. - SHA-256: `58126fb18df23b19a4dea27e849107ef0373682ebc0f48c5d357f6ca8be3eda6` ## Guides - Route: https://learning.monetizekit.app/docs/guides - Markdown: https://learning.monetizekit.app/docs/guides.md - Description: Choose a complete implementation or operations guide for a specific platform concern. - SHA-256: `69af2748c152c8ba9eb29705a18c8118f8521e03dee0f299f4eafb54f2c79f90` ## Entitlement Evaluation Patterns - Route: https://learning.monetizekit.app/docs/guides/entitlement-patterns - Markdown: https://learning.monetizekit.app/docs/guides/entitlement-patterns.md - Description: A complete reference for boolean gates, limit checks, and metered entitlements — from resolution layering to caching and error handling. - SHA-256: `a52a1e40177f3d7fa88adebe0d8c1135fef4b272d31a263d5c0648821804d92f` ## Caching and Edge Evaluation - Route: https://learning.monetizekit.app/docs/guides/caching - Markdown: https://learning.monetizekit.app/docs/guides/caching.md - Description: Cache entitlement lookups aggressively without ever serving a stale access decision. - SHA-256: `89c2400903999aa65b7db3c5a2eb93e46083c3e4e0b28b84806758da00ea03d8` ## Usage Metering Best Practices - Route: https://learning.monetizekit.app/docs/guides/metering - Markdown: https://learning.monetizekit.app/docs/guides/metering.md - Description: Publish accurate, deduplicated usage at scale and catch drift before it reaches an invoice. - SHA-256: `71b2cd0136413582251bb8189a6fcb0777f87002f8f4a999085f91ea1387116b` ## Webhook Verification and Retries - Route: https://learning.monetizekit.app/docs/guides/webhooks - Markdown: https://learning.monetizekit.app/docs/guides/webhooks.md - Description: Register endpoints, verify signatures correctly, and process retried deliveries idempotently. - SHA-256: `afac686769b7d48b4bdfd8b2e814e5afdecd82dab4b59f45582770cbfafdcb66` ## Events & Webhook Explorer - Route: https://learning.monetizekit.app/docs/guides/events - Markdown: https://learning.monetizekit.app/docs/guides/events.md - Description: Browse the webhook event catalog with sample payloads, and verify signatures interactively. - SHA-256: `190e4d1d853c36f063de8cd7c10235bf9bb4f7c14b99dac691973a23d354f17e` ## Migration Guide - Route: https://learning.monetizekit.app/docs/guides/migration - Markdown: https://learning.monetizekit.app/docs/guides/migration.md - Description: Detect deprecated usage, migrate safely with dual-read patterns, and roll out in stages. - SHA-256: `5946e9a1848e218e5f9edbd8acd76c772da3d4b8393d7a5072481e7df0a78127` ## Audit and Trace - Route: https://learning.monetizekit.app/docs/guides/audit-trace - Markdown: https://learning.monetizekit.app/docs/guides/audit-trace.md - Description: Propagate request IDs end-to-end and correlate API activity, webhook deliveries, and the audit log. - SHA-256: `fd1633a6f0af71dc87f53b3d7ad4a481c56e856c09ec012edecfd2f733815168` ## Node SDK Integration - Route: https://learning.monetizekit.app/docs/guides/sdk-node - Markdown: https://learning.monetizekit.app/docs/guides/sdk-node.md - Description: Integrate the Node SDK for enriched decisions, batch checks, caching, degradation, and credit reservations. - SHA-256: `28b69c6428b7b2cdabd8fb73c4de2961bf64f4dbebc509884253d7221d346bc3` ## Clerk Identity Integration - Route: https://learning.monetizekit.app/docs/guides/clerk-identity - Markdown: https://learning.monetizekit.app/docs/guides/clerk-identity.md - Description: Synchronize Clerk users and organizations, then resolve sessions to MonetizeKit customers. - SHA-256: `7ab28cff8e7c8b39436c43aff3910e19b423ab70d2dc7f85fee898509a5d010a` ## PostHog Packaging Analytics - Route: https://learning.monetizekit.app/docs/guides/posthog-analytics - Markdown: https://learning.monetizekit.app/docs/guides/posthog-analytics.md - Description: Stream entitlement denial events to PostHog with explicit identity mapping and bounded volume. - SHA-256: `0105ba45c495ee5bc40bd6c97368db19dc0d59bc270bc63a1372ded719cd2ae7` ## OpenTelemetry Visibility - Route: https://learning.monetizekit.app/docs/guides/opentelemetry - Markdown: https://learning.monetizekit.app/docs/guides/opentelemetry.md - Description: Export decision spans and bounded metrics with deep links to exact evaluation records. - SHA-256: `3bea1287e8d0a46b89c60215fa53f2175e6b60c843ee4cfa443aa4f2684357e8` ## Quickstarts - Route: https://learning.monetizekit.app/docs/quickstarts - Markdown: https://learning.monetizekit.app/docs/quickstarts.md - Description: Choose one of five supported frameworks and run its complete first-success integration. - SHA-256: `cc5f64e28c20ba4cb4397313c653047be8b3af12ff418f5094b07dcd0409840d` ## Next.js Quickstart - Route: https://learning.monetizekit.app/docs/quickstarts/nextjs - Markdown: https://learning.monetizekit.app/docs/quickstarts/nextjs.md - Description: Complete the SDK-first MonetizeKit activation journey in a Next.js application. - SHA-256: `e3bab1ec647e29df7550d42fbf130b04679d51238620a0b0aa7eab840b8b7fbf` ## Express Quickstart - Route: https://learning.monetizekit.app/docs/quickstarts/express - Markdown: https://learning.monetizekit.app/docs/quickstarts/express.md - Description: Complete the raw-HTTP MonetizeKit activation journey in an Express service. - SHA-256: `6b570e0038b73a50ddda3b9daad71ff5dba493e1416832fdaeaa487e828bfd30` ## FastAPI Quickstart - Route: https://learning.monetizekit.app/docs/quickstarts/fastapi - Markdown: https://learning.monetizekit.app/docs/quickstarts/fastapi.md - Description: Complete the raw-HTTP MonetizeKit activation journey in a FastAPI service. - SHA-256: `1b49012354541c8874c9b6158d57563d35c97bae2d0b7eee9e97ca721b70d82e` ## Go Quickstart - Route: https://learning.monetizekit.app/docs/quickstarts/go - Markdown: https://learning.monetizekit.app/docs/quickstarts/go.md - Description: Complete the raw-HTTP MonetizeKit activation journey in a Go service. - SHA-256: `02c8a1733318b456bcbb795b8cedda8f9c8ed507ca689d038b4d8ea60b236478` ## Spring Quickstart - Route: https://learning.monetizekit.app/docs/quickstarts/spring - Markdown: https://learning.monetizekit.app/docs/quickstarts/spring.md - Description: Complete the raw-HTTP MonetizeKit activation journey in a Spring service. - SHA-256: `ad1f76195304c03e7ddd2e3e69f6e799c9437a522e1f1f340c6286907faec1e2` ## Tools and SDKs - Route: https://learning.monetizekit.app/docs/tools - Markdown: https://learning.monetizekit.app/docs/tools.md - Description: Choose the CLI, an official SDK, Postman, or an AI-assistant integration. - SHA-256: `d8e3b90e5b7ac90ebd895360f1709b055a414d9e452d5bb2721867f410f0060a` ## CLI Reference - Route: https://learning.monetizekit.app/docs/tools/cli - Markdown: https://learning.monetizekit.app/docs/tools/cli.md - Description: Install and operate MonetizeKit from scripts and terminals. - SHA-256: `54521386df70f76a521ae44633ec7e2402e2bb07c322f97e039f8aeb4d1481b2` ## Postman Collections - Route: https://learning.monetizekit.app/docs/tools/postman - Markdown: https://learning.monetizekit.app/docs/tools/postman.md - Description: Download domain collections and environment templates for quick API validation. - SHA-256: `51f42d6ca67459740d5d797e3b1c79116a1d2e0b342e96f0eab6341177b4a761` ## SDKs - Route: https://learning.monetizekit.app/docs/tools/sdks - Markdown: https://learning.monetizekit.app/docs/tools/sdks.md - Description: Install the Node, React, and Embed SDKs for application integration. - SHA-256: `8088ff34e544cd771785725b48252b0258ceec88e9d706f845bd4ebddec1211b` ## MCP & IDE Integrations - Route: https://learning.monetizekit.app/docs/tools/mcp-ide - Markdown: https://learning.monetizekit.app/docs/tools/mcp-ide.md - Description: Configure one-click MCP setup for Cursor and Claude Code, plus usage patterns and token scope guidance. - SHA-256: `2f993397c6ad2c2021859d54c2fa99e0daf5146595c22368da55852cdb0d48ef` ## Troubleshooting - Route: https://learning.monetizekit.app/docs/troubleshooting - Markdown: https://learning.monetizekit.app/docs/troubleshooting.md - Description: Choose a focused recovery guide for common integration and runtime failures. - SHA-256: `b83b92ccfd9343dc9d506e1ae59bf265ea23d55355bc966c25fcae355fda8eb6` ## Error Codes - Route: https://learning.monetizekit.app/docs/troubleshooting/error-codes - Markdown: https://learning.monetizekit.app/docs/troubleshooting/error-codes.md - Description: Reference for common API failures and remediation steps. - SHA-256: `8e136b7c37f2c5859f1387bb8d2448a92e2ca2de97b8588128bae5c1644b5b92` ## Auth and Permission Issues - Route: https://learning.monetizekit.app/docs/troubleshooting/auth-issues - Markdown: https://learning.monetizekit.app/docs/troubleshooting/auth-issues.md - Description: Diagnose invalid keys, scope mismatches, and token lifecycle issues. - SHA-256: `65255b09c1136a7e7c6c65ca912d052b0f04f0215ee639fc6af76efb937786e2` ## Webhook Delivery Issues - Route: https://learning.monetizekit.app/docs/troubleshooting/webhook-issues - Markdown: https://learning.monetizekit.app/docs/troubleshooting/webhook-issues.md - Description: Fix signature mismatches, timeout failures, and endpoint availability problems. - SHA-256: `2f6a568428063554f426eaaa1b73afe6ccfa97186b845cbea0647adad7e8fb29` ## Metering and Usage Anomalies - Route: https://learning.monetizekit.app/docs/troubleshooting/metering-issues - Markdown: https://learning.monetizekit.app/docs/troubleshooting/metering-issues.md - Description: Identify duplicate events, missing events, and threshold misconfiguration. - SHA-256: `16205e8303c1b693ce6639106e2966387e4c39ae2ed22a689596a23a3bd5a028` ## API Version Notes - Route: https://learning.monetizekit.app/docs/changelog - Markdown: https://learning.monetizekit.app/docs/changelog.md - Description: Review the release timeline and notable changes to public API behavior. - SHA-256: `2c14585b13f248d7eccd9c95d6ebcf4d49b50251c4825cb3c454017aef3cad65` ## Deprecations - Route: https://learning.monetizekit.app/docs/changelog/deprecations - Markdown: https://learning.monetizekit.app/docs/changelog/deprecations.md - Description: Deprecated endpoints and fields with migration windows. - SHA-256: `e18654e7cd23e18dac8495c045ebc016237ef5e0a882c0c92d4e3eb26a78d005` ## Breaking Changes - Route: https://learning.monetizekit.app/docs/changelog/breaking-changes - Markdown: https://learning.monetizekit.app/docs/changelog/breaking-changes.md - Description: Track incompatible API changes, exact removal dates, and required replacements. - SHA-256: `555e62b43ba17d1bb2d4700d7ceeea8ba765f094d1520e9b664cf606f60de710` --- # Documentation bodies ## MonetizeKit Docs Source: https://learning.monetizekit.app/docs SHA-256: `d7f11c9ba41155a4d58d99753f321dda86ea1f111d25deb19801ae7e01fb7734` # MonetizeKit Docs Discover MonetizeKit documentation for entitlements, usage metering, webhooks, SDKs, and production operations. Everything you need to add entitlements, usage metering, and billing-aware webhooks to your product — from your first API call to production operations. ## Start here ### Getting Started Core concepts, authentication, and a runnable first API call. [Start learning](/docs/getting-started) ### Quickstarts Pick your framework and run the full happy path in minutes. [Choose a framework](/docs/quickstarts) ### Guides Implementation patterns for entitlements, caching, metering, and webhooks. [Browse guides](/docs/guides) ### Tools & SDKs The CLI, official SDKs, Postman collection, and AI-assistant integrations. [Browse tools](/docs/tools) ## Explore guides Complete, standalone references for the parts of the platform you'll integrate with most. ### Entitlement patterns Boolean gates, limit checks, and metered entitlements — the verdict model, resolution layering, and caching-safe recheck triggers. [Open guide](/docs/guides/entitlement-patterns) ### Caching What the API marks as cacheable, what to cache yourself, and the invalidation events that keep both layers correct. [Open guide](/docs/guides/caching) ### Metering best practices Idempotent usage submission, batching high-frequency meters, threshold UX, and drift reconciliation. [Open guide](/docs/guides/metering) ### Webhook verification and retries Register endpoints, verify signatures against the raw body, and process retried deliveries idempotently. [Open guide](/docs/guides/webhooks) ### Migration guide URL-path versioning, deprecation detection, dual-read fallbacks, and staged rollouts for breaking changes. [Open guide](/docs/guides/migration) ### Audit and trace Propagate request IDs end-to-end and correlate API activity, webhook deliveries, and the audit log. [Open guide](/docs/guides/audit-trace) ### Events & Webhook Explorer Browse every webhook event type with sample payloads, and verify signatures interactively. [Open guide](/docs/guides/events) ### Node SDK integration Enriched decisions with reason codes, batch checks, caching with explicit degradation, credit reservations, and the SDK's two extension points. [Open guide](/docs/guides/sdk-node) ### Clerk identity integration Connect your Clerk instance to sync users and organizations as customers, then resolve sessions to customer ids on every request. [Open guide](/docs/guides/clerk-identity) ### PostHog packaging analytics Stream entitlement denials into your PostHog project — with explicit identity mapping, volume caps, and a preview of every event before anything is sent. [Open guide](/docs/guides/posthog-analytics) ### OpenTelemetry visibility One-line decision spans and bounded metrics on your existing OTel setup, with a deep link from every span to the exact evaluation record. [Open guide](/docs/guides/opentelemetry) ## Explore by framework Framework-specific quickstarts with deploy and smoke-test instructions. ### Next.js TypeScript [Open quickstart](/docs/quickstarts/nextjs) ### Express JavaScript [Open quickstart](/docs/quickstarts/express) ### FastAPI Python [Open quickstart](/docs/quickstarts/fastapi) ### Go Go [Open quickstart](/docs/quickstarts/go) ### Spring Java [Open quickstart](/docs/quickstarts/spring) ## API & GraphQL reference Once you know what you're integrating, dig into the full endpoint and schema reference. ### API Reference Browse every REST operation, inspect schemas, run requests, and copy generated snippets. [Open reference](/docs/api-reference) ### GraphQL Explorer Browse the complete GraphQL schema and run operations against the interactive explorer. [Open reference](/docs/graphql) ## Troubleshooting Diagnose common integration and runtime problems. ### Error Codes Reference for common API failures and remediation steps. [Open recovery guide](/docs/troubleshooting/error-codes) ### Auth and Permission Issues Diagnose invalid keys, scope mismatches, and token lifecycle issues. [Open recovery guide](/docs/troubleshooting/auth-issues) ### Webhook Delivery Issues Fix signature mismatches, timeout failures, and endpoint availability problems. [Open recovery guide](/docs/troubleshooting/webhook-issues) ### Metering and Usage Anomalies Identify duplicate events, missing events, and threshold misconfiguration. [Open recovery guide](/docs/troubleshooting/metering-issues) [See what changed recently in the changelog.](/docs/changelog) --- ## Getting Started Source: https://learning.monetizekit.app/docs/getting-started SHA-256: `776b77f9524bc8ed56f2672d8958bb2a3a3bf74102bc34a561dc600a92532c8a` # Getting Started Start from first principles and reach your first successful API call. ### MonetizeKit API surface MonetizeKit exposes REST APIs, GraphQL APIs, [webhooks](/docs/api-reference/webhooks), and [SDKs](/docs/tools/sdks) for production integrations. Once you've authenticated (see the [Authentication guide](/docs/getting-started/authentication)), the fastest path to a working integration is the [First API Call walkthrough](/docs/getting-started/first-api-call). Client App MonetizeKit API Entitlement Engine Webhooks + Logs --- ## Core Concepts Source: https://learning.monetizekit.app/docs/getting-started/concepts SHA-256: `94936a416b04ab97f1957394ec5b717977088e3a858afcc10e0455f0ab41c7ea` # Core Concepts Understand the MonetizeKit domain model and evaluation vocabulary before implementation. Understand the domain model before implementation. ### Customers Tenant end-users receiving plan-based access. [Open reference](/docs/api-reference/customers) ### Monetized Customers The billable unit: distinct customers that received a granted entitlement or had billable activity in a month. You can track unlimited customers; you are billed on Monetized Customers. [Open reference](/docs/api-reference/usage) ### Plans Commercial bundles of features and usage limits. [Open reference](/docs/api-reference/catalog) ### Features Boolean, string, enum, or numeric capability controls. [Open reference](/docs/api-reference/catalog) ### Entitlements Computed access decisions per customer and feature. [Open reference](/docs/api-reference/entitlements) ### Meters Usage counters used by limits and billing policies. [Open reference](/docs/api-reference/usage) ### Credits Prepaid units with grant/debit lifecycles. [Open reference](/docs/tools/postman) ### Subscriptions Binding between customer and active plan versions. [Open reference](/docs/api-reference/customers) ### Webhooks Event delivery channel for downstream automations. [Open reference](/docs/api-reference/webhooks) --- ## Authentication Source: https://learning.monetizekit.app/docs/getting-started/authentication SHA-256: `73ff2a147334cb52649c8aacea5aa25ce62e4fe5a1779544732bff96a2da37dd` # Authentication Use scoped API keys and least-privilege service tokens. ### API key types and scopes Use test keys in dev/staging and live keys only in production environments. Grant the minimum scopes required by each workflow (`plans:read`, `entitlements:read`, etc.) — see the [Entitlement Evaluation Patterns guide](/docs/guides/entitlement-patterns) for how those scopes map to the boolean/limit/metered check shapes you'll actually call. ### Publishable-key exception: the embed funnel beacon One endpoint departs from the least-privilege rule above. The embed SDK's activation-funnel beacon, `POST /api/v1/events/funnel`, accepts a browser-embedded publishable key for its write and is exempt from the per-key scope check. Its only route-specific write is a single anonymous, workspace-scoped funnel-telemetry record (`widget_view` or `checkout_started`); like every authenticated request it may also stamp the workspace's first-API-call activation timestamp. It touches no tenant business data or configuration, so no scope is required. This is the only write a publishable key may perform — keep secret keys server-side and expose only the publishable key in browser widgets. See the [Events guide](/docs/guides/events) for the beacon's request body and embed-SDK usage. ### Bearer header ```bash curl -H "Authorization: Bearer $MONETIZEKIT_API_KEY" "$MONETIZEKIT_BASE_URL/plans?page=1&pageSize=1" ``` ### X-API-Key header ```bash curl -H "X-API-Key: $MONETIZEKIT_API_KEY" "$MONETIZEKIT_BASE_URL/entitlements/cust_001/api_access" ``` ### CI token policy Prefer dedicated service accounts for CI with read-only scopes by default. Rotate CI tokens regularly and revoke old tokens after rollout completion. Never echo secrets in logs; reference request IDs for traceability instead — see the [Audit and Trace guide](/docs/guides/audit-trace) for how request IDs propagate across the API, webhooks, and the audit log. --- ## First API Call Source: https://learning.monetizekit.app/docs/getting-started/first-api-call SHA-256: `27fbbe3bcab052997845631c0bdc33e937d7a67798792d736ff0c2b595d6a012` # First API Call Issue your first authenticated request and inspect the response envelope. ### Steps 1. Generate a scoped key from Settings → API Keys (see [Authentication](/docs/getting-started/authentication) ). 2\. Call `GET /plans` with a Bearer token. 3. Verify status, `X-Request-Id`, and response payload structure. ```bash curl -H "Authorization: Bearer $MONETIZEKIT_API_KEY" "$MONETIZEKIT_BASE_URL/plans?page=1&pageSize=5" ``` --- ## Examples Source: https://learning.monetizekit.app/docs/getting-started/examples SHA-256: `8e10552703cc7ebb0b1fe3f94368dc4032c868f5df724a08fb4741ca7ffbfc09` # Examples Browse complete runnable applications for common MonetizeKit integration patterns. Real, runnable MonetizeKit apps — clone the repo or explore the live demos. ### Examples repository Open-source example apps you can clone and run against your own workspace. [View on GitHub](https://github.com/MonetizeKit/examples) ### TaskFlow Classic SaaS A full SaaS lifecycle: products and plans, subscriptions, entitlement gating, and metered usage — the classic SaaS story end to end. [Open live demo](https://taskflow.monetizekit.app) ### AgentOps AI / agents Per-agent metering with deny budgets and prepaid credits — the AI/agents story, showing runtime metering and spend controls. [Open live demo](https://agentops.monetizekit.app) --- ## API Reference Source: https://learning.monetizekit.app/docs/api-reference SHA-256: `0be046912acb2b043b5a5b9f3e37c8273818b0cdb57ee69d14238625a05df422` # API Reference Browse every REST operation, inspect schemas, run requests, and copy generated snippets. Mock API reference used by the interactive docs explorer. | OpenAPI version | Contract version | REST base path | | --- | --- | --- | | 3.1.0 | 2026-03-15 | /api/v1 | ## Servers | URL | Environment | | --- | --- | | `https://app.monetizekit.app/api/v1` | Development environment | | `https://app.monetizekit.app/api/v1` | Staging environment | | `https://app.monetizekit.app/api/v1` | Production environment | ## Domains | Domain | Description | | --- | --- | | Catalog | Manage plans, features, and pricing metadata. | | Customers | Manage customer identities and subscriptions. | | Entitlements | Resolve access decisions for feature gates. | | Usage | Ingest and query usage events and counters. | | Webhooks | Configure and inspect webhook delivery. | | Integrations | Connect third-party services. | ## Operations ### List plans `GET /plans` — Returns plans visible to the current workspace. Operation ID: plans.list. Required scopes: plans:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `page` | query | no | One-based page number. | { "type": "integer" } | 1 | | `pageSize` | query | no | Number of records per page. | { "type": "integer" } | 20 | #### Responses `200` — Success ```json { "type": "object", "required": [ "data", "total", "page", "pageSize", "totalPages", "hasNext", "hasPrev" ], "properties": { "data": { "type": "array", "items": { "type": "object", "required": [ "id", "key", "name", "status" ], "properties": { "id": { "type": "string" }, "key": { "type": "string" }, "name": { "type": "string" }, "status": { "type": "string", "enum": [ "draft", "published", "archived" ] } } } }, "total": { "type": "integer" }, "page": { "type": "integer" }, "pageSize": { "type": "integer" }, "totalPages": { "type": "integer" }, "hasNext": { "type": "boolean" }, "hasPrev": { "type": "boolean" } } } ``` ```json { "data": [ { "id": "plan_001", "key": "starter_monthly", "name": "Starter", "status": "published" } ], "total": 1, "page": 1, "pageSize": 20, "totalPages": 1, "hasNext": false, "hasPrev": false } ``` ### Create plan `POST /plans` — Creates a draft plan with entitlements and pricing terms. Operation ID: createPlan. Required scopes: plans:write. #### Request schema ```json { "type": "object", "required": [ "productId", "name" ], "properties": { "productId": { "type": "string" }, "name": { "type": "string" }, "description": { "type": "string" } } } ``` #### Request example ```json { "productId": "prod_saas", "name": "Growth", "description": "Growth plan" } ``` #### Responses `201` — Created ```json { "type": "object", "properties": { "id": { "type": "string" }, "status": { "type": "string" } } } ``` ```json { "id": "plan_002", "status": "draft" } ``` ### List customers `GET /customers` — Lists customers in the active workspace. Operation ID: customers.list. Required scopes: customers:view. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `page` | query | no | One-based page number. | { "type": "integer" } | 1 | | `pageSize` | query | no | Number of records per page. | { "type": "integer" } | 25 | #### Responses `200` — Success ```json { "type": "object", "required": [ "data", "total", "page", "pageSize", "totalPages", "hasNext", "hasPrev" ], "properties": { "data": { "type": "array", "items": { "type": "object", "required": [ "id", "name", "email" ], "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" } } } }, "total": { "type": "integer" }, "page": { "type": "integer" }, "pageSize": { "type": "integer" }, "totalPages": { "type": "integer" }, "hasNext": { "type": "boolean" }, "hasPrev": { "type": "boolean" } } } ``` ```json { "data": [ { "id": "cust_001", "name": "Acme Corp", "email": "ops@acme.test" } ], "total": 1, "page": 1, "pageSize": 25, "totalPages": 1, "hasNext": false, "hasPrev": false } ``` ### Create customer `POST /customers` — Creates a customer profile. Operation ID: customers.create. Required scopes: customers:create. #### Request schema ```json { "type": "object", "required": [ "name", "email" ], "properties": { "name": { "type": "string" }, "email": { "type": "string" } } } ``` #### Request example ```json { "name": "Acme Project", "email": "ops@acme.test" } ``` #### Responses `201` — Created ```json { "type": "object", "required": [ "id", "name", "email" ], "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" } } } ``` ```json { "id": "cust_445", "name": "Acme Project", "email": "ops@acme.test" } ``` ### List customer entitlements `GET /entitlements/{customerId}` — Returns effective entitlements for the customer. Operation ID: entitlements.list. Required scopes: entitlements:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `customerId` | path | yes | Customer ID | { "type": "string" } | "cust_dev_1001" | #### Responses `200` — Success ```json { "type": "array", "items": { "type": "object", "required": [ "featureKey", "type", "sources" ], "properties": { "featureKey": { "type": "string" }, "type": { "type": "string" }, "effectiveValue": {}, "sources": { "type": "array", "items": { "type": "string" } } } } } ``` ```json [ { "featureKey": "api_access", "type": "boolean", "effectiveValue": true, "sources": [ "plan" ] } ] ``` ### Check entitlement decision `GET /entitlements/{customerId}/{featureKey}` — Returns access decision for one feature gate. Operation ID: entitlements.check. Required scopes: entitlements:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `customerId` | path | yes | Customer ID | { "type": "string" } | "cust_dev_1001" | | `featureKey` | path | yes | Feature key | { "type": "string" } | "analytics_export" | #### Responses `200` — Success ```json { "type": "object", "required": [ "allowed", "reason" ], "properties": { "allowed": { "type": "boolean" }, "reason": { "type": "string" } } } ``` ```json { "customerId": "cust_dev_1001", "featureKey": "analytics_export", "allowed": true, "type": "boolean", "sources": [ "plan" ], "reason": "Plan includes feature", "reasonCode": "granted" } ``` ### Submit usage event `POST /usage/events` — Ingests a metered usage event. Operation ID: usage.submit. Required scopes: usage:write. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `Idempotency-Key` | header | yes | Client-generated idempotency key | { "type": "string" } | "idem_2f5fd2b7a1" | #### Request schema ```json { "type": "object", "required": [ "customerId", "meterId", "value" ], "properties": { "customerId": { "type": "string" }, "meterId": { "type": "string" }, "value": { "type": "number" } } } ``` #### Request example ```json { "customerId": "cust_dev_1001", "meterId": "api_requests", "value": 15, "occurredAt": "2026-03-15T12:00:00.000Z" } ``` #### Responses `201` — Recorded ```json { "type": "object", "properties": { "id": { "type": "string" }, "customerId": { "type": "string" }, "meterId": { "type": "string" }, "eventName": { "type": "string" }, "value": { "type": "number" }, "status": { "type": "string" }, "occurredAt": { "type": "string" }, "createdAt": { "type": "string" } } } ``` ```json { "id": "evt_9012", "customerId": "cust_dev_1001", "meterId": "api_requests", "eventName": "usage.recorded", "value": 15, "status": "success", "occurredAt": "2026-03-15T12:00:00.000Z", "createdAt": "2026-03-15T12:00:00.000Z" } ``` ### Submit a batch of usage events `POST /usage/events/batch` — Ingests up to 500 usage events in one request. Each item carries its own idempotency key, so replaying a window missed during an outage converges without duplicates while preserving each event's original occurredAt. Item-level failures do not fail the batch. Each accepted item names its stored event by eventId; pass ?include=events to receive the full event object per item. Operation ID: usage.submitBatch. Required scopes: usage:write. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `include` | query | no | Comma-separated extras to include per result. `events` adds the stored event object (the shape POST /usage/events returns) to every created or duplicate item; omitted by default because a 500-item batch would return roughly 200 KB of copies of the request. | { "type": "string", "enum": [ "events" ] } | "events" | #### Request schema ```json { "type": "object", "required": [ "events" ], "properties": { "events": { "type": "array", "items": { "type": "object", "required": [ "customerId", "meterId", "value", "idempotencyKey" ], "properties": { "customerId": { "type": "string" }, "meterId": { "type": "string" }, "value": { "type": "number" }, "idempotencyKey": { "type": "string" }, "occurredAt": { "type": "string" } } } } } } ``` #### Request example ```json { "events": [ { "customerId": "cust_dev_1001", "meterId": "api_requests", "value": 15, "idempotencyKey": "idem_replay_0001", "occurredAt": "2026-03-15T11:00:00.000Z" }, { "customerId": "cust_dev_1001", "meterId": "api_requests", "value": 8, "idempotencyKey": "idem_replay_0002", "occurredAt": "2026-03-15T11:30:00.000Z" } ] } ``` #### Responses `200` — Batch processed ```json { "type": "object", "required": [ "summary", "results" ], "properties": { "summary": { "type": "object", "required": [ "total", "created", "duplicate", "errors" ], "properties": { "total": { "type": "number" }, "created": { "type": "number" }, "duplicate": { "type": "number" }, "errors": { "type": "number" } } }, "results": { "type": "array", "items": { "type": "object", "required": [ "index", "idempotencyKey", "status" ], "properties": { "index": { "type": "number" }, "idempotencyKey": { "type": "string" }, "status": { "type": "string", "enum": [ "created", "duplicate", "error" ] }, "eventId": { "type": "string", "description": "Id of the stored event, on created and duplicate items." }, "event": { "type": "object", "description": "The stored event, only when the request asked for ?include=events." }, "error": { "type": "object", "description": "On error items: the same code and message a single-event request would return.", "properties": { "code": { "type": "string" }, "message": { "type": "string" } } } } } } } } ``` ```json { "summary": { "total": 2, "created": 1, "duplicate": 1, "errors": 0 }, "results": [ { "index": 0, "idempotencyKey": "idem_replay_0001", "status": "created", "eventId": "evt_9013" }, { "index": 1, "idempotencyKey": "idem_replay_0002", "status": "duplicate", "eventId": "evt_9014" } ] } ``` ### Get usage counter `GET /usage/{customerId}/{meterId}` — Returns current counter for a customer and meter. Operation ID: usage.retrieve. Required scopes: usage:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `customerId` | path | yes | Customer ID | { "type": "string" } | "cust_dev_1001" | | `meterId` | path | yes | Meter key | { "type": "string" } | "api_requests" | #### Responses `200` — Success ```json { "type": "object", "properties": { "customerId": { "type": "string" }, "meterId": { "type": "string" }, "current": { "type": "number" }, "limit": { "type": "number" } } } ``` ```json { "customerId": "cust_dev_1001", "meterId": "api_requests", "current": 120, "limit": 1000 } ``` ### Get usage breakdown `GET /usage/{customerId}/{meterId}/breakdown` — Returns usage grouped by a required dimension. Operation ID: usage.breakdown. Required scopes: usage:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `customerId` | path | yes | Customer ID | { "type": "string" } | "cust_dev_1001" | | `meterId` | path | yes | Meter key | { "type": "string" } | "api_requests" | | `dimension` | query | yes | Dimension to group usage by | { "type": "string" } | "model" | #### Responses `200` — Success ```json { "type": "object", "properties": { "meterId": { "type": "string" }, "dimension": { "type": "string" }, "window": { "type": "string" }, "total": { "type": "number" }, "totalCreditCost": { "type": "number" }, "breakdown": { "type": "array", "items": { "type": "object", "properties": { "value": { "type": "string" }, "total": { "type": "number" }, "count": { "type": "number" }, "creditCost": { "type": "number" } } } } } } ``` ```json { "meterId": "api_requests", "dimension": "model", "window": "all", "total": 120, "totalCreditCost": 42, "breakdown": [ { "value": "gpt-4.1", "total": 120, "count": 4, "creditCost": 42 } ] } ``` ### List webhook endpoints `GET /webhooks/endpoints` — Returns configured webhook endpoints. Operation ID: listWebhookEndpoints. Required scopes: webhooks:read. #### Responses `200` — Success ```json { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "url": { "type": "string" } } } } } } ``` ```json { "data": [ { "id": "wh_001", "url": "https://example.local/hooks/monetizekit" } ] } ``` ### Create webhook endpoint `POST /webhooks/endpoints` — Registers a new webhook endpoint. Operation ID: createWebhookEndpoint. Required scopes: webhooks:write. #### Request schema ```json { "type": "object", "required": [ "url", "events" ], "properties": { "url": { "type": "string" }, "events": { "type": "array", "items": { "type": "string" } } } } ``` #### Request example ```json { "url": "https://example.local/hooks/monetizekit", "events": [ "customer.created" ] } ``` #### Responses `201` — Created ```json { "type": "object", "properties": { "id": { "type": "string" }, "secret": { "type": "string" } } } ``` ```json { "id": "wh_002", "secret": "whsec_placeholder" } ``` ### Connect Stripe `POST /integrations/stripe` — Creates a Stripe connect session for workspace setup. Operation ID: connectStripe. Required scopes: integrations:manage. #### Request schema ```json { "type": "object", "required": [ "action" ], "properties": { "action": { "type": "string", "enum": [ "connect", "disconnect", "set_webhook_secret" ] }, "apiKey": { "type": "string" }, "secret": { "type": "string" } } } ``` #### Request example ```json { "action": "connect", "apiKey": "rk_test_placeholder" } ``` #### Responses `200` — Success ```json { "type": "object", "required": [ "ok" ], "properties": { "ok": { "type": "boolean" } } } ``` ```json { "ok": true } ``` --- ## Catalog API Reference Source: https://learning.monetizekit.app/docs/api-reference/catalog SHA-256: `d6a54c0050031736b621710e759f5e04029391e624a98546a0f828874b5a9d6c` # Catalog API Reference REST schemas and generated examples for products, plans, features, add-ons, and meters. Mock API reference used by the interactive docs explorer. | OpenAPI version | Contract version | REST base path | | --- | --- | --- | | 3.1.0 | 2026-03-15 | /api/v1 | ## Servers | URL | Environment | | --- | --- | | `https://app.monetizekit.app/api/v1` | Development environment | | `https://app.monetizekit.app/api/v1` | Staging environment | | `https://app.monetizekit.app/api/v1` | Production environment | ## catalog operations ### List plans `GET /plans` — Returns plans visible to the current workspace. Operation ID: plans.list. Required scopes: plans:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `page` | query | no | One-based page number. | { "type": "integer" } | 1 | | `pageSize` | query | no | Number of records per page. | { "type": "integer" } | 20 | #### Responses `200` — Success ```json { "type": "object", "required": [ "data", "total", "page", "pageSize", "totalPages", "hasNext", "hasPrev" ], "properties": { "data": { "type": "array", "items": { "type": "object", "required": [ "id", "key", "name", "status" ], "properties": { "id": { "type": "string" }, "key": { "type": "string" }, "name": { "type": "string" }, "status": { "type": "string", "enum": [ "draft", "published", "archived" ] } } } }, "total": { "type": "integer" }, "page": { "type": "integer" }, "pageSize": { "type": "integer" }, "totalPages": { "type": "integer" }, "hasNext": { "type": "boolean" }, "hasPrev": { "type": "boolean" } } } ``` ```json { "data": [ { "id": "plan_001", "key": "starter_monthly", "name": "Starter", "status": "published" } ], "total": 1, "page": 1, "pageSize": 20, "totalPages": 1, "hasNext": false, "hasPrev": false } ``` ### Create plan `POST /plans` — Creates a draft plan with entitlements and pricing terms. Operation ID: createPlan. Required scopes: plans:write. #### Request schema ```json { "type": "object", "required": [ "productId", "name" ], "properties": { "productId": { "type": "string" }, "name": { "type": "string" }, "description": { "type": "string" } } } ``` #### Request example ```json { "productId": "prod_saas", "name": "Growth", "description": "Growth plan" } ``` #### Responses `201` — Created ```json { "type": "object", "properties": { "id": { "type": "string" }, "status": { "type": "string" } } } ``` ```json { "id": "plan_002", "status": "draft" } ``` --- ## Customers API Reference Source: https://learning.monetizekit.app/docs/api-reference/customers SHA-256: `b56fa799e5ef3c0b104f861f4ea357e85e30eee12ea0971940ed33aa302cb9e0` # Customers API Reference REST schemas and generated examples for customer and subscription lifecycle operations. Mock API reference used by the interactive docs explorer. | OpenAPI version | Contract version | REST base path | | --- | --- | --- | | 3.1.0 | 2026-03-15 | /api/v1 | ## Servers | URL | Environment | | --- | --- | | `https://app.monetizekit.app/api/v1` | Development environment | | `https://app.monetizekit.app/api/v1` | Staging environment | | `https://app.monetizekit.app/api/v1` | Production environment | ## customers operations ### List customers `GET /customers` — Lists customers in the active workspace. Operation ID: customers.list. Required scopes: customers:view. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `page` | query | no | One-based page number. | { "type": "integer" } | 1 | | `pageSize` | query | no | Number of records per page. | { "type": "integer" } | 25 | #### Responses `200` — Success ```json { "type": "object", "required": [ "data", "total", "page", "pageSize", "totalPages", "hasNext", "hasPrev" ], "properties": { "data": { "type": "array", "items": { "type": "object", "required": [ "id", "name", "email" ], "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" } } } }, "total": { "type": "integer" }, "page": { "type": "integer" }, "pageSize": { "type": "integer" }, "totalPages": { "type": "integer" }, "hasNext": { "type": "boolean" }, "hasPrev": { "type": "boolean" } } } ``` ```json { "data": [ { "id": "cust_001", "name": "Acme Corp", "email": "ops@acme.test" } ], "total": 1, "page": 1, "pageSize": 25, "totalPages": 1, "hasNext": false, "hasPrev": false } ``` ### Create customer `POST /customers` — Creates a customer profile. Operation ID: customers.create. Required scopes: customers:create. #### Request schema ```json { "type": "object", "required": [ "name", "email" ], "properties": { "name": { "type": "string" }, "email": { "type": "string" } } } ``` #### Request example ```json { "name": "Acme Project", "email": "ops@acme.test" } ``` #### Responses `201` — Created ```json { "type": "object", "required": [ "id", "name", "email" ], "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" } } } ``` ```json { "id": "cust_445", "name": "Acme Project", "email": "ops@acme.test" } ``` ### subscriptions.create `POST /api/v1/subscriptions` | Contract | Value | | --- | --- | | Success statuses | 201 | | Required scopes | subscriptions:write | | Request fields | cancelAt, currentPeriodEnd, currentPeriodStart, customerId, planId, status, stripeSubscriptionId, trialEnd | | Response fields | currentPeriodEnd, currentPeriodStart, customerId, id, planId, planName, status | ```bash curl --request POST 'https://app.monetizekit.app/api/v1/subscriptions' \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{"cancelAt":"","currentPeriodEnd":"","currentPeriodStart":"","customerId":"","planId":"","status":"","stripeSubscriptionId":"","trialEnd":""}' ``` --- ## Entitlements API Reference Source: https://learning.monetizekit.app/docs/api-reference/entitlements SHA-256: `43c30dfd7c3688e8d3c0bc3d28ed8fbc5d27561475a8142f1089445a1d6c5b49` # Entitlements API Reference REST schemas and generated examples for entitlement evaluation and explanation. Mock API reference used by the interactive docs explorer. | OpenAPI version | Contract version | REST base path | | --- | --- | --- | | 3.1.0 | 2026-03-15 | /api/v1 | ## Servers | URL | Environment | | --- | --- | | `https://app.monetizekit.app/api/v1` | Development environment | | `https://app.monetizekit.app/api/v1` | Staging environment | | `https://app.monetizekit.app/api/v1` | Production environment | ## entitlements operations ### List customer entitlements `GET /entitlements/{customerId}` — Returns effective entitlements for the customer. Operation ID: entitlements.list. Required scopes: entitlements:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `customerId` | path | yes | Customer ID | { "type": "string" } | "cust_dev_1001" | #### Responses `200` — Success ```json { "type": "array", "items": { "type": "object", "required": [ "featureKey", "type", "sources" ], "properties": { "featureKey": { "type": "string" }, "type": { "type": "string" }, "effectiveValue": {}, "sources": { "type": "array", "items": { "type": "string" } } } } } ``` ```json [ { "featureKey": "api_access", "type": "boolean", "effectiveValue": true, "sources": [ "plan" ] } ] ``` ### Check entitlement decision `GET /entitlements/{customerId}/{featureKey}` — Returns access decision for one feature gate. Operation ID: entitlements.check. Required scopes: entitlements:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `customerId` | path | yes | Customer ID | { "type": "string" } | "cust_dev_1001" | | `featureKey` | path | yes | Feature key | { "type": "string" } | "analytics_export" | #### Responses `200` — Success ```json { "type": "object", "required": [ "allowed", "reason" ], "properties": { "allowed": { "type": "boolean" }, "reason": { "type": "string" } } } ``` ```json { "customerId": "cust_dev_1001", "featureKey": "analytics_export", "allowed": true, "type": "boolean", "sources": [ "plan" ], "reason": "Plan includes feature", "reasonCode": "granted" } ``` --- ## Usage and Meters API Reference Source: https://learning.monetizekit.app/docs/api-reference/usage SHA-256: `30a648a8aa3e4ede222bccee253539813a8511aa270fb549680527852815b7ae` # Usage and Meters API Reference REST schemas and generated examples for usage submission, batch ingestion, totals, and dimensional breakdowns. Mock API reference used by the interactive docs explorer. | OpenAPI version | Contract version | REST base path | | --- | --- | --- | | 3.1.0 | 2026-03-15 | /api/v1 | ## Servers | URL | Environment | | --- | --- | | `https://app.monetizekit.app/api/v1` | Development environment | | `https://app.monetizekit.app/api/v1` | Staging environment | | `https://app.monetizekit.app/api/v1` | Production environment | ## usage operations ### Submit usage event `POST /usage/events` — Ingests a metered usage event. Operation ID: usage.submit. Required scopes: usage:write. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `Idempotency-Key` | header | yes | Client-generated idempotency key | { "type": "string" } | "idem_2f5fd2b7a1" | #### Request schema ```json { "type": "object", "required": [ "customerId", "meterId", "value" ], "properties": { "customerId": { "type": "string" }, "meterId": { "type": "string" }, "value": { "type": "number" } } } ``` #### Request example ```json { "customerId": "cust_dev_1001", "meterId": "api_requests", "value": 15, "occurredAt": "2026-03-15T12:00:00.000Z" } ``` #### Responses `201` — Recorded ```json { "type": "object", "properties": { "id": { "type": "string" }, "customerId": { "type": "string" }, "meterId": { "type": "string" }, "eventName": { "type": "string" }, "value": { "type": "number" }, "status": { "type": "string" }, "occurredAt": { "type": "string" }, "createdAt": { "type": "string" } } } ``` ```json { "id": "evt_9012", "customerId": "cust_dev_1001", "meterId": "api_requests", "eventName": "usage.recorded", "value": 15, "status": "success", "occurredAt": "2026-03-15T12:00:00.000Z", "createdAt": "2026-03-15T12:00:00.000Z" } ``` ### Submit a batch of usage events `POST /usage/events/batch` — Ingests up to 500 usage events in one request. Each item carries its own idempotency key, so replaying a window missed during an outage converges without duplicates while preserving each event's original occurredAt. Item-level failures do not fail the batch. Each accepted item names its stored event by eventId; pass ?include=events to receive the full event object per item. Operation ID: usage.submitBatch. Required scopes: usage:write. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `include` | query | no | Comma-separated extras to include per result. `events` adds the stored event object (the shape POST /usage/events returns) to every created or duplicate item; omitted by default because a 500-item batch would return roughly 200 KB of copies of the request. | { "type": "string", "enum": [ "events" ] } | "events" | #### Request schema ```json { "type": "object", "required": [ "events" ], "properties": { "events": { "type": "array", "items": { "type": "object", "required": [ "customerId", "meterId", "value", "idempotencyKey" ], "properties": { "customerId": { "type": "string" }, "meterId": { "type": "string" }, "value": { "type": "number" }, "idempotencyKey": { "type": "string" }, "occurredAt": { "type": "string" } } } } } } ``` #### Request example ```json { "events": [ { "customerId": "cust_dev_1001", "meterId": "api_requests", "value": 15, "idempotencyKey": "idem_replay_0001", "occurredAt": "2026-03-15T11:00:00.000Z" }, { "customerId": "cust_dev_1001", "meterId": "api_requests", "value": 8, "idempotencyKey": "idem_replay_0002", "occurredAt": "2026-03-15T11:30:00.000Z" } ] } ``` #### Responses `200` — Batch processed ```json { "type": "object", "required": [ "summary", "results" ], "properties": { "summary": { "type": "object", "required": [ "total", "created", "duplicate", "errors" ], "properties": { "total": { "type": "number" }, "created": { "type": "number" }, "duplicate": { "type": "number" }, "errors": { "type": "number" } } }, "results": { "type": "array", "items": { "type": "object", "required": [ "index", "idempotencyKey", "status" ], "properties": { "index": { "type": "number" }, "idempotencyKey": { "type": "string" }, "status": { "type": "string", "enum": [ "created", "duplicate", "error" ] }, "eventId": { "type": "string", "description": "Id of the stored event, on created and duplicate items." }, "event": { "type": "object", "description": "The stored event, only when the request asked for ?include=events." }, "error": { "type": "object", "description": "On error items: the same code and message a single-event request would return.", "properties": { "code": { "type": "string" }, "message": { "type": "string" } } } } } } } } ``` ```json { "summary": { "total": 2, "created": 1, "duplicate": 1, "errors": 0 }, "results": [ { "index": 0, "idempotencyKey": "idem_replay_0001", "status": "created", "eventId": "evt_9013" }, { "index": 1, "idempotencyKey": "idem_replay_0002", "status": "duplicate", "eventId": "evt_9014" } ] } ``` ### Get usage counter `GET /usage/{customerId}/{meterId}` — Returns current counter for a customer and meter. Operation ID: usage.retrieve. Required scopes: usage:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `customerId` | path | yes | Customer ID | { "type": "string" } | "cust_dev_1001" | | `meterId` | path | yes | Meter key | { "type": "string" } | "api_requests" | #### Responses `200` — Success ```json { "type": "object", "properties": { "customerId": { "type": "string" }, "meterId": { "type": "string" }, "current": { "type": "number" }, "limit": { "type": "number" } } } ``` ```json { "customerId": "cust_dev_1001", "meterId": "api_requests", "current": 120, "limit": 1000 } ``` ### Get usage breakdown `GET /usage/{customerId}/{meterId}/breakdown` — Returns usage grouped by a required dimension. Operation ID: usage.breakdown. Required scopes: usage:read. #### Parameters | Name | In | Required | Description | Schema | Example | | --- | --- | --- | --- | --- | --- | | `customerId` | path | yes | Customer ID | { "type": "string" } | "cust_dev_1001" | | `meterId` | path | yes | Meter key | { "type": "string" } | "api_requests" | | `dimension` | query | yes | Dimension to group usage by | { "type": "string" } | "model" | #### Responses `200` — Success ```json { "type": "object", "properties": { "meterId": { "type": "string" }, "dimension": { "type": "string" }, "window": { "type": "string" }, "total": { "type": "number" }, "totalCreditCost": { "type": "number" }, "breakdown": { "type": "array", "items": { "type": "object", "properties": { "value": { "type": "string" }, "total": { "type": "number" }, "count": { "type": "number" }, "creditCost": { "type": "number" } } } } } } ``` ```json { "meterId": "api_requests", "dimension": "model", "window": "all", "total": 120, "totalCreditCost": 42, "breakdown": [ { "value": "gpt-4.1", "total": 120, "count": 4, "creditCost": 42 } ] } ``` --- ## Webhooks and Events API Reference Source: https://learning.monetizekit.app/docs/api-reference/webhooks SHA-256: `79cedadd7566cab7f15c24dc1099a9cf95dd0cb930d30c80d0a32238f41c20f0` # Webhooks and Events API Reference REST schemas and generated examples for webhook endpoint registration and delivery management. Mock API reference used by the interactive docs explorer. | OpenAPI version | Contract version | REST base path | | --- | --- | --- | | 3.1.0 | 2026-03-15 | /api/v1 | ## Servers | URL | Environment | | --- | --- | | `https://app.monetizekit.app/api/v1` | Development environment | | `https://app.monetizekit.app/api/v1` | Staging environment | | `https://app.monetizekit.app/api/v1` | Production environment | ## webhooks operations ### List webhook endpoints `GET /webhooks/endpoints` — Returns configured webhook endpoints. Operation ID: listWebhookEndpoints. Required scopes: webhooks:read. #### Responses `200` — Success ```json { "type": "object", "properties": { "data": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "string" }, "url": { "type": "string" } } } } } } ``` ```json { "data": [ { "id": "wh_001", "url": "https://example.local/hooks/monetizekit" } ] } ``` ### Create webhook endpoint `POST /webhooks/endpoints` — Registers a new webhook endpoint. Operation ID: createWebhookEndpoint. Required scopes: webhooks:write. #### Request schema ```json { "type": "object", "required": [ "url", "events" ], "properties": { "url": { "type": "string" }, "events": { "type": "array", "items": { "type": "string" } } } } ``` #### Request example ```json { "url": "https://example.local/hooks/monetizekit", "events": [ "customer.created" ] } ``` #### Responses `201` — Created ```json { "type": "object", "properties": { "id": { "type": "string" }, "secret": { "type": "string" } } } ``` ```json { "id": "wh_002", "secret": "whsec_placeholder" } ``` --- ## Integrations API Reference Source: https://learning.monetizekit.app/docs/api-reference/integrations SHA-256: `8ace3b2a09b7b056649f88beacfb65f04cd0bc710c4851b470f8ba236c9f0606` # Integrations API Reference REST schemas and generated examples for connecting and managing third-party integrations. Mock API reference used by the interactive docs explorer. | OpenAPI version | Contract version | REST base path | | --- | --- | --- | | 3.1.0 | 2026-03-15 | /api/v1 | ## Servers | URL | Environment | | --- | --- | | `https://app.monetizekit.app/api/v1` | Development environment | | `https://app.monetizekit.app/api/v1` | Staging environment | | `https://app.monetizekit.app/api/v1` | Production environment | ## integrations operations ### Connect Stripe `POST /integrations/stripe` — Creates a Stripe connect session for workspace setup. Operation ID: connectStripe. Required scopes: integrations:manage. #### Request schema ```json { "type": "object", "required": [ "action" ], "properties": { "action": { "type": "string", "enum": [ "connect", "disconnect", "set_webhook_secret" ] }, "apiKey": { "type": "string" }, "secret": { "type": "string" } } } ``` #### Request example ```json { "action": "connect", "apiKey": "rk_test_placeholder" } ``` #### Responses `200` — Success ```json { "type": "object", "required": [ "ok" ], "properties": { "ok": { "type": "boolean" } } } ``` ```json { "ok": true } ``` --- ## GraphQL Explorer Source: https://learning.monetizekit.app/docs/graphql SHA-256: `7bf2570dad14b9257ef68f1669a687c7c190d961a2fb20a42354deca049358d8` # GraphQL Explorer Browse the complete GraphQL schema and run operations against the interactive explorer. ## GraphQL endpoint `https://app.monetizekit.app/api/graphql` > [!NOTE] Authentication and execution > > You can browse the schema and examples without signing in. Sign in and provide your own API token to execute live operations. ## Schema ### OBJECT Query | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `plan` | Plan | key: String! (required) | 4 | Get one plan with entitlements | No | | `customers` | [Customer] | first: Int, after: String | 6 | List customers | No | | `entitlementCheck` | EntitlementDecision | customerId: ID! (required), featureKey: String! (required) | 3 | Check one entitlement decision | No | | `usageCounter` | UsageCounter | customerId: ID! (required), meterKey: String! (required) | 3 | Fetch usage counter | No | | `creditBalance` | CreditBalance | customerId: ID! (required) | 3 | Fetch customer credits | No | ### OBJECT Mutation | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `createCustomer` | Customer | input: CreateCustomerInput! (required) | 5 | Create a customer | No | | `submitUsage` | UsageEventResult | input: UsageEventInput! (required) | 5 | Submit usage event | No | ### OBJECT Subscription | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `usageUpdated` | UsageCounter | customerId: ID! (required) | 2 | Usage stream updates | No | ### OBJECT Customer | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `id` | ID! | None | 1 | — | No | | `externalId` | String! | None | 1 | — | No | | `status` | String! | None | 1 | — | No | | `subscriptions` | [SubscriptionPlan] | None | 2 | — | No | ### OBJECT Plan | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `id` | ID! | None | 1 | — | No | | `key` | String! | None | 1 | — | No | | `name` | String! | None | 1 | — | No | | `entitlements` | [Entitlement] | None | 3 | — | No | | `legacyFlags` | [String] | None | 2 | — | Use entitlements instead of legacyFlags; removal v2.4 | ### OBJECT Entitlement | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `featureKey` | String! | None | 1 | — | No | | `value` | String! | None | 1 | — | No | ### OBJECT EntitlementDecision | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `allowed` | Boolean! | None | 1 | — | No | | `reason` | String! | None | 1 | — | No | ### OBJECT UsageCounter | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `meterKey` | String! | None | 1 | — | No | | `current` | Int! | None | 1 | — | No | | `limit` | Int | None | 1 | — | No | ### OBJECT CreditBalance | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `available` | Int! | None | 1 | — | No | | `pending` | Int! | None | 1 | — | No | ### OBJECT SubscriptionPlan | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `id` | ID! | None | 1 | — | No | | `planKey` | String! | None | 1 | — | No | ### OBJECT UsageEventResult | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `accepted` | Boolean! | None | 1 | — | No | | `eventId` | ID! | None | 1 | — | No | ### INPUT_OBJECT CreateCustomerInput | Input field | Type | Required | Description | | --- | --- | --- | --- | | `externalId` | String! | yes | — | | `name` | String | no | — | ### INPUT_OBJECT UsageEventInput | Input field | Type | Required | Description | | --- | --- | --- | --- | | `customerId` | ID! | yes | — | | `meterKey` | String! | yes | — | | `value` | Int! | yes | — | ### OBJECT Webhook | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `id` | ID! | None | 1 | — | No | | `url` | String! | None | 1 | — | No | ### OBJECT Meter | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `id` | ID! | None | 1 | — | No | | `key` | String! | None | 1 | — | No | ### OBJECT Feature | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `id` | ID! | None | 1 | — | No | | `key` | String! | None | 1 | — | No | ### OBJECT LegacyPlan | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `id` | ID! | None | 1 | — | No | ### INTERFACE Node | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `id` | ID! | None | 1 | — | No | ## Curated examples ### Plan with entitlements ```graphql query PlanWithEntitlements($key: String!) { plan(key: $key) { id key entitlements { featureKey value } } } ``` Variables ```json { "key": "starter_monthly" } ``` ### Customers with subscriptions ```graphql query CustomersWithSubscriptions($first: Int) { customers(first: $first) { id externalId subscriptions { id planKey } } } ``` Variables ```json { "first": 20 } ``` ### Single entitlement check ```graphql query SingleEntitlement($customerId: ID!, $featureKey: String!) { entitlementCheck(customerId: $customerId, featureKey: $featureKey) { allowed reason } } ``` Variables ```json { "customerId": "cust_dev_1001", "featureKey": "analytics_export" } ``` ### Usage data ```graphql query UsageData($customerId: ID!, $meterKey: String!) { usageCounter(customerId: $customerId, meterKey: $meterKey) { meterKey current limit } } ``` Variables ```json { "customerId": "cust_dev_1001", "meterKey": "api_requests" } ``` ### Credit balances ```graphql query CreditBalances($customerId: ID!) { creditBalance(customerId: $customerId) { available pending } } ``` Variables ```json { "customerId": "cust_dev_1001" } ``` ## Shared query seed ### Shared: Plan Health ```graphql query SharedPlanHealth($key: String!) { plan(key: $key) { id key name } } ``` ### Shared: Usage Check ```graphql query SharedUsageCheck($customerId: ID!, $meterKey: String!) { usageCounter(customerId: $customerId, meterKey: $meterKey) { current limit } } ``` --- ## GraphQL Queries Source: https://learning.monetizekit.app/docs/graphql/queries SHA-256: `7b08ffec5b31d542f8da453d0d40aff64e90ac3304862ee40d2f083cc349e6fd` # GraphQL Queries Query operation schemas and runnable GraphQL examples. ## GraphQL endpoint `https://app.monetizekit.app/api/graphql` > [!NOTE] Authentication and execution > > You can browse the schema and examples without signing in. Sign in and provide your own API token to execute live operations. ## Query operations ### OBJECT Query | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `plan` | Plan | key: String! (required) | 4 | Get one plan with entitlements | No | | `customers` | [Customer] | first: Int, after: String | 6 | List customers | No | | `entitlementCheck` | EntitlementDecision | customerId: ID! (required), featureKey: String! (required) | 3 | Check one entitlement decision | No | | `usageCounter` | UsageCounter | customerId: ID! (required), meterKey: String! (required) | 3 | Fetch usage counter | No | | `creditBalance` | CreditBalance | customerId: ID! (required) | 3 | Fetch customer credits | No | ## Curated examples ### Plan with entitlements ```graphql query PlanWithEntitlements($key: String!) { plan(key: $key) { id key entitlements { featureKey value } } } ``` Variables ```json { "key": "starter_monthly" } ``` ### Customers with subscriptions ```graphql query CustomersWithSubscriptions($first: Int) { customers(first: $first) { id externalId subscriptions { id planKey } } } ``` Variables ```json { "first": 20 } ``` ### Single entitlement check ```graphql query SingleEntitlement($customerId: ID!, $featureKey: String!) { entitlementCheck(customerId: $customerId, featureKey: $featureKey) { allowed reason } } ``` Variables ```json { "customerId": "cust_dev_1001", "featureKey": "analytics_export" } ``` ### Usage data ```graphql query UsageData($customerId: ID!, $meterKey: String!) { usageCounter(customerId: $customerId, meterKey: $meterKey) { meterKey current limit } } ``` Variables ```json { "customerId": "cust_dev_1001", "meterKey": "api_requests" } ``` ### Credit balances ```graphql query CreditBalances($customerId: ID!) { creditBalance(customerId: $customerId) { available pending } } ``` Variables ```json { "customerId": "cust_dev_1001" } ``` --- ## GraphQL Mutations Source: https://learning.monetizekit.app/docs/graphql/mutations SHA-256: `bc9b2e5475c9dd57ba0f8c931994ac830f8e18c51329a24d59d4b40370d1667f` # GraphQL Mutations Mutation operation schemas and runnable GraphQL write examples. ## GraphQL endpoint `https://app.monetizekit.app/api/graphql` > [!NOTE] Authentication and execution > > You can browse the schema and examples without signing in. Sign in and provide your own API token to execute live operations. ## Mutation operations ### OBJECT Mutation | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `createCustomer` | Customer | input: CreateCustomerInput! (required) | 5 | Create a customer | No | | `submitUsage` | UsageEventResult | input: UsageEventInput! (required) | 5 | Submit usage event | No | --- ## GraphQL Subscriptions Source: https://learning.monetizekit.app/docs/graphql/subscriptions SHA-256: `58126fb18df23b19a4dea27e849107ef0373682ebc0f48c5d357f6ca8be3eda6` # GraphQL Subscriptions Subscription operation schemas and runnable real-time GraphQL examples. ## GraphQL endpoint `https://app.monetizekit.app/api/graphql` > [!NOTE] Authentication and execution > > You can browse the schema and examples without signing in. Sign in and provide your own API token to execute live operations. ## Subscription operations ### OBJECT Subscription | Field | Type | Arguments | Complexity | Description | Deprecated | | --- | --- | --- | --- | --- | --- | | `usageUpdated` | UsageCounter | customerId: ID! (required) | 2 | Usage stream updates | No | --- ## Guides Source: https://learning.monetizekit.app/docs/guides SHA-256: `69af2748c152c8ba9eb29705a18c8118f8521e03dee0f299f4eafb54f2c79f90` # Guides Choose a complete implementation or operations guide for a specific platform concern. Advanced implementation patterns and operational guidance — each guide is a complete, standalone reference for one part of the platform. ### Entitlement patterns Boolean gates, limit checks, and metered entitlements — the verdict model, resolution layering, and caching-safe recheck triggers. [Open guide](/docs/guides/entitlement-patterns) ### Caching What the API marks as cacheable, what to cache yourself, and the invalidation events that keep both layers correct. [Open guide](/docs/guides/caching) ### Metering best practices Idempotent usage submission, batching high-frequency meters, threshold UX, and drift reconciliation. [Open guide](/docs/guides/metering) ### Webhook verification and retries Register endpoints, verify signatures against the raw body, and process retried deliveries idempotently. [Open guide](/docs/guides/webhooks) ### Migration guide URL-path versioning, deprecation detection, dual-read fallbacks, and staged rollouts for breaking changes. [Open guide](/docs/guides/migration) ### Audit and trace Propagate request IDs end-to-end and correlate API activity, webhook deliveries, and the audit log. [Open guide](/docs/guides/audit-trace) ### Events & Webhook Explorer Browse every webhook event type with sample payloads, and verify signatures interactively. [Open guide](/docs/guides/events) ### Node SDK integration Enriched decisions with reason codes, batch checks, caching with explicit degradation, credit reservations, and the SDK's two extension points. [Open guide](/docs/guides/sdk-node) ### Clerk identity integration Connect your Clerk instance to sync users and organizations as customers, then resolve sessions to customer ids on every request. [Open guide](/docs/guides/clerk-identity) ### PostHog packaging analytics Stream entitlement denials into your PostHog project — with explicit identity mapping, volume caps, and a preview of every event before anything is sent. [Open guide](/docs/guides/posthog-analytics) ### OpenTelemetry visibility One-line decision spans and bounded metrics on your existing OTel setup, with a deep link from every span to the exact evaluation record. [Open guide](/docs/guides/opentelemetry) --- ## Entitlement Evaluation Patterns Source: https://learning.monetizekit.app/docs/guides/entitlement-patterns SHA-256: `a52a1e40177f3d7fa88adebe0d8c1135fef4b272d31a263d5c0648821804d92f` # Entitlement Evaluation Patterns A complete reference for boolean gates, limit checks, and metered entitlements — from resolution layering to caching and error handling. Every gated feature, resource limit, and billable action in your product resolves through one of three entitlement check shapes. Picking the right shape — and branching on the right field in the response — is the single most common source of subtle monetization bugs. This guide walks through all three, how they resolve across plan/add-on/override layers, and how to wire them into REST, GraphQL, and SDK call sites correctly the first time. ## The three check shapes | Shape | Answers | Endpoint | Possible verdicts | | --- | --- | --- | --- | | Boolean gate | Can this customer use the feature at all? | `GET /entitlements/{customerId}/{featureKey}` | `ALLOW`DENY`` | | Limit check | Has the customer reached a hard cap on a resource? | `GET /entitlements/{customerId}/{featureKey}` | `ALLOW`DENY`` | | Metered entitlement | Should this usage event be billed, and is the customer still within budget? | `POST /usage/events` | `RECORDED`DEGRADE`REQUIRE_TOP_UP`DENY`` | ## Node SDK method reference The Node SDK exposes four methods that cover all three check shapes above — there is no separate "limit check" method; limit-type features are read from the same `entitlements.check()` call as boolean gates. | Method | Used for | | --- | --- | | `mk.entitlements.check(customerId, featureKey)` | Boolean gates and limit checks (1 & 2 below) | | `mk.entitlements.getAll(customerId)` | Rendering a full pricing/settings page (see FAQ) | | `mk.usage.submit({ customerId, meterId, value, idempotencyKey })` | Metered entitlements (3 below) | | `mk.usage.get(customerId, meterId)` | Raw meter consumption — not a limit check (see callout) | > [!NOTE] Combined check: POST /entitlements/preflight > > For a single call that resolves entitlement, budget, and credit balance together (e.g. before starting a paid job), use `POST /entitlements/preflight` with `{ customerId, featureKey, estimatedValue, requiredCredits }`. It returns `allowed` plus nested `entitlement`/`budget`/ `credits` objects and a `reasons` array explaining any denial. This endpoint is REST and GraphQL only — the installed `@monetizekit/node` SDK has no `entitlements.preflight()` method yet, so call it with `fetch` directly. ## Decision verdicts Every entitlement check resolves to exactly one of five verdicts. Branch on the verdict — inferred from the response fields below — never on raw HTTP status, so the same decision model works across REST, GraphQL, and every SDK. | Verdict | Meaning | Typical response shape | | --- | --- | --- | | `ALLOW` | Entitled — serve the feature. | `{"allowed":true,"reasonCode":"granted","reason":"Entitlement grants access"}` | | `DENY` | Not entitled — block and surface an upgrade path. | `{ "allowed": false, "reasonCode": "not_in_plan", "reason": "Feature is not included in the Pro plan" }` | | `REQUIRE_TOP_UP` | A usage event was still recorded, but a require_topup budget was exceeded — prompt a top-up. | `{ "status": "success", "requiresTopup": true } // from POST /usage/events` | | `DEGRADE` | A usage event was still recorded, but a degrade budget was exceeded — serve a reduced tier. | `{ "status": "success", "degraded": true } // from POST /usage/events` | | `RECORDED` | Metered event accepted for later billing, no budget policy triggered; access continues. | `{"id":"usage_evt_9012","status":"success"}` | > [!TIP] Best practice > > Never branch on the HTTP status code alone. A `403` can mean `DENY` (upsell) or the customer ran out of credits (`REQUIRE_TOP_UP`, which should route to a top-up flow, not an upgrade page). Inspect `allowed` and `reasonCode` together to select the correct verdict, and keep that mapping in one shared helper rather than duplicating it at every call site. ## Resolution layering An entitlement's effective value is resolved by layering three sources, each capable of overriding the one before it: | Layer | Precedence | Description | | --- | --- | --- | | Plan | Base | The subscription's plan version defines the default value for every feature key. | | Add-on | Overrides Plan | Active add-ons raise or unlock entitlements on top of the plan (e.g. extra seats, priority support). | | Override | Overrides Add-on | A per-customer override (granted manually or via a sales-negotiated contract) wins over plan and add-ons. | > [!NOTE] Deterministic tie-breaking > > When two active add-ons define conflicting values for the same feature key (e.g. two seat packs), MonetizeKit takes the highest numeric value for limits and `true` for booleans — an add-on can only expand access, never restrict what the plan already grants. Overrides always win outright regardless of type. ## 1. Boolean gate: "can they use this at all?" Use a boolean gate to hide or block an entire feature — a menu item, an API route, an export button. Check it once per request (or once per page load) and cache the result per [the caching guide](/docs/guides/caching) . ```bash curl -s \ -H "Authorization: Bearer $MONETIZEKIT_API_KEY" \ "$MONETIZEKIT_BASE_URL/entitlements/cust_dev_1001/analytics_export" # {"allowed":true,"reasonCode":"granted","reason":"Entitlement grants access"} ``` ```javascript import { MonetizeKit } from "@monetizekit/node"; const mk = new MonetizeKit({ apiKey: process.env.MONETIZEKIT_API_KEY }); const decision = await mk.entitlements.check("cust_dev_1001", "analytics_export"); if (!decision.allowed) { // Branch on `decision.reasonCode` — a stable machine-readable code // (e.g. "not_in_plan", "limit_reached"). `decision.reason` stays a // human-readable sentence for logs and support tickets. return res.status(403).json({ code: decision.reasonCode, reason: decision.reason, }); } ``` ```python from monetizekit import MonetizeKit mk = MonetizeKit(api_key=os.environ["MONETIZEKIT_API_KEY"]) decision = mk.entitlements.check("cust_dev_1001", "analytics_export") if not decision.allowed: # Branch on decision.reason_code (stable enum, e.g. "not_in_plan"); # decision.reason is the human-readable sentence for logs. raise HTTPException(status_code=403, detail=decision.reason) ``` ```go decision, err := client.Entitlements.Check(ctx, "cust_dev_1001", "analytics_export") if err != nil { return err } if !decision.Allowed { // Branch on decision.ReasonCode (stable enum); Reason is for humans. return fmt.Errorf("feature denied (%s): %s", decision.ReasonCode, decision.Reason) } ``` GraphQL has no single-feature equivalent of `GET /entitlements/{customerId}/{featureKey}` — fetch every effective entitlement for the customer and filter client-side for the key you need. See the [GraphQL Queries reference](/docs/graphql/queries) for the full operation shape: ```graphql query CustomerEntitlements($customerId: String!) { customer(id: $customerId) { entitlements { featureKey allowed effectiveValueJson type sources } } } ``` ## 2. Limit check: "have they hit a cap?" Use a limit check for capacity-bound resources such as seats, projects, or connected integrations — anything with a `usage` / `limit` / `remaining` triple rather than a simple on/off switch. Limit-type features are checked through the exact same endpoint as boolean gates — `GET /entitlements/{customerId}/{featureKey}` — the response just includes the extra fields when the feature is limit-typed. Treat 90%+ utilization as a soft `DEGRADE` signal for in-app nudges, and only hard-block once `remaining === 0`. ```bash curl -s \ -H "Authorization: Bearer $MONETIZEKIT_API_KEY" \ "$MONETIZEKIT_BASE_URL/entitlements/cust_dev_1001/seats" # { "allowed": true, "type": "limit", "usage": 8, "limit": 10, "remaining": 2, ... } ``` ```javascript // Limit checks use the SAME method as boolean gates — the SDK returns // usage/limit/remaining directly on limit-type features, so there is no // separate "usage.get()" call needed here. const entitlement = await mk.entitlements.check("cust_dev_1001", "seats"); if (!entitlement.allowed) { return res.status(429).json({ reason: entitlement.reason }); } if ( entitlement.remaining !== undefined && entitlement.limit !== undefined && entitlement.remaining <= entitlement.limit * 0.1 ) { // Soft threshold — DEGRADE: still allow, but warn the customer in-app. notifyApproachingLimit(entitlement); } ``` ```python entitlement = mk.entitlements.check("cust_dev_1001", "seats") if not entitlement.allowed: raise HTTPException(status_code=429, detail=entitlement.reason) if entitlement.remaining is not None and entitlement.remaining <= entitlement.limit * 0.1: # Soft threshold — DEGRADE: still allow, but warn the customer in-app. notify_approaching_limit(entitlement) ``` > [!NOTE] Not a /usage/{customerId}/{meterId} call > > `GET /usage/{customerId}/{meterId}` reports raw meter consumption (`current`/`unit`/`trend`/`history`) for dashboards and analytics — it has no `limit` field and can't be used to enforce a cap. To enforce a limit, map the resource to a limit-type feature and check it via `GET /entitlements/{customerId}/{featureKey}` instead. ## 3. Metered entitlement: "record and keep serving" Metered entitlements never block the request — they `RECORDED` the usage event for later billing while the feature keeps working. Always send a deterministic `Idempotency-Key` so retried requests (client timeouts, proxy retries) don't double-count usage; MonetizeKit deduplicates identical keys for 24 hours. The full lifecycle — batching, budget policies, and drift reconciliation — is covered in the [Usage Metering Best Practices guide](/docs/guides/metering) . ```bash curl -s -X POST \ -H "Authorization: Bearer $MONETIZEKIT_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: req:cust_dev_1001:req_8f2c1a" \ -d '{"customerId":"cust_dev_1001","meterId":"meter_api_requests","value":1}' \ "$MONETIZEKIT_BASE_URL/usage/events" # {"id":"usage_evt_9012","customerId":"cust_dev_1001","meterId":"meter_api_requests","eventName":"api_request","value":1,"status":"success","occurredAt":"2026-06-14T00:00:00.000Z","createdAt":"2026-06-14T00:00:00.000Z","duplicate":false,"degraded":false,"requiresTopup":false} ``` ```javascript const key = `req:${customerId}:${requestId}`; // deterministic idempotency key const result = await mk.usage.submit({ customerId, meterId: "meter_api_requests", value: 1, idempotencyKey: key, }); // result.status === "success" even though billing settles asynchronously — // this is the RECORDED verdict: access is not gated on ingestion. Watch // result.degraded / result.requiresTopup for soft/hard budget signals. ``` > [!WARNING] Don't gate on RECORDED > > A successful response from `POST /usage/events` only means the event was durably recorded — it says nothing about whether the customer is still within budget. Check `degraded` / `requiresTopup` on that same response (or subscribe to `usage.threshold` webhooks) if the caller also needs a `REQUIRE_TOP_UP` decision, e.g. before rendering a "low balance" banner. > [!TIP] TypeScript caveat: the SDK's declared type lags the REST response > > `mk.entitlements.check()` and `mk.entitlements.getAll()` return the real fields shown above at runtime, but the installed `@monetizekit/node`'s declared return type doesn't yet include > > `allowed` , > > `reason` , > > `usage` , > > `limit` , > > `remaining` , > > `planName` , > > `planVersion` , > > `latencyMs` > > . Plain JavaScript call sites are unaffected; TypeScript call sites should widen the result type (e.g. `as EntitlementResult & FeatureEntitlementCheckResult`) or read these fields from the REST response directly until the SDK's types catch up. ## Caching and recheck triggers Entitlement checks are read-heavy and safe to cache briefly — but a stale `ALLOW` served after a downgrade or cancellation is a real revenue leak. Invalidate any cached decision for a customer whenever one of these webhook events fires (verified against the raw payload as described in the [Webhooks guide](/docs/guides/webhooks) ): entitlement.changed subscription.updated subscription.canceled plan.published credit.granted credit.depleted See the [Caching and Edge Evaluation guide](/docs/guides/caching) for TTL and invalidation strategy, and the [Webhooks guide](/docs/guides/webhooks) for verifying and consuming these events reliably. ## Common pitfalls ### Branching on HTTP status A `403` from a boolean gate and a `403` from a depleted credit balance require different UI. Always read `reasonCode`, not just the status code. ### Caching past a webhook event A TTL cache alone is not enough. Explicitly bust the cache key for a customer on any of the recheck-trigger events above, not just on your own mutation flows. ### Gating on metered writes `POST /usage/events` is fire-and-forget by design (`RECORDED`). Don't block the feature on its response — check the counter or subscribe to `usage.threshold` instead. ### Skipping idempotency keys Client retries on `POST /usage/events` without an `Idempotency-Key` will double-bill. Derive the key deterministically from the source event, not `Math.random()`. ## FAQ ### Can I check multiple entitlements in one call? Yes — `GET /entitlements/{customerId}` (without a feature key) returns every effective entitlement for the customer in one response, which is cheaper than N individual gate checks when rendering a full pricing/settings page. ### What happens if a plan and an override disagree? The override always wins, regardless of whether it is more or less permissive than the plan default. Overrides are intended for explicit, auditable exceptions (see the [Audit and Trace guide](/docs/guides/audit-trace) ) — they are not merged with plan values the way add-ons are. ### Should I evaluate entitlements client-side or server-side? Always enforce server-side. Client-side checks (via `@monetizekit/react`) are for UI responsiveness only — hiding a button before the network round-trip completes — and must never be the sole gate in front of a paid feature. ## Related guides ### Caching and Edge Evaluation Cache entitlement decisions safely without serving stale access. [Open guide](/docs/guides/caching) ### Usage Metering Best Practices Publish accurate usage with idempotency and anomaly detection. [Open guide](/docs/guides/metering) ### Webhook Verification and Retries Consume recheck-trigger events reliably and idempotently. [Open guide](/docs/guides/webhooks) ### Audit and Trace Correlate entitlement decisions with the audit log for compliance. [Open guide](/docs/guides/audit-trace) --- ## Caching and Edge Evaluation Source: https://learning.monetizekit.app/docs/guides/caching SHA-256: `89c2400903999aa65b7db3c5a2eb93e46083c3e4e0b28b84806758da00ea03d8` # Caching and Edge Evaluation Cache entitlement lookups aggressively without ever serving a stale access decision. Entitlement checks sit on the hot path of nearly every request — a paywalled route, a feature-flagged UI element, a rate-limited API call. Read-heavy and latency-sensitive, they are an ideal caching target, but caching an access decision is not the same as caching a product listing: serving `ALLOW` for a few seconds after a cancellation is a real revenue and security leak. This guide covers what the API marks as cacheable and why it stays on your side of the connection, what you should cache yourself, and the invalidation triggers that keep both layers correct — see the [Entitlement Evaluation Patterns guide](/docs/guides/entitlement-patterns) first if you haven't settled on which check shape you're caching. ## What the API already caches The single-feature entitlement endpoint marks its response as cacheable for 60 seconds by the caller's own cache — a browser, an HTTP client with a cache, or a private caching proxy you run. It is deliberately `private`: an entitlement decision is scoped to the API key that asked for it, so it is never stored by a shared cache such as a CDN, where it could be served to a request that carries no key at all. It sets exactly three cache-related headers — `Cache-Control` , `Cache-Tag` , `Surrogate-Key` — no vendor-specific `CDN-Cache-Control` or similar. ```bash HTTP/1.1 200 OK Content-Type: application/json X-API-Version: v1 X-Request-Id: 7c2f6e1a-0e3b-4b9a-9a9f-8e2c9e6f0d21 Cache-Control: private, max-age=60, stale-while-revalidate=10 Cache-Tag: entitlements-customer-cust_dev_1001,entitlements-customer-cust_dev_1001-feature-analytics_export Surrogate-Key: entitlements-customer-cust_dev_1001 entitlements-customer-cust_dev_1001-feature-analytics_export {"customerId":"cust_dev_1001","featureKey":"analytics_export","allowed":true,"effectiveValue":true,"type":"boolean","sources":["Plan"],"reason":"Entitlement grants access","reasonCode":"granted","planName":"Pro","planVersion":3,"latencyMs":4} ``` - `Cache-Control: private, max-age=60, stale-while-revalidate=10` lets the caller's own cache serve the response for up to 60s, and up to 10s more while revalidating in the background. `private` forbids shared caches from storing it. - `Cache-Tag` carries the same two comma-separated tags as `Surrogate-Key` below — one scoped to the whole customer ( `entitlements-customer-cust_dev_1001`) and one scoped to this specific feature ( `entitlements-customer-cust_dev_1001-feature-analytics_export`) — so a tag-aware private cache can invalidate either granularity. - `Surrogate-Key: entitlements-customer-cust_dev_1001 entitlements-customer-cust_dev_1001-feature-analytics_export` gives a surrogate-key-aware private caching layer the same two keys, so it can purge exactly the affected customer/feature pair on mutation instead of a blanket flush. ## Cache policy by endpoint | Endpoint | Cacheable | Why | | --- | --- | --- | | `GET /entitlements/{customerId}/{featureKey}` | Yes — private, 60s | Single-feature checks are the hottest read path; a 60s TTL in the caller's own cache absorbs repeat checks without ever sharing a decision across callers. | | `GET /entitlements/{customerId}` | No (no-store) | The full batch response changes more frequently and is cheaper to recompute than to keep coherent. | | `GET /usage/{customerId}/{meterId}` | Client-side only, short TTL | Counters mutate on every metered event; the API does not set edge cache headers on this route. | | `POST /usage/events` | No | Mutating endpoint. Deduplicated via Idempotency-Key, not cached. | | `POST /usage/events/batch` | No | Mutating endpoint. Deduplicated per item via each event's `idempotencyKey`, not cached. | > [!WARNING] Never cache the batch endpoint > > `GET /entitlements/{customerId}` intentionally sends `Cache-Control: no-store`. It returns the customer's full entitlement set, which changes on any plan, add-on, or override mutation — caching it trades a small latency win for a much larger correctness risk. Prefer single-feature checks on hot paths and reserve the batch call for pages that render many gates at once and can tolerate a fresh read each time. ## Adding your own application-layer cache Most server-side HTTP clients do not cache at all, so the `private` directive above only helps browsers and clients you have configured with a cache. For server-rendered pages that check several gates per request, layer a short-TTL cache in front of the SDK call, keyed identically to the API's surrogate key so invalidation stays consistent across both layers. ```javascript const cache = new Map(); // swap for Redis/Memcached in production async function checkEntitlement(customerId, featureKey) { const cacheKey = `ent:${customerId}:${featureKey}`; const hit = cache.get(cacheKey); if (hit && hit.expiresAt > Date.now()) return hit.decision; const decision = await mk.entitlements.check(customerId, featureKey); cache.set(cacheKey, { decision, expiresAt: Date.now() + 30_000 }); // 30s TTL return decision; } function invalidateCustomer(customerId) { for (const key of cache.keys()) { if (key.startsWith(`ent:${customerId}:`)) cache.delete(key); } } ``` ```javascript async function checkEntitlement(customerId, featureKey) { const cacheKey = `ent:${customerId}:${featureKey}`; const cached = await redis.get(cacheKey); if (cached) return JSON.parse(cached); const decision = await mk.entitlements.check(customerId, featureKey); await redis.set(cacheKey, JSON.stringify(decision), "EX", 30); return decision; } // Invalidate every cached key for a customer on a recheck-trigger webhook. async function invalidateCustomer(customerId) { const keys = await redis.keys(`ent:${customerId}:*`); if (keys.length) await redis.del(keys); } ``` ```python def check_entitlement(customer_id: str, feature_key: str) -> dict: cache_key = f"ent:{customer_id}:{feature_key}" cached = redis_client.get(cache_key) if cached: return json.loads(cached) decision = mk.entitlements.check(customer_id, feature_key) redis_client.set(cache_key, json.dumps(decision), ex=30) return decision # Invalidate every cached key for a customer on a recheck-trigger webhook. def invalidate_customer(customer_id: str) -> None: for key in redis_client.scan_iter(f"ent:{customer_id}:*"): redis_client.delete(key) ``` ## Invalidate on the right events Because the API response is only ever cached on your side, MonetizeKit cannot purge it for you. Your application-layer cache does not know about a subscription, override, or add-on mutation unless you tell it — subscribe to the webhook events below and bust your cache keys in the handler: ```javascript app.post("/webhooks/monetizekit", async (req, res) => { const event = verifyAndParse(req); // see the Webhooks guide const INVALIDATING_EVENTS = new Set([ "entitlement.changed", "subscription.created", "subscription.updated", "subscription.canceled", "plan.published", "credit.granted", "credit.depleted", ]); if (INVALIDATING_EVENTS.has(event.type) && event.data.customerId) { await invalidateCustomer(event.data.customerId); } res.sendStatus(200); }); ``` Full event payload shapes are in the [Events & Webhook Explorer](/docs/guides/events) , and signature verification (including replay protection and idempotent processing on your side) is covered in the [Webhooks guide](/docs/guides/webhooks) . ## Common pitfalls ### Caching the batch endpoint It changes too often to cache safely. Cache individual feature checks instead, or shorten your own TTL to a few seconds if you must cache it client-side. ### TTL longer than your invalidation guarantees If your webhook consumer can lag (queue backlog, downstream outage), your effective staleness window is TTL + consumer lag. Keep TTLs short enough to bound worst-case staleness on their own. ### One cache key per customer instead of per feature Coarse keys force a full-customer flush on every mutation. Key by `{customerId}:{featureKey}` (mirroring the API's per-feature `Surrogate-Key` tag) so unrelated feature checks stay warm. ### No negative caching A customer who is repeatedly denied a feature (e.g. a bot probing routes) will otherwise generate one API call per request. Cache `DENY` results too, with the same TTL. ## FAQ ### Do I need a cache at all? For a browser calling with a publishable key, usually not — the browser honours the 60s `private` TTL on its own. For server-side code, yes if the check is on a hot path: server HTTP clients do not cache by default, so every check is a round trip to the API until you add an application-layer cache such as the ones above. ### What TTL should I use client-side? Match or undercut the API's 60s TTL — 15 to 30 seconds is a reasonable default for most products. Shorten it further for high-stakes gates (e.g. seat limits during a live sales demo) and lengthen it for low-stakes UI toggles. ### Why is the response not cached at the edge? An entitlement decision is an authenticated response. A shared cache keys on the URL, not on who asked, so an edge-cached decision would be served to any request for that URL — including one with no API key — until the TTL expired. Keeping the cache on your side keeps the decision behind your key. ### How do I force a fresh read? If a workflow needs a guaranteed-fresh read (for example, immediately after your own mutation), bypass or invalidate your own cache entry for that customer/feature pair; the API itself always evaluates fresh. ## Related guides ### Entitlement Evaluation Patterns Boolean gates, limit checks, and metered entitlements in depth. [Open guide](/docs/guides/entitlement-patterns) ### Webhook Verification and Retries Consume invalidation-triggering events securely and idempotently. [Open guide](/docs/guides/webhooks) ### Events & Webhook Explorer Browse every event type and payload shape. [Open guide](/docs/guides/events) --- ## Usage Metering Best Practices Source: https://learning.monetizekit.app/docs/guides/metering SHA-256: `71b2cd0136413582251bb8189a6fcb0777f87002f8f4a999085f91ea1387116b` # Usage Metering Best Practices Publish accurate, deduplicated usage at scale and catch drift before it reaches an invoice. Metered billing is only as trustworthy as the events feeding it. A single duplicated event overcharges a customer; a single dropped event undercharges you. This guide covers the full lifecycle of a usage event — idempotent submission, batching for high-frequency meters, threshold-based UX, and the reconciliation habits that catch drift before it reaches an invoice. See the [Entitlement Evaluation Patterns guide](/docs/guides/entitlement-patterns) for how a metered event resolves into a RECORDED/DEGRADE/REQUIRE_TOP_UP verdict on the caller side. ## 1. Submit events idempotently Every `POST /usage/events` call requires an `Idempotency-Key` header. MonetizeKit deduplicates identical keys within a workspace for 24 hours — replayed requests (client timeouts, proxy retries, at-least-once queue delivery) return the original response instead of recording a second event. This mirrors the same idempotent-processing discipline the [Webhooks guide](/docs/guides/webhooks) recommends for inbound deliveries. ```bash curl -s -X POST \ -H "Authorization: Bearer $MONETIZEKIT_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: req:cust_dev_1001:req_8f2c1a" \ -d '{"customerId":"cust_dev_1001","meterId":"meter_api_requests","value":1}' \ "$MONETIZEKIT_BASE_URL/usage/events" # 201 Created -> {"id":"usage_evt_9012","customerId":"cust_dev_1001","meterId":"meter_api_requests","eventName":"api_request","value":1,"status":"success","occurredAt":"2026-06-14T00:00:00.000Z","createdAt":"2026-06-14T00:00:00.000Z","duplicate":false,"degraded":false,"requiresTopup":false} ``` Every recorded event carries two timestamps. `occurredAt` is the **event time** — when the metered activity actually happened. It defaults to now, and you may set it in the request body (an ISO 8601 timestamp, no more than 120 days in the past) to import history or replay a window you missed during an outage. `createdAt` is the **ingestion time** — when MonetizeKit accepted the event. It is always stamped server-side and cannot be set by callers, so a replayed backlog stays visible as ingestion lag instead of masquerading as real-time traffic. ```javascript // Derive the key from something already unique to the source action — // never Math.random() or Date.now(), which won't survive a retry. const idempotencyKey = `req:${customerId}:${requestId}`; const result = await mk.usage.submit({ customerId, meterId: "meter_api_requests", value: 1, idempotencyKey, }); // result.status === "success"; check result.degraded / result.requiresTopup // for soft/hard budget signals (see "Design around budget policies" below). ``` ```python idempotency_key = f"req:{customer_id}:{request_id}" result = mk.usage.submit( customer_id=customer_id, meter_id="meter_api_requests", value=1, idempotency_key=idempotency_key, ) ``` > [!TIP] Derive keys, don't generate them > > Build the idempotency key from data that is already unique to the triggering action — a request ID, a queue message ID, a `(userId, action, timestamp-bucket)` tuple. A key generated fresh on every attempt (e.g. a random UUID per call) defeats deduplication entirely, because a retried call generates a *different* key. ## 2. Batch high-frequency meters For meters that increment many times per second (token counts, API request counts), one HTTP call per event is wasteful. `POST /usage/events/batch` accepts up to **500 events in one request**. Each item takes the same fields as a single event plus a required per-item `idempotencyKey`, and may carry its own `occurredAt` — which also makes this the sanctioned catch-up path after an outage: replay the missed window with each event's original time and duplicates converge instead of double-counting. The batch endpoint answers `200 OK` with a `summary` and one entry in `results` per submitted event, **in request order**. Each result's `status` is `created`, `duplicate`, or `error`; accepted items also carry the stored event's `eventId`. A failing item (unknown customer, `deny`-policy budget exceeded, `occurredAt` out of range) never fails its siblings — its `error` carries the same `code` a single-event request would return, and you retry only those items with the same keys. The full event object per item (the same shape a single `POST /usage/events` returns) is opt-in: add `?include=events` when you need it, and leave it off for routine flushes — at 500 events it is roughly 200 KB of copies of what you just sent. Budgets are applied per `(customer, meter, subjectId)` group within the batch — events without a `subjectId` form their own group per customer and meter. A group that no budget policy would touch is written in one statement, and a threshold crossed inside it fires a single `usage.threshold` webhook whose `value` is that group's accepted total. A group whose total *would* trigger a policy is processed in request order, so exactly the events that fit under a `deny` limit are accepted and the rest come back as `402 BUDGET_EXCEEDED` items. ```bash curl -s -X POST \ -H "Authorization: Bearer $MONETIZEKIT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"events":[ {"customerId":"cust_dev_1001","meterId":"meter_api_requests","value":1,"idempotencyKey":"req:cust_dev_1001:req_8f2c1a"}, {"customerId":"cust_dev_1001","meterId":"meter_api_requests","value":1,"idempotencyKey":"req:cust_dev_1001:req_8f2c1b","occurredAt":"2026-06-14T00:00:00.000Z"} ]}' \ "$MONETIZEKIT_BASE_URL/usage/events/batch" # 200 OK -> {"summary":{"total":2,"created":1,"duplicate":1,"errors":0}, # "results":[{"index":0,"idempotencyKey":"req:cust_dev_1001:req_8f2c1a","status":"duplicate","eventId":"evt_9013"}, # {"index":1,"idempotencyKey":"req:cust_dev_1001:req_8f2c1b","status":"created","eventId":"evt_9014"}]} # Add ?include=events to the URL to get each stored event object back as "event". ``` Buffer events in-process and flush on a timer or size threshold, keeping each buffered event's own idempotency key so a crashed flush can safely retry. The SDK's `mk.usage.submit` is a single-event call; flush the buffer to the batch endpoint over HTTP. ```javascript // Buffer events in-process and flush them as one batch request — // far cheaper than one HTTP round trip per event for high-frequency meters. class UsageBuffer { constructor({ baseUrl, apiKey, flushIntervalMs = 5_000, maxBatchSize = 500 }) { this.baseUrl = baseUrl; this.apiKey = apiKey; this.buffer = []; this.maxBatchSize = maxBatchSize; // the endpoint caps a batch at 500 events setInterval(() => this.flush(), flushIntervalMs); } record(customerId, meterId, value, idempotencyKey) { // Capture event time now; it is preserved even if the flush is delayed. const occurredAt = new Date().toISOString(); this.buffer.push({ customerId, meterId, value, idempotencyKey, occurredAt }); if (this.buffer.length >= this.maxBatchSize) void this.flush(); } async flush() { if (this.buffer.length === 0) return; const events = this.buffer.splice(0, this.maxBatchSize); const response = await fetch(`${this.baseUrl}/usage/events/batch`, { method: "POST", headers: { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json", }, body: JSON.stringify({ events }), }); const { results } = await response.json(); // Re-queue only the items that failed; their keys make the retry safe. const failed = results.filter((result) => result.status === "error"); this.buffer.unshift(...failed.map((result) => events[result.index])); } } ``` ## 3. Design around budget policies and thresholds A budget has two independent settings that are easy to conflate: a **policy** (`deny`, `degrade`, or `require_topup`) that decides what happens to *this* request once accepting it would push usage past the budget's hard limit, and a separate **soft/hard threshold** pair (an arbitrary value you configure per budget, not a fixed 80%/100%) that fires an advisory `usage.threshold` webhook the moment either is first crossed — regardless of policy. Subscribe to that webhook (verified the same way as any other event — see the [Webhooks guide](/docs/guides/webhooks) ) to notify customers proactively instead of polling `GET /usage/{customerId}/{meterId}`. | Policy | Behavior when the hard limit would be exceeded | Response | | --- | --- | --- | | `deny` | Event is rejected before being recorded — no usage row is written. | `402 BUDGET_EXCEEDED` | | `degrade` | Event is still recorded; response flags the request so you can serve a reduced tier. | `201 Created — { "degraded": true, ... }` | | `require_topup` | Event is still recorded; response flags that a credit top-up is needed. | `201 Created — { "requiresTopup": true, ... }` | > [!NOTE] Threshold crossing is advisory, not enforcement > > The `usage.threshold` webhook fires whenever any budget's configured `softThreshold` or `hardThreshold` is crossed, independent of that budget's policy — including on budgets with no enforcement effect at all. Use it to drive notifications; use the response fields in the table above (or a `deny` rejection) to drive actual feature-gating decisions. ## 4. Reconcile on a schedule Idempotency prevents duplicate submissions, but it can't catch events you never sent — a crashed worker before the buffer flushed, a silently-swallowed exception in an event handler. Run a periodic job comparing MonetizeKit's reported totals against your own source of truth (application logs, a data warehouse) and alert on drift beyond a small tolerance. If a customer disputes a specific event, the [Audit and Trace guide](/docs/guides/audit-trace) covers how to isolate it by request ID. ```sql -- Nightly job: compare MonetizeKit's counter against your own source of truth SELECT m.customer_id, m.meter_id, m.reported_total, s.actual_total, (m.reported_total - s.actual_total) AS drift FROM monetizekit_usage_snapshot m JOIN internal_usage_source s ON m.customer_id = s.customer_id AND m.meter_id = s.meter_id WHERE ABS(m.reported_total - s.actual_total) > 5; -- flag drift above tolerance ``` > [!NOTE] Treat drift as a leading indicator > > Small, consistent drift (a handful of events per day) usually means a race condition in your batching logic. Sudden, large drift after a deploy almost always means a broken idempotency key derivation or a change to which events are instrumented at all — investigate deploys first. ## Common pitfalls ### Random idempotency keys A key that changes on every retry attempt provides zero deduplication. Derive it from the triggering action, not the HTTP call. ### Fire-and-forget with no error handling A `201 Created` means the event was recorded, not billed — invoicing settles later. Log failures from `POST /usage/events` and retry with the same idempotency key — don't drop them silently. ### Losing the buffer on crash In-process buffers lose unflushed events on a crash or deploy. For meters where every event matters financially, back the buffer with a durable queue rather than an in-memory array. ### No reconciliation job Idempotency catches duplicates, not gaps. Without a periodic drift check, missing events go unnoticed until a customer disputes an invoice. ## FAQ ### How long is an idempotency key remembered? 24 hours, scoped per workspace. A retry after that window will be recorded as a new event, so make sure your retry logic has a much shorter window than that. ### Can I submit negative usage to correct an overcount? No — `value` must be a positive number; the API rejects zero and negative values with a `400`. Events are also immutable once accepted, so there is no self-serve correction endpoint today. Prevent overcounts up front with a correct idempotency key, and escalate a confirmed overcount through support for a manual adjustment. ### What happens if I exceed the API rate limit while batching? You'll receive a `429` whose message states how many seconds to wait, and `X-RateLimit-Reset` tells you exactly when the window resets — there is no `Retry-After` header. Back off until that reset time rather than retrying immediately; a smaller `maxBatchSize` reduces how often you hit the limit in the first place. ## Related guides ### Entitlement Evaluation Patterns How metered entitlements resolve into REQUIRE_TOP_UP and RECORDED verdicts. [Open guide](/docs/guides/entitlement-patterns) ### Events & Webhook Explorer Payload shape for usage.threshold and every other event type. [Open guide](/docs/guides/events) ### Audit and Trace Correlate a disputed usage event back to its request ID. [Open guide](/docs/guides/audit-trace) --- ## Webhook Verification and Retries Source: https://learning.monetizekit.app/docs/guides/webhooks SHA-256: `afac686769b7d48b4bdfd8b2e814e5afdecd82dab4b59f45582770cbfafdcb66` # Webhook Verification and Retries Register endpoints, verify signatures correctly, and process retried deliveries idempotently. Webhooks push state changes to your system the moment they happen — a subscription upgrade, a usage threshold crossing, a credit grant — without polling. Because deliveries happen over the open internet and are retried automatically, a production-grade handler needs three things: a correct signature check, replay protection, and idempotent processing. This guide covers all three, plus the full delivery lifecycle and how to debug a failing endpoint. If you're integrating webhooks as part of a broader migration off a legacy integration, see the [Migration Guide](/docs/guides/migration) for the same dual-read rollout pattern applied to endpoint cutovers. ## 1. Register an endpoint Pick from the 15 event types across 6 categories cataloged in the [Events & Webhook Explorer](/docs/guides/events) . The signing secret (`whsec_` followed by 48 hex characters, matching `^whsec_[0-9a-f]{48}$`) is shown exactly once at creation — store it immediately, since later views only show the prefix. The number of endpoints you can register is governed by your plan's `max_webhook_endpoints` entitlement, which resolves the same way any other entitlement does — see the [Entitlement Evaluation Patterns guide](/docs/guides/entitlement-patterns) for the boolean-gate and limit-check shapes. ```bash # Settings → Webhooks → Add Endpoint # 1. Enter the HTTPS URL that will receive deliveries. # 2. Select which event types should trigger this endpoint. # 3. Save — the signing secret (whsec_...) is generated and shown once. ``` ```bash curl -s -X POST \ -H "Authorization: Bearer $MONETIZEKIT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"url":"https://example.com/hooks/monetizekit","events":["customer.created","subscription.updated","usage.threshold"]}' \ "$MONETIZEKIT_BASE_URL/webhooks/endpoints" # 201 -> { "id": "wh_002", "secret": "whsec_..." } -- shown once, store it now ``` > [!NOTE] No CLI create command > > Endpoints are registered from the Dashboard or the REST API only — the CLI's `webhooks` commands (below) cover testing and diagnosing existing endpoints, not creating them. ## 2. Verify the signature Every delivery is signed with HMAC-SHA256 over `"{timestamp}.{rawBody}"` using your endpoint's signing secret. The signature is sent as `X-MonetizeKit-Signature` (format `sha256=`), and the timestamp as `X-MonetizeKit-Timestamp` (Unix seconds); the event type is also sent separately as `X-MonetizeKit-Event`. Always verify against the **raw** request body — a JSON `parse` → `stringify` round trip can reorder keys or change whitespace and invalidate the signature. If you're also propagating a request ID for support/debugging, see the [Audit and Trace guide](/docs/guides/audit-trace) for how delivery IDs and request IDs correlate in the audit log. ```javascript import { createHmac, timingSafeEqual } from "node:crypto"; function verify(rawBody, headers, secret) { const timestamp = headers["x-monetizekit-timestamp"]; const signature = headers["x-monetizekit-signature"]; // "sha256=..." // Reject stale timestamps first — this is your handler's responsibility; // the HMAC check below only proves the signature, not the age, is valid. if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) { return false; } const expected = "sha256=" + createHmac("sha256", secret) .update(`${timestamp}.${rawBody}`) .digest("hex"); const a = Buffer.from(expected); const b = Buffer.from(signature); return a.length === b.length && timingSafeEqual(a, b); } ``` ```javascript import { verifyWebhookSignature } from "@monetizekit/node"; app.post("/hooks/monetizekit", express.raw({ type: "application/json" }), (req, res) => { const timestamp = req.headers["x-monetizekit-timestamp"]; // verifyWebhookSignature() only checks the HMAC — it does not reject stale // timestamps, so your handler must do it before (or after) calling it. if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) { return res.sendStatus(401); } const ok = verifyWebhookSignature({ rawBody: req.body, // must be the raw, unparsed body timestamp, signature: req.headers["x-monetizekit-signature"], secret: process.env.MONETIZEKIT_WEBHOOK_SECRET, }); if (!ok) return res.sendStatus(401); handleEvent(JSON.parse(req.body)); res.sendStatus(200); }); ``` ```python import hashlib, hmac, time def verify(raw_body: bytes, timestamp: str, signature: str, secret: str) -> bool: if abs(time.time() - int(timestamp)) > 300: return False # reject stale timestamps payload = f"{timestamp}.".encode() + raw_body expected = "sha256=" + hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature) ``` ```go func Verify(rawBody []byte, timestamp, signature, secret string) bool { ts, err := strconv.ParseInt(timestamp, 10, 64) if err != nil { return false } if delta := time.Now().Unix() - ts; delta > 300 || delta < -300 { return false // reject stale timestamps } mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(timestamp + "." + string(rawBody))) expected := "sha256=" + hex.EncodeToString(mac.Sum(nil)) return hmac.Equal([]byte(expected), []byte(signature)) } ``` > [!WARNING] Reject stale timestamps > > Every snippet above compares `X-MonetizeKit-Timestamp` against the current time and rejects anything older than 5 minutes before checking the signature. This is your handler's responsibility — `verifyWebhookSignature()` (and the equivalent manual HMAC check) only proves the signature is valid, not that it's recent. Without the staleness check, a captured request/signature pair remains replayable indefinitely. ## Try it: compute a signature Paste a secret, timestamp, and body below to compute the expected signature interactively, or paste a signature you received to verify it against these values. ## 3. Process deliveries idempotently Every delivery carries a unique `X-MonetizeKit-Delivery` ID that stays constant across retries of the same logical event. Store processed delivery IDs and skip work you've already done — this is what makes retries safe rather than a source of duplicate side effects (double-sent emails, double-decremented credits). The same idempotency discipline applies to usage events on your own side — see the [Usage Metering Best Practices guide](/docs/guides/metering) . ```javascript app.post("/hooks/monetizekit", async (req, res) => { if (!verifyWebhookSignature(/* ... */)) return res.sendStatus(401); const event = JSON.parse(req.body); const deliveryId = req.headers["x-monetizekit-delivery"]; // Dedupe by delivery ID before processing — QStash retries reuse the same ID. const alreadyProcessed = await store.hasProcessed(deliveryId); if (alreadyProcessed) return res.sendStatus(200); await handleEvent(event); await store.markProcessed(deliveryId); res.sendStatus(200); // respond only after the handler durably completes }); ``` Respond `2xx` only once your handler has durably committed the work — an early `200` followed by a crash before persisting looks identical to success and the event will never be retried. ## Delivery lifecycle and retries Delivery has two modes, chosen automatically based on your environment's configuration — you don't select one: when Upstash QStash is configured, delivery is queued to QStash (durable, retried on Upstash's own schedule) and immediately marked `202`. Otherwise, delivery is a direct best-effort POST with a 10s timeout, and failed direct-mode deliveries are retried by an hourly job until either delivered or **5 total attempts** have been made — there is no sub-hour backoff between attempts in direct mode, so exhausting the budget takes up to roughly 4 hours after the first failure. | Status | Meaning | | --- | --- | | `202 (queued)` | Dispatched via QStash; Upstash owns retries from here on. | | `2xx` | Endpoint returned a 2xx within the 10s direct-delivery timeout. | | `non-2xx / timeout (retrying)` | Direct-mode delivery failed with budget remaining; retried on the next hourly job. | | `non-2xx / timeout (exhausted)` | All 5 attempts failed. No further retries; investigate in Recent Deliveries. | A direct-mode delivery is retried only on a non-2xx response or a timeout. Any 2xx — including `200` or `204` — stops retries, so make sure your handler doesn't return `2xx` before it's actually safe to stop. An endpoint that accumulates 10 consecutive delivery failures is automatically disabled; re-enable it from Settings → Webhooks once the underlying issue is fixed. Cache invalidation triggered by these same events is covered in the [Caching and Edge Evaluation guide](/docs/guides/caching) . ## Testing and debugging locally ### Send a fixture event (CLI) ```bash monetizekit webhooks test https://localhost:3000/hooks/monetizekit entitlement.changed ``` Posts a built-in fixture payload and prints whether the endpoint responded 2xx. Its signature uses a simplified `HMAC-SHA256(secret, payload)` scheme (no timestamp, no `sha256=` prefix) — good for checking basic reachability, not for exercising your real `X-MonetizeKit-Signature` verification code. ### Tunnel to localhost Use a tunnel (ngrok or similar) to expose a local handler during development, and register that HTTPS tunnel URL as the endpoint. Swap in your production URL before shipping. ### Inspect delivery logs Settings → Webhooks → Recent Deliveries shows each attempt's event, endpoint, HTTP status, attempt count, and timestamp. ```bash monetizekit diagnose webhooks ``` ## Common pitfalls ### Verifying a re-serialized body Frameworks that auto-parse JSON before your handler runs (Express's default `json()` middleware) can subtly change byte-for-byte content. Use the raw body parser on the webhook route specifically. ### Rotating a secret without a grace period Rolling a signing secret invalidates the old one immediately. In-flight retries signed with the previous secret will fail verification — roll during low-traffic windows and keep the old secret ready to accept for a short overlap if your infrastructure supports dual verification. ### No dedupe on X-MonetizeKit-Delivery Retries are expected, not exceptional. If your handler isn't idempotent on delivery ID, a transient network blip on your side will duplicate side effects on the 2nd attempt. ### Blocking the response on slow work If your handler does slow downstream work (emails, third-party calls), enqueue it and respond `200` promptly once the event is durably recorded — don't let a slow downstream call trigger a delivery timeout and an unnecessary retry. ## FAQ ### What timeout does MonetizeKit use before treating a direct-mode delivery as failed? 10 seconds. Slow or hanging endpoints are treated the same as a failure and scheduled for retry — do the heavy work asynchronously after responding. (QStash-mode deliveries use Upstash's own timeout, not this one.) ### Can I subscribe one endpoint to every event type? Yes, but consider splitting high-volume categories (usage) from low-volume, high-stakes ones (subscriptions, credits) across separate endpoints so a slow handler for one category doesn't create a retry backlog for the other. ### What happens after all 5 retry attempts fail? The delivery keeps its last non-2xx status and no further attempts are made — there is no separate terminal "failed" status distinct from the HTTP status code it last got. It remains visible in Settings → Webhooks → Recent Deliveries for manual inspection, but there is no automatic replay — reconcile via the underlying resource's API (e.g. re-fetch the subscription) if you suspect you missed an update. ## Related guides ### Events & Webhook Explorer Browse every event type and sample payload. [Open guide](/docs/guides/events) ### Caching and Edge Evaluation Use webhook events as cache-invalidation triggers. [Open guide](/docs/guides/caching) ### Audit and Trace Correlate a delivery ID with an audit log entry. [Open guide](/docs/guides/audit-trace) --- ## Events & Webhook Explorer Source: https://learning.monetizekit.app/docs/guides/events SHA-256: `190e4d1d853c36f063de8cd7c10235bf9bb4f7c14b99dac691973a23d354f17e` # Events & Webhook Explorer Browse the webhook event catalog with sample payloads, and verify signatures interactively. ## Verify a signature MonetizeKit signs each delivery: HMAC-SHA256 over `"{timestamp}.{rawBody}"` using your endpoint secret, sent as `X-MonetizeKit-Signature`. Paste your values to compute and verify it — see the [Webhooks guide](/docs/guides/webhooks) for registering an endpoint and processing retried deliveries idempotently, and the [Caching and Edge Evaluation guide](/docs/guides/caching) for using these same events as cache-invalidation triggers. ## customers `customer.created` A new customer was created in the workspace. ```json { "id": "evt_sample_00000000", "type": "customer.created", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "customerId": "cust_123", "customerName": "Acme Corp", "customerEmail": "ops@acme.test" } } ``` `customer.updated` A customer's attributes or plan changed. ```json { "id": "evt_sample_00000000", "type": "customer.updated", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "customerId": "cust_123", "changes": [ "plan" ] } } ``` ## subscriptions `subscription.created` A customer subscribed to a plan. ```json { "id": "evt_sample_00000000", "type": "subscription.created", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "customerId": "cust_123", "subscriptionId": "sub_123", "planId": "plan_pro" } } ``` `subscription.updated` A subscription changed status, plan, or term. ```json { "id": "evt_sample_00000000", "type": "subscription.updated", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "subscriptionId": "sub_123", "status": "active", "planId": "plan_pro" } } ``` `subscription.canceled` A subscription was canceled. ```json { "id": "evt_sample_00000000", "type": "subscription.canceled", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "subscriptionId": "sub_123", "canceledAt": "2026-06-14T00:00:00.000Z" } } ``` ## catalog `plan.created` A new plan was created (not yet published). ```json { "id": "evt_sample_00000000", "type": "plan.created", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "planId": "plan_pro", "status": "draft", "version": 1 } } ``` `plan.updated` A plan's definition changed (features, pricing, or limits). ```json { "id": "evt_sample_00000000", "type": "plan.updated", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "planId": "plan_pro", "version": 2 } } ``` `plan.published` A plan version was published. ```json { "id": "evt_sample_00000000", "type": "plan.published", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "planId": "plan_pro", "status": "published", "version": 3 } } ``` `plan.archived` A plan was archived and can no longer be assigned to new customers. ```json { "id": "evt_sample_00000000", "type": "plan.archived", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "planId": "plan_legacy", "status": "archived", "version": 4 } } ``` `feature.updated` A feature definition changed. ```json { "id": "evt_sample_00000000", "type": "feature.updated", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "featureId": "feat_seats", "key": "seats" } } ``` `feature.deleted` A feature definition was deleted. ```json { "id": "evt_sample_00000000", "type": "feature.deleted", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "featureId": "feat_legacy", "key": "legacy_feature" } } ``` ## usage `usage.threshold` A customer crossed a soft or hard usage budget threshold. ```json { "id": "evt_sample_00000000", "type": "usage.threshold", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "customerId": "cust_123", "meterId": "meter_api", "thresholdValue": 100000, "currentUsage": 100250 } } ``` ## credits `credit.granted` Credits were granted to a customer wallet. ```json { "id": "evt_sample_00000000", "type": "credit.granted", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "customerId": "cust_123", "amount": 500, "reason": "manual_grant" } } ``` `credit.depleted` A customer's credit balance reached zero. ```json { "id": "evt_sample_00000000", "type": "credit.depleted", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "customerId": "cust_123", "balance": 0 } } ``` ## entitlements `entitlement.changed` A customer's effective entitlement for a feature changed (plan, add-on, or override). ```json { "id": "evt_sample_00000000", "type": "entitlement.changed", "workspace_id": "ws_example", "created_at": "2026-06-14T00:00:00.000Z", "data": { "customerId": "cust_123", "featureKey": "seats", "allowed": true, "effectiveValue": 25 } } ``` ## Activation funnel Beyond the webhook events above, the embed SDK posts activation-funnel telemetry to the ingestion beacon `POST /api/v1/events/funnel` as visitors move through your pricing widget. Send `widget_view` when the pricing table mounts and `checkout_started` when the upgrade call-to-action is clicked; the `activated` stage is derived server-side from the MRR movement ledger and is never posted by the widget. The request body carries `event` (`widget_view` or `checkout_started`), `sessionId` (a stable anonymous id per widget mount), and an optional `planId`; a successful call returns `201` with the recorded event id. Authenticate this beacon with a browser-embedded publishable key — the one write that accepts one — which is exempt from the per-key scope check because it records only an anonymous, workspace-scoped funnel-telemetry row (plus the standard first-API-call activation telemetry the API layer records for any authenticated request) and touches no tenant business data or configuration. See [Authentication](/docs/getting-started/authentication) for the publishable-key exception. --- ## Migration Guide Source: https://learning.monetizekit.app/docs/guides/migration SHA-256: `5946e9a1848e218e5f9edbd8acd76c772da3d4b8393d7a5072481e7df0a78127` # Migration Guide Detect deprecated usage, migrate safely with dual-read patterns, and roll out in stages. MonetizeKit versions the API by URL path and gives every deprecation a minimum warning window before removal — but a smooth migration is still on you: you need to know what you're using, verify the replacement, and roll the change out without a big-bang cutover. This guide covers all three. ## How versioning works | Aspect | Detail | | --- | --- | | Version scheme | URL-path versioning — /api/v1/, with /api/v2/ served alongside it once introduced. | | Unsupported version | 404 with error: "unsupported_api_version". | | Current version header | X-API-Version: v1 is present on every response, success or error. | | Minimum deprecation window | At least one minor release with active warnings before removal; enterprise plans may get an extended window. | ## 1. Find what you're using that's deprecated Deprecated endpoints and GraphQL fields are marked in the [API reference](/docs/api-reference) and enumerated with removal dates on the [Deprecations](/docs/changelog/deprecations) page. There is no per-call response header that flags deprecated usage — the signal lives in the docs, not the wire protocol — so cross-reference the paths your integration actually calls (from your own access logs) against that page: ```bash # There is no runtime Deprecation/Sunset response header to grep for — the # only version-related header on every response is X-API-Version. Detect # deprecated usage by cross-referencing every endpoint/field your integration # calls against the Deprecations page (/docs/changelog/deprecations) instead. # Example entry as of this writing: # # item: "GET /integrations/legacy-webhooks" # removalVersion: v2.4 # removalDate: 2026-09-30 # migrationInstructions: "Use GET /webhooks/endpoints for endpoint management and replay operations." grep -A1 "GET /integrations/legacy-webhooks" your-access-log.txt ``` Anything already returning `404 unsupported_api_version` means you're calling an unsupported version prefix outright, not merely a deprecated field — fix that first. ## 2. Add a dual-read fallback Don't cut over in one deploy. Read from the new shape first and fall back to the deprecated one only if the new call fails, logging every fallback so you can measure how much traffic still depends on the old path. ```javascript // Neither the deprecated endpoint nor its replacement has an // @monetizekit/node SDK method (webhook endpoint management is REST-only — // see the Webhooks guide), so call both directly. async function getWebhookIntegrations() { const [legacy, current] = await Promise.allSettled([ fetch(`${baseUrl}/integrations/legacy-webhooks`, { headers: authHeaders }).then((r) => r.json()), fetch(`${baseUrl}/webhooks/endpoints`, { headers: authHeaders }).then((r) => r.json()), ]); // Prefer the new shape; fall back only while the legacy path is still live. if (current.status === "fulfilled") return normalize(current.value.data); console.warn("Falling back to deprecated GET /integrations/legacy-webhooks", legacy); if (legacy.status === "fulfilled") return normalize(legacy.value.data); throw new AggregateError([current.reason, legacy.reason], "Both webhook integration APIs failed"); } ``` ## 3. Roll out in stages Once the new path works, move traffic over gradually and deterministically — the same workspace should stay on the same side of the gate across requests, so a problem surfaces as a contained blast radius rather than a random flicker. ```javascript // Route a percentage of traffic to the new integration path first, // keyed deterministically so a given workspace always lands on the same side. function useNewWebhooksApi(workspaceId, rolloutPercent) { const bucket = hashToPercent(workspaceId); // stable 0-99 bucket per workspace return bucket < rolloutPercent; } const rolloutPercent = 10; // start small: 10% -> 50% -> 100% over successive deploys const path = useNewWebhooksApi(workspaceId, rolloutPercent) ? "/webhooks/endpoints" : "/integrations/legacy-webhooks"; await fetch(`${baseUrl}${path}`, { headers: authHeaders }); ``` > [!TIP] Watch, then widen > > Hold each rollout percentage long enough to observe error rates and fallback volume before widening it. A migration that silently regresses at 10% and isn't caught until 100% is far more expensive to unwind than one caught early. ## Migration checklist ### Before you remove the old code path ## Common pitfalls ### Waiting until the removal date A removal date is a hard cutoff, not a target to start migrating on. Start as soon as a deprecation is announced — the minimum warning window is the floor, not a comfortable buffer. ### Big-bang cutover Switching every workspace at once means every migration bug ships to every customer at once. A staged percentage rollout turns that into a contained, quickly-reversible blast radius. ### No fallback logging Without logging when the dual-read fallback triggers, you can't tell when it's safe to delete the legacy path — you're guessing instead of measuring. ### Ignoring GraphQL field deprecations Deprecated GraphQL fields (like `legacyFlags`) keep working until removal, so nothing breaks today — but they carry the same removal-date risk as REST endpoints. Check [the GraphQL reference](/docs/graphql) for `deprecationReason` annotations, not just REST responses. ## FAQ ### How much notice do I get before a breaking change? At least one minor release with active deprecation warnings before removal. See [Breaking Changes](/docs/changelog/breaking-changes) for the running list with exact removal dates. ### Will /api/v1 stop working once /api/v2 ships? No — a new major version is served alongside the previous one, not as a replacement for it. `/api/v1` keeps working until it is explicitly deprecated and removed under the same policy as any other endpoint. ### Can I test against a future API version before it's generally available? Watch the Changelog for early-access announcements. Until a version is documented in the API reference, treat any behavior you observe from it as unstable and don't build against it in production. ## Related guides ### Audit and Trace Correlate migration-related errors with request IDs. [Open guide](/docs/guides/audit-trace) ### Webhook Verification and Retries Migrating a webhook integration follows the same dual-read pattern. [Open guide](/docs/guides/webhooks) --- ## Audit and Trace Source: https://learning.monetizekit.app/docs/guides/audit-trace SHA-256: `fd1633a6f0af71dc87f53b3d7ad4a481c56e856c09ec012edecfd2f733815168` # Audit and Trace Propagate request IDs end-to-end and correlate API activity, webhook deliveries, and the audit log. When a customer disputes a charge, an integration silently breaks, or a compliance reviewer asks "who changed this and when," you need a chain of evidence that spans your logs, MonetizeKit's API responses, and the workspace's Audit Log. Every layer of that chain is connected by IDs — this guide shows how to propagate and use them. ## Every response carries a request ID Every REST response — success or error — includes an `X-Request-Id` header. Supply your own value and it's echoed back exactly; omit it and MonetizeKit generates a UUID v4 for you. Log this value at the call site so it's the join key between your application logs and any downstream investigation. ```bash curl -i \ -H "Authorization: Bearer $MONETIZEKIT_API_KEY" \ "$MONETIZEKIT_BASE_URL/plans?page=1&pageSize=1" \ | rg -i "^x-request-id:" # X-Request-Id: 7c2f6e1a-0e3b-4b9a-9a9f-8e2c9e6f0d21 ``` ```bash curl -i \ -H "Authorization: Bearer $MONETIZEKIT_API_KEY" \ -H "X-Request-Id: my-trace-9f2c1a" \ "$MONETIZEKIT_BASE_URL/plans?page=1&pageSize=1" \ | rg -i "^x-request-id:" # X-Request-Id: my-trace-9f2c1a -- echoed back exactly as sent ``` ```javascript const requestId = `svc-${crypto.randomUUID()}`; const response = await fetch(`${baseUrl}/plans?page=1&pageSize=1`, { headers: { Authorization: `Bearer ${apiKey}`, "X-Request-Id": requestId, }, }); logger.info("monetizekit_call", { requestId, status: response.status }); ``` > [!TIP] Generate one ID per logical operation, not per HTTP call > > If a single user action fans out into three API calls (check an entitlement, record usage, create a subscription), give all three the same `X-Request-Id` prefix or a shared correlation field in your own logs. Tracing a single MonetizeKit request ID only gets you one leg of the journey. ## Error responses include the same ID Every error envelope — regardless of status code — nests `code`, `message`, and `request_id` under a single top-level `error` object (plus `details` for field-level validation errors). When a customer reports a failure, ask for `error.request_id` first; it's the fastest way to pull the exact request from logs without guessing at timestamps. Cross-reference `error.code` against the [Error Codes reference](/docs/troubleshooting/error-codes) for known causes and resolutions before escalating. ```json { "error": { "code": "NOT_FOUND", "message": "Customer not found: cust_dev_9999", "request_id": "7c2f6e1a-0e3b-4b9a-9a9f-8e2c9e6f0d21" } } ``` ## Correlate with the Audit Log The workspace Audit Log (Enterprise mode, under `/audit` in the dashboard) is the compliance-grade record of security-relevant actions: CRUD on governed resources, authentication events, approval decisions, and data exports. Each entry records an actor, an actor type, an IP address, the affected resource, and free-form metadata — cross-reference the metadata against the request IDs and delivery IDs you logged on your side. ### Action categories | Action | Meaning | | --- | --- | | `create / update / delete` | CRUD on a governed resource (contract, plan, API key, customer, workspace, etc.). | | `login / logout` | Session-level authentication events for dashboard users. | | `approve / reject` | Decisions on an approval workflow (e.g. a contract or override request). | | `transfer` | Ownership changes — workspace transfer, credit wallet reassignment. | | `read / export` | Sensitive reads and data exports, including audit log CSV exports themselves. | ### Actor types | Actor | Meaning | | --- | --- | | `user` | A dashboard user acting through the UI. | | `api_key` | A REST/GraphQL call authenticated with a service token. | | `webhook` | An inbound integration (e.g. a Stripe webhook) that triggered a state change. | | `system` | An automated internal process (scheduled jobs, reconciliation). | | `integration` | A connected third-party integration acting on the workspace's behalf. | ## Correlate webhook deliveries Webhook-triggered changes appear in the Audit Log with `actorType: "webhook"`. Log the delivery's `X-MonetizeKit-Delivery` ID (see the [Webhooks guide](/docs/guides/webhooks) ) alongside the audit entry's timestamp and resource ID — together they let you prove exactly which delivery attempt caused which downstream state change, which is essential when disputing whether an event was processed once or twice. The same correlation strategy applies to disputed usage events — see the [Usage Metering Best Practices guide](/docs/guides/metering) for the reconciliation job that catches drift before an invoice does. ## Exporting for external review Pull audit entries programmatically with `GET /audit` (scope `audit:view`) — the same API-key auth, rate limiting, and `X-Request-Id`/error-envelope handling as every other REST call in this guide. ```bash curl -s \ -H "Authorization: Bearer $MONETIZEKIT_API_KEY" \ "$MONETIZEKIT_BASE_URL/audit" # { "data": [ { "id": "...", "timestamp": "...", "actor": "...", "actorType": "...", # "actorIp": "...", "action": "...", "resource": "...", "resourceId": "...", # "description": "...", "metadata": { ... } }, ... ] } ``` ### REST API (programmatic, most recent 500) `GET /audit` returns the workspace's 500 most recent entries, newest first — there's no query-param filtering or pagination yet, so page further back or filter by actor/action/date in the dashboard instead. It isn't listed in the [API Reference](/docs/api-reference) explorer because of that limited surface, but the endpoint itself is fully functional today. ### CSV export (bulk, filtered) The Audit Log page's "Export CSV" action exports the currently filtered entries — narrow the filters first (actor, action, date range) so the export matches the scope of your review, then hand the file to a compliance team or archive it externally. > [!NOTE] No self-serve SIEM streaming yet > > If your compliance workflow needs continuous, real-time ingestion into a SIEM rather than periodic polling of `GET /audit` or manual CSV export, that's not a built-in feature today — drive interim alerting off request IDs and webhook delivery correlation as described above. ## Common pitfalls ### Not logging the request ID at the call site If you only discover you need a request ID after an incident, it's too late — log it on every call, success and failure alike, from day one. ### Reusing one request ID across retries A retried call is a distinct request. Reusing the same `X-Request-Id` across retries makes it impossible to tell, from the ID alone, whether a request succeeded on the first or third attempt. ### Exporting unfiltered audit data CSV exports are themselves an `export` action recorded in the log. Filter to the minimum necessary scope before exporting, both for review clarity and for data-minimization compliance requirements. ### Assuming the audit API paginates `GET /audit` has no `page`/`cursor` params — it always returns the 500 most recent entries. Don't build automation that assumes it can page through the full history; use the dashboard's date-range filters and CSV export for anything older. ## FAQ ### Can I set my own X-Request-Id and have it accepted? Yes — any non-empty string is accepted and echoed back verbatim. If you omit the header, MonetizeKit generates a UUID v4 for you and returns it, so the header is always present either way. ### Does the audit log capture read-only API calls? Sensitive reads (like revealing a webhook signing secret) are recorded as `read` actions. Routine, high-volume reads (entitlement checks, usage lookups) are not, to keep the log focused on security- and governance-relevant events rather than every API call. ### How long is audit log data retained? It's a per-workspace setting (Settings → Security → `auditRetentionDays`), defaulting to 365 days if unset. Whatever you configure is clamped to between 90 and 730 days — export data you need to retain longer than that via CSV export rather than assuming indefinite retention. ## Related guides ### Webhook Verification and Retries Delivery IDs are the join key for webhook-triggered audit entries. [Open guide](/docs/guides/webhooks) ### Migration Guide Use request IDs to isolate errors introduced during a migration rollout. [Open guide](/docs/guides/migration) ### Entitlement Evaluation Patterns Overrides are auditable exceptions — see how they resolve. [Open guide](/docs/guides/entitlement-patterns) --- ## Node SDK Integration Source: https://learning.monetizekit.app/docs/guides/sdk-node SHA-256: `28b69c6428b7b2cdabd8fb73c4de2961bf64f4dbebc509884253d7221d346bc3` # Node SDK Integration Integrate the Node SDK for enriched decisions, batch checks, caching, degradation, and credit reservations. `@monetizekit/node` is the reference SDK for server-side entitlement checks, usage metering, and credit operations. This guide covers the integration surface added in v0.2.0: machine-readable decision causes you can branch on, batch checks, a built-in decision cache with explicit offline behavior, atomic credit reservations for uncertain-cost operations, and the `IdentityResolver` / `DecisionObserver` extension points that the Clerk, PostHog, and OpenTelemetry guides plug into. > [!NOTE] Requires @monetizekit/node >= 0.2.0 > > Everything on this page ships in SDK v0.2.0. On v0.1.x, `entitlements.check()` works but returns the pre-enrichment shape, and `mk.entitlements.checkMany(customerId, featureKeys)`, the credit-reservation methods, caching, degradation, and both extension points are unavailable. The underlying REST endpoints (including `POST /entitlements/batch` and the reservation routes) work from any HTTP client regardless of SDK version. ## Install and configure ```bash npm install @monetizekit/node ``` ```typescript import { MonetizeKit } from "@monetizekit/node"; const apiKey = process.env.MONETIZEKIT_API_KEY; if (!apiKey) throw new Error("MONETIZEKIT_API_KEY is required"); export const mk = new MonetizeKit({ apiKey, // mk_test_... or mk_live_... // cache: true uses the defaults (30s TTL, 1000 entries); // pass { ttlMs, maxEntries } to tune. cache: { ttlMs: 30_000, maxEntries: 1_000 }, // What check()/checkMany() do when the API is unreachable. // "throw" (default) | "fail_open" | "fail_closed" degradation: "fail_closed", }); ``` All options besides `apiKey` are optional. Leave `cache` and `degradation` unset and the SDK behaves like v0.1: every check is a network call and API failures throw. ## Enriched decisions: branch on reasonCode Every check returns a stable, machine-readable `reasonCode` alongside the free-form `reason` sentence. Denials additionally carry `resetsAt` (when a metering window resets) and `grantedByPlans` (published plans that would grant the feature or raise the limit) — enough to render a useful paywall instead of a generic “access denied”. ```typescript const decision = await mk.entitlements.check("cust_dev_1001", "api_requests"); if (!decision.allowed) { switch (decision.reasonCode) { case "limit_reached": // decision.resetsAt: ISO timestamp when the metering window resets // decision.grantedByPlans: published plans that raise this limit return res.status(402).json({ error: "limit_reached", retryAfter: decision.resetsAt, upgradeTo: decision.grantedByPlans, }); case "not_in_plan": return res.status(403).json({ error: "not_in_plan", upgradeTo: decision.grantedByPlans, }); case "unknown_feature": // Typo'd feature key or unpublished feature — a bug, not a paywall. throw new Error(`Unknown feature key: ${decision.featureKey}`); } } ``` ```json { "customerId": "cust_dev_1001", "featureKey": "analytics_export", "allowed": true, "effectiveValue": true, "type": "boolean", "sources": [ "Plan" ], "reason": "Entitlement grants access", "reasonCode": "granted", "planName": "Pro", "planVersion": 3, "latencyMs": 4, "cached": false, "degraded": false } ``` | reasonCode | Allowed | Meaning | | --- | --- | --- | | `granted` | Yes | A boolean/enum/string entitlement grants access. | | `granted_unlimited` | Yes | A limit-type feature with an unlimited effective value. | | `granted_no_meter` | Yes | A limit-type feature with no usage meter mapped — the limit cannot be enforced, so access is granted. | | `within_limit` | Yes | Metered usage is below the limit; usage / limit / remaining / resetsAt are populated. | | `limit_reached` | No | Metered usage has reached the limit. resetsAt says when the window resets; grantedByPlans lists plans that raise it. | | `not_in_plan` | No | The feature exists but the customer's plan does not include it. grantedByPlans lists plans that do. | | `unknown_feature` | No | No published feature matches this key — usually a typo, not a paywall. | The API produces exactly 7 codes (the table above). Two more — `sdk_fail_open` and `sdk_fail_closed` — are produced locally by the SDK's degradation fallback and never appear in an API response. ## Batch checks Pages that render many gates at once (a settings screen, a pricing table, a feature matrix) shouldn't pay one round trip per gate. `mk.entitlements.checkMany(customerId, featureKeys)` calls `POST /entitlements/batch`, which resolves the customer once and evaluates up to 50 feature keys against it — duplicate keys are deduplicated, and each result has the same enriched shape as a single check. ```typescript // One request, one customer resolution, up to 50 feature keys. const decisions = await mk.entitlements.checkMany("cust_dev_1001", [ "analytics_export", "api_requests", "sso", ]); // One decision per unique key, same shape as a single check(). const gates = Object.fromEntries(decisions.map((d) => [d.featureKey, d.allowed])); ``` > [!NOTE] Batch responses are never HTTP-cacheable > > Unlike single-feature checks (cacheable by the caller for 60s), the batch endpoint always computes fresh decisions. The SDK still writes each result into its local cache, so a `checkMany` warm-up makes subsequent single `check()` calls for the same keys cache hits. See the [Caching guide](/docs/guides/caching) for the full policy. ## Caching and degradation With `cache` enabled, fresh decisions are served locally (marked `cached: true`) and every API-served decision refreshes the cache. The `degradation` option — throw | fail_open | fail_closed — decides what happens when the API is unreachable, and it always prefers a stale cached decision over a fabricated one. | Mode | On API failure | Use when | | --- | --- | --- | | `throw` | Rethrows the transport error (the default). | You have your own retry/fallback logic, or a failed check must abort the request. | | `fail_open` | Serves a stale cached decision if one exists; otherwise allows with reasonCode sdk_fail_open and degraded: true. | Low-stakes gates where blocking paying users during an outage costs more than a leak. | | `fail_closed` | Serves a stale cached decision if one exists; otherwise denies with reasonCode sdk_fail_closed and degraded: true. | High-stakes gates (credit spend, expensive compute) where an accidental allow is the worse failure. | > [!WARNING] Alert on degraded decisions > > Every fallback decision is flagged `degraded: true` and reported to your `DecisionObserver`s. A sustained stream of degraded decisions means your product is running on guesses — wire an alert on it in your monitoring stack rather than discovering it from a revenue anomaly. ## Credit reservations for uncertain-cost operations AI workloads rarely know their cost up front. A check-then-debit sequence can overspend under concurrency: two requests both pass the balance check, then both debit. Reservations close that window with an atomic hold — reserve the worst case, run the operation, capture the actual cost, and the difference returns to the wallet. ```typescript // Hold credits before an uncertain-cost operation (e.g. an LLM call), // capture the actual cost after, and the remainder returns automatically. const { value } = await mk.credits.withReservation( { customerId: "cust_dev_1001", amount: 100, // worst-case cost ttlSeconds: 300, idempotencyKey: `gen:${requestId}`, }, async () => { const completion = await llm.generate(prompt); return { value: completion, cost: completion.usage.totalCredits }; }, ); // On success: captures the returned cost, releases the rest. // On a thrown error: releases the full hold, then rethrows. ``` `mk.credits.withReservation(data, fn)` wraps the three lifecycle calls; use them directly when capture happens in a different process than the reserve: ```typescript const { reservation } = await mk.credits.reserve({ customerId: "cust_dev_1001", amount: 100, ttlSeconds: 600, }); try { const completion = await llm.generate(prompt); await mk.credits.captureReservation(reservation.id, completion.usage.totalCredits); } catch (error) { await mk.credits.releaseReservation(reservation.id); throw error; } ``` - Endpoints: `POST /credits/reserve`, `GET /credits/reservations/{reservationId}`, `POST /credits/reservations/{reservationId}/capture`, `POST /credits/reservations/{reservationId}/release`. - `ttlSeconds` defaults to 300s and must be between 10s and 86,400s (24h). A hold that is never captured or released is expired by an hourly background job — size the TTL to your operation's worst-case duration, not to “long enough to never expire”. - Reservation states: held → captured → released → expired (`held` resolves to exactly one of the other three, exactly once — capture and release replays are idempotent and concurrent capture/release races have one winner). - Audit trail: a hold writes a `reservation_hold` ledger entry, a release/expiry writes `reservation_release`, and a capture writes a standard `debit` for the captured cost (plus a `reservation_release` for any returned remainder). - Pass an `idempotencyKey` on `reserve` so a retried request re-uses the existing hold instead of double-holding. ## Extension points The SDK exposes exactly two integration interfaces, and every provider integration is an implementation of one of them — so adding Clerk, PostHog, or OpenTelemetry never changes how your product code calls `check()`. ```typescript import { MonetizeKit, type DecisionObserver, type IdentityResolver } from "@monetizekit/node"; const logObserver: DecisionObserver = { onDecision(event) { logger.debug("mk decision", event); }, }; const resolver: IdentityResolver = { async resolveCustomerId(externalId) { return lookupCustomerIdInYourDb(externalId); }, }; const mk = new MonetizeKit({ apiKey: process.env.MONETIZEKIT_API_KEY, observers: [logObserver], identityResolver: resolver, }); const customerId = await mk.resolveCustomerId("user_2abc123"); ``` > [!TIP] Observers can never break a decision > > The SDK swallows anything an observer throws, and observers are invoked synchronously after the decision is made — do async work (network sends, batching) fire-and-forget inside `onDecision`, never `await`ed. ## FAQ ### Should I use the SDK cache or my own Redis cache? The built-in cache is per-process and in-memory — ideal for collapsing repeated checks inside one server, with zero infrastructure. If you run many short-lived instances (serverless) or need cross-instance coherence, layer the Redis pattern from the Caching guide instead; the two compose, but usually one is enough. ### What happens if my process crashes between reserve and capture? The hold stays until its TTL elapses, then the hourly expiry job releases it back to the wallet with a `reservation_release` ledger entry. Nothing is silently lost — but the credits are unavailable to that customer until expiry, which is why TTLs should be as short as the operation allows. ### Can I capture more than I reserved? No — capture is bounded by the held amount. If actual cost can exceed your estimate, reserve the worst case (that is the point of the hold), or split the operation and reserve again for the overage. ## Related guides ### Entitlement Evaluation Patterns Boolean gates, limit checks, and metered entitlements in depth. [Open guide](/docs/guides/entitlement-patterns) ### Entitlements & Caching Where decisions come from and how to cache them safely. [Open guide](/docs/guides/caching) ### Audit & Trace Propagate request IDs and correlate API activity end-to-end. [Open guide](/docs/guides/audit-trace) --- ## Clerk Identity Integration Source: https://learning.monetizekit.app/docs/guides/clerk-identity SHA-256: `7ab28cff8e7c8b39436c43aff3910e19b423ab70d2dc7f85fee898509a5d010a` # Clerk Identity Integration Synchronize Clerk users and organizations, then resolve sessions to MonetizeKit customers. Clerk answers *who is this?*; MonetizeKit answers *what can they do?*. The seam between the two has two halves. The **packaged connection** (Integrations → Clerk) keeps your customer directory in sync: Clerk users and organizations become MonetizeKit customers, automatically, with webhook-driven lifecycle updates and an initial import for existing accounts. The **request-time half** — turning a verified Clerk session into a customer id for entitlement checks — runs in your app through the SDK's `IdentityResolver` extension point. > [!NOTE] SDK half requires @monetizekit/node >= 0.2.0 > > The packaged connection needs no SDK at all. For request-time resolution, `identityResolver` and `mk.resolveCustomerId(externalId, context)` ship in SDK v0.2.0. ## Step 1 — Connect your Clerk instance In **Integrations → Clerk → Connect**, paste your Clerk secret key (`sk_test_…` or `sk_live_…`). MonetizeKit validates the key against the Clerk Backend API, inspects the instance (organizations enabled? how many users and organizations?), and *proposes* an account model. Nothing is applied silently — you confirm or override the proposal before anything connects. The key is envelope-encrypted at rest and never re-displayed. | Account model | Mapping | Fits when | | --- | --- | --- | | `user (B2C)` | Each Clerk user → one MonetizeKit customer | Individual subscriptions; every user has their own plan, usage, and credits. | | `organization (B2B)` | Each Clerk organization → one MonetizeKit customer | Team plans: entitlements, limits, and credit wallets are shared org-wide; members are seats. | | `both` | Users and organizations each become customers | Products where personal and team workspaces coexist; your app decides per-session which subject to bill. | The available models are exactly user, organization, both. If you later need per-member metering inside an org customer, model members as MonetizeKit *entities* under the customer rather than separate customers. > [!NOTE] One Clerk instance, one MonetizeKit account > > A Clerk instance already connected to a different MonetizeKit account is refused at connect time. One instance can back multiple environments *within* one account (test instance → test environment, production → live); it can never span accounts. ## Step 2 — Register the webhook in Clerk After connecting, the dialog shows your workspace's receiver URL: `{your MonetizeKit base URL}/api/webhooks/clerk-sync/{connectionId}`. In the Clerk Dashboard (**Configure → Webhooks → Add endpoint**), create an endpoint with that URL and subscribe it to exactly these event types: | Event | What the sync does | | --- | --- | | `user.created / organization.created` | Creates a customer with the Clerk id stamped in its attributes (clerkUserId / clerkOrganizationId). | | `user.updated / organization.updated` | Updates the customer's name and email; existing attributes are merged, never replaced. | | `user.deleted / organization.deleted` | Archives the customer — it stops being billable, but usage and billing history are preserved. | (6 event types total: user.created, user.updated, user.deleted, organization.created, organization.updated, organization.deleted.) Then copy the endpoint's signing secret (`whsec_…`) back into the MonetizeKit configure dialog. Deliveries are verified against that secret; unverifiable requests are rejected. > [!TIP] Retries and out-of-order deliveries are handled > > Each delivery is applied at most once (deduplicated by Svix message id), and an event older than the state already applied for that user or organization is skipped — a replayed or late webhook never overwrites newer data. ## Step 3 — Import existing accounts The webhook only covers accounts created *after* it exists. For everyone who signed up before, run **Import directory** from the configure dialog. The import pages through your Clerk instance (100 records per page), creates or updates the matching customers, and persists its progress — a failed run resumes where it stopped, and re-running it is idempotent (already-synced accounts converge to the same state instead of duplicating). > [!WARNING] Email conflicts are surfaced, not guessed > > If an existing customer already has a Clerk user's email but is not linked to that Clerk id, the sync skips it and records a conflict rather than silently merging two identities. Resolve those from the dashboard. ## Unsynced accounts — an explicit choice At connect time you record what your app does when it sees an authenticated Clerk account that has no synced customer yet (webhook delay, import not run). The connection stores this policy so the team's intent is explicit; your app's request-time code (next section) is where it takes effect — when `resolveCustomerId` returns `null`: - `create_with_default_plan` (recommended) — treat first sight as signup: create the customer inline on your default plan so the user is never blocked. The sync's idempotent apply converges with it once the webhook lands. - `deny_until_synced` — respond with “no billing account” until the sync catches up; correct for products where a customer must exist before any usage. ## Request-time resolution with the SDK The sync stamps each customer with its Clerk id (in the customer's attributes, visible in the dashboard), but the customer API has no external-id lookup — you cannot ask “which customer belongs to Clerk user X?” per request. Store the mapping where your app already looks on every request: Clerk's `privateMetadata`. ```typescript import { clerkClient } from "@clerk/nextjs/server"; const clerk = await clerkClient(); await clerk.users.updateUserMetadata(clerkUserId, { privateMetadata: { monetizekitCustomerId: customerId }, }); ``` Then implement `IdentityResolver` once, hand it to the SDK constructor, and call `mk.resolveCustomerId(externalId, context)` wherever you have a Clerk user id: ```typescript import { clerkClient } from "@clerk/nextjs/server"; import { MonetizeKit, type IdentityResolver } from "@monetizekit/node"; const apiKey = process.env.MONETIZEKIT_API_KEY; if (!apiKey) throw new Error("MONETIZEKIT_API_KEY is required"); const clerkResolver: IdentityResolver = { async resolveCustomerId(clerkUserId) { const clerk = await clerkClient(); const user = await clerk.users.getUser(clerkUserId); return (user.privateMetadata.monetizekitCustomerId as string | undefined) ?? null; }, }; export const mk = new MonetizeKit({ apiKey, identityResolver: clerkResolver }); ``` ```typescript import { auth } from "@clerk/nextjs/server"; import { mk } from "@/lib/monetizekit"; export async function POST() { const { userId } = await auth(); if (!userId) return new Response("Unauthorized", { status: 401 }); const customerId = await mk.resolveCustomerId(userId); if (!customerId) return new Response("No billing account", { status: 403 }); const decision = await mk.entitlements.check(customerId, "report_generation"); if (!decision.allowed) { return Response.json( { error: decision.reasonCode, upgradeTo: decision.grantedByPlans }, { status: 402 }, ); } return Response.json(await generateReport(customerId)); } ``` > [!WARNING] privateMetadata, not publicMetadata > > `publicMetadata` is readable by the browser. A customer id isn't a secret credential, but exposing it invites clients to send it to your API directly — and any endpoint that trusts a client-supplied customer id lets one user check (or spend) as another. Keep the id server-side and always derive it from the verified session. ## Optional — zero-lookup resolution via session claims The resolver above costs one Clerk Backend API call per resolution. For hot paths, project the metadata into the session token so the customer id arrives with the request: ```typescript import { auth } from "@clerk/nextjs/server"; export async function readBillingIdentityFromSession() { const { userId, sessionClaims } = await auth(); const customerId = sessionClaims?.monetizekitCustomerId as string | undefined; return { userId, customerId }; } ``` ## FAQ ### Do I still need my own Clerk webhook handler for provisioning? No — customer creation, updates, and archival are handled by the packaged connection. Your app only needs the request-time half: reading the customer id from `privateMetadata` (or a session claim) and checking entitlements. If you previously provisioned customers from your own `user.created` handler, you can retire it; the sync's idempotent apply converges with customers it created. ### Should I key customers by email instead? No. Emails change, and a Clerk user can carry several. The Clerk user id is the stable identifier — it is what the sync stamps on the customer — and the customer's email is display/billing contact data kept fresh by user.updated events, not a join key. ### What happens when a Clerk user is deleted? The sync archives the customer: it stops being billable and disappears from active lists, but usage and billing history are preserved. If the deletion is a GDPR erasure request, additionally call the customer erasure endpoint (`POST /customers/{id}/erasure`) to anonymize identifiers while retaining financial records. ### Organizations have no email address — what does the customer get? A deterministic placeholder (`{org id}@clerk-orgs.invalid`), since customers require a unique email per workspace. Treat it as sync-managed: the next `organization.updated` event re-applies it, so keep the real billing contact in the customer's `attributes` (which the sync merges, never replaces) rather than editing the email field. ## Related guides ### Node SDK Integration The IdentityResolver extension point the request-time half builds on. [Open guide](/docs/guides/sdk-node) ### Entitlement Evaluation Patterns What to do with the decision once you have the customer id. [Open guide](/docs/guides/entitlement-patterns) ### Webhook Verification and Retries The same idempotent-consumer discipline, applied to MonetizeKit's own webhooks. [Open guide](/docs/guides/webhooks) --- ## PostHog Packaging Analytics Source: https://learning.monetizekit.app/docs/guides/posthog-analytics SHA-256: `0105ba45c495ee5bc40bd6c97368db19dc0d59bc270bc63a1372ded719cd2ae7` # PostHog Packaging Analytics Stream entitlement denial events to PostHog with explicit identity mapping and bounded volume. Every denied entitlement check is a commercial moment: a customer just hit the edge of what their plan allows. The **packaged destination** (Integrations → PostHog) streams each denial into your PostHog project as an `mk_denial` event carrying the feature, the machine-readable reason, and the plans that would have granted it — the raw material for conversion funnels, feature-wall rankings, and packaging experiments. For richer client-side instrumentation (including *allowed* decisions), the SDK's `DecisionObserver` extension point is the manual half. > [!NOTE] Analytics can never affect enforcement > > Emission is queue-isolated: the entitlement decision path only enqueues a durable delivery row and never waits on PostHog. Capture failures are retried by the hourly drainer and are visible in the configure dialog — a PostHog outage cannot slow down or change a single decision. ## Step 1 — Connect your PostHog project In **Integrations → PostHog → Connect**, paste your project API key (`phc_…`, from PostHog → Project settings). This is the ingestion key — MonetizeKit never asks for a personal API key and never reads from your project. The key is validated against PostHog's read-only `/decide` endpoint, which authenticates it *without creating any event, person, or group*, then stored envelope-encrypted and never re-displayed. Pick your ingestion host (us.i.posthog.com or eu.i.posthog.com) and make two explicit identity choices: | Identity mapping | What each event carries | Fits when | | --- | --- | --- | | `group (default)` | `$groups: { account } + $process_person_profile: false` | B2B / org-backed customers. Events land as group analytics; person profiles are never created for accounts. | | `person` | The customer id as the person distinct_id | B2C products where each MonetizeKit customer is one human. | The mapping choices are exactly group and person. Group-mapped events set `$process_person_profile: false` on the wire, so a group-mapped workspace can never accidentally create person profiles for accounts. Separately, choose how customer identifiers travel: | Identifier mode | Effect | | --- | --- | | `full` | Customer ids are sent as-is (default) — easiest to join against your own data. | | `hashed` | Ids are replaced with a stable SHA-256 hash — cohorts still work, raw ids never leave. | | `omitted` | No customer identifier at all — events are anonymous volume only. | ## Step 2 — Preview before anything is sent Nothing streams until you confirm. Before connecting, the wizard shows two things: a **volume projection** computed from your workspace's own denial history over the last 30 days (so the monthly cap you set is grounded in your real traffic, not a guess), and the **exact event** PostHog will receive — rendered by the same code the delivery pipeline uses, from your most recent real denial when one exists: ```json { "event": "mk_denial", "distinct_id": "cus_sample", "properties": { "feature_key": "advanced_reports", "reason_code": "not_in_plan", "granted_by_plans": [ "Growth", "Scale" ], "environment": "production", "customer_id": "cus_sample", "$process_person_profile": false, "$groups": { "account": "cus_sample" } }, "timestamp": "2026-07-28T12:00:00.000Z" } ``` | Property | Meaning | | --- | --- | | `feature_key` | The feature the customer was denied. | | `reason_code` | Machine-readable cause (not_in_plan, limit_reached, unknown_feature, …). | | `granted_by_plans` | Published plans that would grant (or raise the limit for) the feature. | | `environment` | The environment the check ran in (production, test, …). | | `customer_id` | The customer identifier — full, hashed, or absent per your identifier mode. | | `collapsed_count` | How many identical denials this delivery represents (collapse window). | `granted_by_plans` is the actionable part: the published plans that would have granted (or raised the limit for) the denied feature — the same signal your app can use for upgrade prompts via the API's `grantedByPlans` field. ## Volume controls — caps and collapsing Two mechanisms keep a hot denial loop from becoming a PostHog bill surprise: - **Collapse window** — identical denials (same customer + feature + reason) inside a 300-second window merge into one delivery with a `collapsed_count` property, so a retry storm is one event, not a thousand. - **Monthly cap** — you set a hard events-per-month cap at connect time (default 50,000). At the cap, delivery stops *visibly*: further events are marked `skipped_capped` (never silently dropped), the destination flips to `capped`, and you get a notification. Delivery resumes automatically when the month rolls over. > [!TIP] Delivery status is always inspectable > > Every queued event has one of pending, delivered, failed, skipped_capped status. The configure dialog shows sent-this-month against the cap, plus pending and failed queue counts, with a manual *Drain now* action. Failed deliveries retry on the hourly drain. ## Build the funnel in PostHog The event is deliberately minimal so it composes with your existing PostHog data. The highest-signal starting point is denial → upgrade: ```bash # In PostHog: Insights -> Funnel # Step 1: mk_denial (customer hit a packaging wall) # Step 2: subscription upgraded (from your billing events) # # Break down step 1 by "feature_key" to rank which walls convert — # and by "reason_code" to separate plan gaps (not_in_plan) from # limit pressure (limit_reached). ``` ## Manual pattern — every decision via the SDK's `DecisionObserver` The packaged destination streams denials from the platform side. When you also want *allowed* decisions, cache/degradation visibility, or custom event names, attach an observer in your app (requires `@monetizekit/node` ≥ 0.2.0): ```typescript import { PostHog } from "posthog-node"; import { MonetizeKit, type DecisionObserver } from "@monetizekit/node"; const posthog = new PostHog(process.env.POSTHOG_PROJECT_KEY, { host: "https://us.i.posthog.com", }); const posthogObserver: DecisionObserver = { onDecision(event) { posthog.capture({ distinctId: event.customerId, event: event.allowed ? "mk_check_allowed" : "mk_check_denied", properties: { feature_key: event.featureKey, reason_code: event.reasonCode, cached: event.cached, degraded: event.degraded, latency_ms: event.latencyMs, }, }); }, }; export const mk = new MonetizeKit({ apiKey: process.env.MONETIZEKIT_API_KEY, observers: [posthogObserver], }); ``` > [!WARNING] Running both? Use distinct event names > > The packaged destination owns `mk_denial`. If you also stream denials from an observer, name them differently (as above) — otherwise your funnels will double-count every denial. ## FAQ ### Will this create persons in my PostHog project? Not with the default `group` mapping — every event carries `$process_person_profile: false`, so accounts appear only as group analytics. Person profiles are created only if you explicitly choose `person` mapping at connect time. ### Can a PostHog outage slow down entitlement checks? No. The decision path only writes a durable queue row (fire-and-forget) — delivery to PostHog happens in a separate drainer. If PostHog is down, rows sit as `failed` and retry on the next hourly drain; decisions are unaffected in latency and outcome. ### What about customer PII? Events never include names or emails — only the customer id, and only in the form you chose: full, SHA-256 hashed, or omitted entirely. Switching the identifier mode later applies to new events (already-delivered events are in your PostHog project, under your retention controls). ### Which events are available? The packaged event types today are exactly mk_denial. The destination stores an explicit per-event-type toggle list, so additional packaging events (trials, upgrades, credit exhaustion) can ship individually — you opt into each, and nothing new is ever streamed without your action. ## Related guides ### Node SDK Integration The DecisionObserver extension point the manual pattern builds on. [Open guide](/docs/guides/sdk-node) ### Entitlement Evaluation Patterns The reason codes and grantedByPlans field the events carry. [Open guide](/docs/guides/entitlement-patterns) ### Clerk Identity Integration Keep customer identities synced so distinct ids stay meaningful. [Open guide](/docs/guides/clerk-identity) --- ## OpenTelemetry Visibility Source: https://learning.monetizekit.app/docs/guides/opentelemetry SHA-256: `3bea1287e8d0a46b89c60215fa53f2175e6b60c843ee4cfa443aa4f2684357e8` # OpenTelemetry Visibility Export decision spans and bounded metrics with deep links to exact evaluation records. Entitlement checks are control-flow: they decide whether requests proceed, degrade, or get billed. When they misbehave — slow, degraded, or suddenly denying — you want to see it in the same dashboards and traces as the rest of your system, not in a separate silo. The packaged exporter registers instrumentation against your existing OpenTelemetry setup; it composes with any OTLP-speaking vendor and no-ops silently when no OTel SDK is registered. > [!NOTE] Requires @monetizekit/node >= 0.2.0 > > The exporter ships as the `@monetizekit/node/otel` subpath export, built on the `DecisionObserver` extension point — see the [Node SDK guide](/docs/guides/sdk-node). `@opentelemetry/api` is an optional peer dependency, loaded only by this subpath. MonetizeKit does not push OTLP telemetry from the platform side; the signals below are generated in your process, where the decisions are consumed. ## Enable in one line `instrumentMonetizeKit()` returns a `DecisionObserver` that emits spans and metrics through your process's registered tracer and meter providers: ```typescript import { MonetizeKit } from "@monetizekit/node"; import { instrumentMonetizeKit } from "@monetizekit/node/otel"; const apiKey = process.env.MONETIZEKIT_API_KEY; if (!apiKey) throw new Error("MONETIZEKIT_API_KEY is required"); export const mk = new MonetizeKit({ apiKey, observers: [instrumentMonetizeKit()], }); ``` Sampling is parent-based and never overridden: if the caller's trace is unsampled, the decision span is too. Observer failures are swallowed twice over (by the SDK and by the exporter itself) — a broken telemetry pipeline can never affect an entitlement decision. ## What gets emitted One span per decision — `monetizekit.entitlement_check` for single checks, `monetizekit.batch_check` for batch results — nested inside whatever span is active when the check runs. Names and attributes are stable public API: renames are treated as breaking changes and ship with migration notes. | Span attribute | Meaning | | --- | --- | | `monetizekit.customer_id` | MonetizeKit customer id the decision was made for. | | `monetizekit.feature_key` | Feature key that was checked. | | `monetizekit.decision` | “allowed” or “denied” — the product decision. | | `monetizekit.reason_code` | Stable machine-readable cause (granted, limit_reached, not_in_plan, …). | | `monetizekit.cache_hit` | True when served from the SDK's local cache. Cached decisions are real spans too — flagged, not hidden. | | `monetizekit.degraded` | True when the API was unreachable and the SDK's degradation policy answered. | | `monetizekit.evaluation_id` | Id of the evaluation-log record behind the decision (when the API supplied one). | | `monetizekit.inspector_url` | Ready-made dashboard deep link to that exact evaluation record. | | `monetizekit.error` | The transport error message, on API failures only. | > [!WARNING] A denial is not an error > > Denied checks are span status `OK` with `monetizekit.decision=denied` — a customer hitting a plan limit is the product working, and it will never pollute your error tracker. Only transport failures (API unreachable, timeout) set status `ERROR`; degraded decisions additionally carry `monetizekit.degraded=true` so you can alert on degradation separately from denials. ## Metrics: bounded by design Three instruments cover the operational questions. Metric attributes carry decision, cache, degradation, and feature-key dimensions — and deliberately never customer or evaluation ids, so time-series cardinality (and your monitoring bill) cannot grow with your account count: | Instrument | Kind | Meaning | | --- | --- | --- | | `monetizekit.check.duration` | Histogram (ms) | End-to-end check duration — cache hits and API round trips, distinguishable by attribute. | | `monetizekit.checks` | Counter | Decision volume, dimensioned by decision, cache_hit, degraded, and feature_key. | | `monetizekit.degraded_checks` | Counter | Decisions served by the fail-open/fail-closed fallback. Alert when this is nonzero. | Customer-level detail belongs on spans and in the [analytics stream](/docs/guides/posthog-analytics), not in metrics. Traces and metrics are independently enableable via `instrumentMonetizeKit({ traces, metrics })`. ## From a span to the exact evaluation Every check response carries the id of its evaluation-log record as `evaluationId`, and the exporter renders it as a ready-made deep link: `monetizekit.inspector_url` points at `/observability/inspector/{evaluationId}` in the dashboard, which resolves that one record directly — plan version, resolution reason, usage context, evaluation timing. No searching. A trace showing a denial becomes the evaluation record explaining it, one click apart. | Tool | Rendering the link | | --- | --- | | Datadog | Facet the monetizekit.inspector_url span attribute; URL-valued facets render as clickable links in the trace side panel. | | Grafana (Tempo) | Add a data link on the span attribute using ${__data.fields["monetizekit.inspector_url"]} in the trace panel's Data links settings. | | Honeycomb | URL-shaped column values are clickable in trace and query results out of the box — no configuration needed. | | Sentry | Span attributes render in the trace detail view; URL values are shown as links in the span attributes table. | > [!NOTE] Evaluation records expire after 90 days > > Evaluation logs are retained for 90 days, globally. An inspector URL stored in a trace remains a valid correlation key in your own telemetry forever, but it stops resolving to a record after that window — investigate recent evaluations, don't archive by inspector URL. The link itself grants nothing: opening it requires signing in to a workspace that owns the evaluation. ## Alerts worth paging on Express these in your metrics backend of choice — the instrument and attribute names are the ones emitted above: | Alert | Expression | What it means | | --- | --- | --- | | Degraded decisions | `rate of monetizekit.degraded_checks > 0` | The SDK cannot reach the API and is serving fallback decisions — your gates are running on guesses. | | Fallback share | `decisions with monetizekit.reason_code in (sdk_fail_open, sdk_fail_closed) as a % of all decisions` | How much of your traffic was decided by the fail-open/fail-closed policy, not the API. | | Gate latency | `p95 of monetizekit.check.duration where monetizekit.cache_hit = false, per feature_key` | Uncached checks sit on your hot path — a p95 regression here is user-visible request latency. | | Denial spike | `sudden change in monetizekit.checks where monetizekit.decision = denied, per feature_key` | A plan publish or catalog change may have unintentionally revoked access — correlate with your deploy/config timeline. | ## Manual pattern: span events instead of spans If you'd rather attach decisions to your existing request spans than create a child span per check, implement `DecisionObserver` directly — the packaged exporter and this pattern use the same extension point and the same attribute names: ```typescript import { trace } from "@opentelemetry/api"; import { MonetizeKit, type DecisionObserver } from "@monetizekit/node"; const spanEventObserver: DecisionObserver = { onDecision(event) { trace.getActiveSpan()?.addEvent("monetizekit.decision", { "monetizekit.feature_key": event.featureKey ?? "", "monetizekit.decision": event.allowed ? "allowed" : "denied", "monetizekit.reason_code": event.reasonCode ?? "", "monetizekit.cache_hit": event.cached, "monetizekit.degraded": event.degraded, "monetizekit.latency_ms": event.latencyMs, }); }, }; export const mk = new MonetizeKit({ apiKey: process.env.MONETIZEKIT_API_KEY, observers: [spanEventObserver], }); ``` ## FAQ ### Do I need a specific OTel vendor or collector? No. The exporter depends only on `@opentelemetry/api`, which delegates to whatever SDK your process registered — any OTLP-speaking backend works. Without a registered SDK the calls are no-ops with no warnings, so the observer is safe to ship before your telemetry stack is wired up. ### Will this flood my tracing bill with cache-hit spans? Cache-served decisions are emitted as spans flagged `monetizekit.cache_hit=true`, because a decision your code acted on that is invisible in the trace is a debugging trap. Sampling is parent-based: decision spans are only recorded inside traces you already chose to sample. If you still want fewer spans, use the manual span-event pattern, or disable traces and keep metrics. ### Can I use both this and the PostHog destination? Yes — they answer different questions from different vantage points. OTel telemetry is generated in your process and tells you whether gating is *healthy* (latency, degradation, error rates); the PostHog destination streams denials from the platform side and tells you whether packaging is *working* (who hits limits, what converts). Neither depends on the other. ### What do degraded spans look like during an outage? Span status `ERROR` (the API call failed), with `monetizekit.degraded=true`, `monetizekit.error` carrying the transport message, and `monetizekit.reason_code` set to `sdk_fail_open` or `sdk_fail_closed` (or a stale-cache reason when the SDK could serve real, older data). One alert on `monetizekit.degraded_checks` distinguishes “the API is down” from “customers are hitting limits” — which is the point. ## Related guides ### Node SDK Integration The DecisionObserver extension point this guide builds on. [Open guide](/docs/guides/sdk-node) ### Audit and Trace Request-id propagation and the audit log, end to end. [Open guide](/docs/guides/audit-trace) ### PostHog Packaging Analytics The product-analytics twin of this guide's operational signals. [Open guide](/docs/guides/posthog-analytics) --- ## Quickstarts Source: https://learning.monetizekit.app/docs/quickstarts SHA-256: `cc5f64e28c20ba4cb4397313c653047be8b3af12ff418f5094b07dcd0409840d` # Quickstarts Choose one of five supported frameworks and run its complete first-success integration. Choose a framework and run the full happy path in minutes. ### Next.js SDK-first Language: TypeScript. Includes deploy + smoke test instructions. [Open quickstart](/docs/quickstarts/nextjs) ### Express Raw HTTP Language: JavaScript. Includes deploy + smoke test instructions. [Open quickstart](/docs/quickstarts/express) ### FastAPI Raw HTTP Language: Python. Includes deploy + smoke test instructions. [Open quickstart](/docs/quickstarts/fastapi) ### Go Raw HTTP Language: Go. Includes deploy + smoke test instructions. [Open quickstart](/docs/quickstarts/go) ### Spring Raw HTTP Language: Java. Includes deploy + smoke test instructions. [Open quickstart](/docs/quickstarts/spring) --- ## Next.js Quickstart Source: https://learning.monetizekit.app/docs/quickstarts/nextjs SHA-256: `e3bab1ec647e29df7550d42fbf130b04679d51238620a0b0aa7eab840b8b7fbf` # Next.js Quickstart Complete the SDK-first MonetizeKit activation journey in a Next.js application. Next.js uses the SDK-first path in TypeScript. Complete every step with an isolated non-production workspace before deploying. ## Prerequisites - Node 22+ - pnpm - A scoped non-production API key ## Environment setup ```bash MONETIZEKIT_BASE_URL=https://app.monetizekit.app/api/v1 MONETIZEKIT_API_KEY=${MONETIZEKIT_API_KEY} MONETIZEKIT_PLAN_ID=${MONETIZEKIT_PLAN_ID} MONETIZEKIT_FEATURE_KEY=${MONETIZEKIT_FEATURE_KEY} MONETIZEKIT_DENIED_FEATURE_KEY=${MONETIZEKIT_DENIED_FEATURE_KEY} MONETIZEKIT_METER_ID=${MONETIZEKIT_METER_ID} MONETIZEKIT_RUN_ID=replace-with-a-unique-run-id ``` ## Install commands ```bash pnpm add @monetizekit/node ``` ## Happy path ### 1. Create a customer Create a unique test customer. Raw HTTP variants send a deterministic idempotency key; the current Node SDK does not expose one for customer creation. ```typescript import { MonetizeKit, type Customer, type Plan, type Subscription, } from "@monetizekit/node"; async function createCustomer( client: MonetizeKit, runId: string, ): Promise { return client.customers.create({ name: `Docs quickstart ${runId}`, email: `docs-quickstart+${runId}@example.com`, }); } ``` Expected HTTP status: 201. ### 2. Select the isolated published plan List published plans and select the exact MONETIZEKIT_PLAN_ID provisioned for this run. ```typescript async function selectPlan(client: MonetizeKit, planId: string): Promise { const plans = await client.plans.list(); const plan = plans.data.find((candidate) => candidate.id === planId); if (!plan) { throw new Error(`Isolated plan ${planId} is not published in this workspace`); } return plan; } ``` Expected HTTP status: 200. ### 3. Attach the plan Create the customer's subscription. Raw HTTP variants reuse a deterministic idempotency key. ```typescript async function attachPlan( client: MonetizeKit, customerId: string, planId: string, ): Promise { return client.subscriptions.create({ customerId, planId, status: "active", }); } ``` Expected HTTP status: 201. ### 4. Check and enforce an entitlement Request the feature decision and stop protected work unless `allowed` is true. ```typescript async function requireEntitlement( client: MonetizeKit, customerId: string, featureKey: string, ): Promise { const decision = (await client.entitlements.check( customerId, featureKey, )) as unknown as EntitlementDecision; if (!decision.allowed) { throw new Error( `Entitlement denied (${decision.reasonCode}): ${decision.reason}`, ); } return decision; } ``` Expected HTTP status: 200. ### 5. Submit usage Record one metered event with a deterministic idempotency key that remains stable across retries. ```typescript async function submitUsage( client: MonetizeKit, customerId: string, meterId: string, idempotencyKey: string, ): Promise { return client.usage.submit({ customerId, meterId, value: 1, idempotencyKey, }); } ``` Expected HTTP status: 201. ### 6. Verify the observed usage Read the meter after submission and include the observed result in the smoke output. ```typescript async function validateUsage( client: MonetizeKit, customerId: string, meterId: string, ): Promise { return client.usage.get(customerId, meterId); } ``` Expected HTTP status: 200. ## Troubleshooting ### 401 missing_api_key / invalid_api_key Confirm the API key is present, active, and uses the non-production prefix for the environment you intend to test. [Read the full guide](/docs/troubleshooting/auth-issues) ### 403 missing scope Issue a key with customers:create, plans:read, subscriptions:write, entitlements:read, usage:write, usage:read, and cleanup permissions. [Read the full guide](/docs/troubleshooting/auth-issues) ### Entitlement denied Confirm MONETIZEKIT_PLAN_ID is the isolated plan that grants MONETIZEKIT_FEATURE_KEY and does not grant MONETIZEKIT_DENIED_FEATURE_KEY. [Read the full guide](/docs/guides/entitlement-patterns) ### A retry records duplicate usage Keep MONETIZEKIT_RUN_ID stable for retries of the same logical smoke run so the generated Idempotency-Key is reused. [Read the full guide](/docs/troubleshooting/metering-issues) ## Deploy + smoke test Platform: Vercel. 1. Set the seven quickstart environment variables in the Vercel project. 2. Deploy the server-side integration, then run the smoke entry point from a trusted runner. ```bash pnpm exec tsx examples/docs-quickstarts/nextjs/quickstart.ts --smoke ``` Expected: One JSON object with outcome "passed", allowed and denied entitlement decisions, and observed usage data, followed by successful subscription/customer cleanup. ## CLI links Use the CLI to authenticate and inspect the same workspace after the smoke test. ```bash monetizekit auth service-token create docs-quickstart --scopes customers:view --ttl 30d ``` ```bash monetizekit customers list ``` --- ## Express Quickstart Source: https://learning.monetizekit.app/docs/quickstarts/express SHA-256: `6b570e0038b73a50ddda3b9daad71ff5dba493e1416832fdaeaa487e828bfd30` # Express Quickstart Complete the raw-HTTP MonetizeKit activation journey in an Express service. Express uses the Raw HTTP path in JavaScript. Complete every step with an isolated non-production workspace before deploying. ## Prerequisites - Node 22+ - pnpm - A scoped non-production API key ## Environment setup ```bash MONETIZEKIT_BASE_URL=https://app.monetizekit.app/api/v1 MONETIZEKIT_API_KEY=${MONETIZEKIT_API_KEY} MONETIZEKIT_PLAN_ID=${MONETIZEKIT_PLAN_ID} MONETIZEKIT_FEATURE_KEY=${MONETIZEKIT_FEATURE_KEY} MONETIZEKIT_DENIED_FEATURE_KEY=${MONETIZEKIT_DENIED_FEATURE_KEY} MONETIZEKIT_METER_ID=${MONETIZEKIT_METER_ID} MONETIZEKIT_RUN_ID=replace-with-a-unique-run-id ``` ## Install commands ```bash pnpm add express ``` ## Happy path ### 1. Create a customer Create a unique test customer. Raw HTTP variants send a deterministic idempotency key; the current Node SDK does not expose one for customer creation. ```javascript async function createCustomer(config, idempotencyKey) { return requestJson( config, "/customers", { method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": idempotencyKey, }, body: JSON.stringify({ name: `Docs quickstart ${config.runId}`, email: `docs-quickstart+${config.runId}@example.com`, }), }, 201, ); } ``` Expected HTTP status: 201. ### 2. Select the isolated published plan List published plans and select the exact MONETIZEKIT_PLAN_ID provisioned for this run. ```javascript async function selectPlan(config) { const plans = await requestJson(config, "/plans", { method: "GET" }, 200); const plan = plans.data?.find((candidate) => candidate.id === config.planId); if (!plan) { throw new Error(`Isolated plan ${config.planId} is not published in this workspace`); } return plan; } ``` Expected HTTP status: 200. ### 3. Attach the plan Create the customer's subscription. Raw HTTP variants reuse a deterministic idempotency key. ```javascript async function attachPlan(config, customerId, planId, idempotencyKey) { return requestJson( config, "/subscriptions", { method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": idempotencyKey, }, body: JSON.stringify({ customerId, planId, status: "active" }), }, 201, ); } ``` Expected HTTP status: 201. ### 4. Check and enforce an entitlement Request the feature decision and stop protected work unless `allowed` is true. ```javascript async function requireEntitlement(config, customerId) { const decision = await requestJson( config, `/entitlements/${encodeURIComponent(customerId)}/${encodeURIComponent(config.featureKey)}`, { method: "GET" }, 200, ); if (!decision.allowed) { throw new Error( `Entitlement denied (${decision.reasonCode}): ${decision.reason}`, ); } return decision; } ``` Expected HTTP status: 200. ### 5. Submit usage Record one metered event with a deterministic idempotency key that remains stable across retries. ```javascript async function submitUsage(config, customerId, idempotencyKey) { return requestJson( config, "/usage/events", { method: "POST", headers: { "Content-Type": "application/json", "Idempotency-Key": idempotencyKey, }, body: JSON.stringify({ customerId, meterId: config.meterId, value: 1, }), }, 201, ); } ``` Expected HTTP status: 201. ### 6. Verify the observed usage Read the meter after submission and include the observed result in the smoke output. ```javascript async function validateUsage(config, customerId) { return requestJson( config, `/usage/${encodeURIComponent(customerId)}/${encodeURIComponent(config.meterId)}`, { method: "GET" }, 200, ); } ``` Expected HTTP status: 200. ## Troubleshooting ### 401 missing_api_key / invalid_api_key Confirm the API key is present, active, and uses the non-production prefix for the environment you intend to test. [Read the full guide](/docs/troubleshooting/auth-issues) ### 403 missing scope Issue a key with customers:create, plans:read, subscriptions:write, entitlements:read, usage:write, usage:read, and cleanup permissions. [Read the full guide](/docs/troubleshooting/auth-issues) ### Entitlement denied Confirm MONETIZEKIT_PLAN_ID is the isolated plan that grants MONETIZEKIT_FEATURE_KEY and does not grant MONETIZEKIT_DENIED_FEATURE_KEY. [Read the full guide](/docs/guides/entitlement-patterns) ### A retry records duplicate usage Keep MONETIZEKIT_RUN_ID stable for retries of the same logical smoke run so the generated Idempotency-Key is reused. [Read the full guide](/docs/troubleshooting/metering-issues) ## Deploy + smoke test Platform: Docker Compose. 1. Install dependencies and inject the seven quickstart environment variables. 2. Build and run the service image before invoking its smoke entry point. ```bash node examples/docs-quickstarts/express/quickstart.mjs --smoke ``` Expected: One JSON object with outcome "passed", allowed and denied entitlement decisions, and observed usage data, followed by successful subscription/customer cleanup. ## CLI links Use the CLI to authenticate and inspect the same workspace after the smoke test. ```bash monetizekit customers list ``` ```bash monetizekit workspace list ``` --- ## FastAPI Quickstart Source: https://learning.monetizekit.app/docs/quickstarts/fastapi SHA-256: `1b49012354541c8874c9b6158d57563d35c97bae2d0b7eee9e97ca721b70d82e` # FastAPI Quickstart Complete the raw-HTTP MonetizeKit activation journey in a FastAPI service. FastAPI uses the Raw HTTP path in Python. Complete every step with an isolated non-production workspace before deploying. ## Prerequisites - Python 3.12+ - pip - A scoped non-production API key ## Environment setup ```bash MONETIZEKIT_BASE_URL=https://app.monetizekit.app/api/v1 MONETIZEKIT_API_KEY=${MONETIZEKIT_API_KEY} MONETIZEKIT_PLAN_ID=${MONETIZEKIT_PLAN_ID} MONETIZEKIT_FEATURE_KEY=${MONETIZEKIT_FEATURE_KEY} MONETIZEKIT_DENIED_FEATURE_KEY=${MONETIZEKIT_DENIED_FEATURE_KEY} MONETIZEKIT_METER_ID=${MONETIZEKIT_METER_ID} MONETIZEKIT_RUN_ID=replace-with-a-unique-run-id ``` ## Install commands ```bash pip install -r examples/docs-quickstarts/fastapi/requirements.txt ``` ## Happy path ### 1. Create a customer Create a unique test customer. Raw HTTP variants send a deterministic idempotency key; the current Node SDK does not expose one for customer creation. ```python def create_customer(config: dict[str, str], idempotency_key: str) -> dict[str, Any]: return request_json( config, "POST", "/customers", 201, headers={"Idempotency-Key": idempotency_key}, body={ "name": f"Docs quickstart {config['run_id']}", "email": f"docs-quickstart+{config['run_id']}@example.com", }, ) ``` Expected HTTP status: 201. ### 2. Select the isolated published plan List published plans and select the exact MONETIZEKIT_PLAN_ID provisioned for this run. ```python def select_plan(config: dict[str, str]) -> dict[str, Any]: plans = request_json(config, "GET", "/plans", 200) plan = next( (candidate for candidate in plans.get("data", []) if candidate["id"] == config["plan_id"]), None, ) if plan is None: raise RuntimeError( f"Isolated plan {config['plan_id']} is not published in this workspace" ) return plan ``` Expected HTTP status: 200. ### 3. Attach the plan Create the customer's subscription. Raw HTTP variants reuse a deterministic idempotency key. ```python def attach_plan( config: dict[str, str], customer_id: str, plan_id: str, idempotency_key: str, ) -> dict[str, Any]: return request_json( config, "POST", "/subscriptions", 201, headers={"Idempotency-Key": idempotency_key}, body={"customerId": customer_id, "planId": plan_id, "status": "active"}, ) ``` Expected HTTP status: 201. ### 4. Check and enforce an entitlement Request the feature decision and stop protected work unless `allowed` is true. ```python def require_entitlement( config: dict[str, str], customer_id: str ) -> dict[str, Any]: decision = request_json( config, "GET", f"/entitlements/{quote(customer_id, safe='')}/{quote(config['feature_key'], safe='')}", 200, ) if not decision["allowed"]: raise RuntimeError( f"Entitlement denied ({decision['reasonCode']}): {decision['reason']}" ) return decision ``` Expected HTTP status: 200. ### 5. Submit usage Record one metered event with a deterministic idempotency key that remains stable across retries. ```python def submit_usage( config: dict[str, str], customer_id: str, idempotency_key: str ) -> dict[str, Any]: return request_json( config, "POST", "/usage/events", 201, headers={"Idempotency-Key": idempotency_key}, body={"customerId": customer_id, "meterId": config["meter_id"], "value": 1}, ) ``` Expected HTTP status: 201. ### 6. Verify the observed usage Read the meter after submission and include the observed result in the smoke output. ```python def validate_usage( config: dict[str, str], customer_id: str ) -> dict[str, Any]: return request_json( config, "GET", f"/usage/{quote(customer_id, safe='')}/{quote(config['meter_id'], safe='')}", 200, ) ``` Expected HTTP status: 200. ## Troubleshooting ### 401 missing_api_key / invalid_api_key Confirm the API key is present, active, and uses the non-production prefix for the environment you intend to test. [Read the full guide](/docs/troubleshooting/auth-issues) ### 403 missing scope Issue a key with customers:create, plans:read, subscriptions:write, entitlements:read, usage:write, usage:read, and cleanup permissions. [Read the full guide](/docs/troubleshooting/auth-issues) ### Entitlement denied Confirm MONETIZEKIT_PLAN_ID is the isolated plan that grants MONETIZEKIT_FEATURE_KEY and does not grant MONETIZEKIT_DENIED_FEATURE_KEY. [Read the full guide](/docs/guides/entitlement-patterns) ### A retry records duplicate usage Keep MONETIZEKIT_RUN_ID stable for retries of the same logical smoke run so the generated Idempotency-Key is reused. [Read the full guide](/docs/troubleshooting/metering-issues) ## Deploy + smoke test Platform: Docker Compose. 1. Install requirements and inject the seven quickstart environment variables. 2. Build and run the API image before invoking its smoke entry point. ```bash python3 examples/docs-quickstarts/fastapi/quickstart.py --smoke ``` Expected: One JSON object with outcome "passed", allowed and denied entitlement decisions, and observed usage data, followed by successful subscription/customer cleanup. ## CLI links Use the CLI to authenticate and inspect the same workspace after the smoke test. ```bash monetizekit auth login ``` ```bash monetizekit customers list ``` --- ## Go Quickstart Source: https://learning.monetizekit.app/docs/quickstarts/go SHA-256: `02c8a1733318b456bcbb795b8cedda8f9c8ed507ca689d038b4d8ea60b236478` # Go Quickstart Complete the raw-HTTP MonetizeKit activation journey in a Go service. Go uses the Raw HTTP path in Go. Complete every step with an isolated non-production workspace before deploying. ## Prerequisites - Go 1.22+ - A scoped non-production API key ## Environment setup ```bash MONETIZEKIT_BASE_URL=https://app.monetizekit.app/api/v1 MONETIZEKIT_API_KEY=${MONETIZEKIT_API_KEY} MONETIZEKIT_PLAN_ID=${MONETIZEKIT_PLAN_ID} MONETIZEKIT_FEATURE_KEY=${MONETIZEKIT_FEATURE_KEY} MONETIZEKIT_DENIED_FEATURE_KEY=${MONETIZEKIT_DENIED_FEATURE_KEY} MONETIZEKIT_METER_ID=${MONETIZEKIT_METER_ID} MONETIZEKIT_RUN_ID=replace-with-a-unique-run-id ``` ## Install commands ```bash cd examples/docs-quickstarts/go && go mod download ``` ## Happy path ### 1. Create a customer Create a unique test customer. Raw HTTP variants send a deterministic idempotency key; the current Node SDK does not expose one for customer creation. ```go func createCustomer(cfg config, idempotencyKey string) (customer, error) { var result customer err := requestJSON( cfg, http.MethodPost, "/customers", map[string]any{ "name": "Docs quickstart " + cfg.RunID, "email": "docs-quickstart+" + cfg.RunID + "@example.com", }, idempotencyKey, http.StatusCreated, &result, ) return result, err } ``` Expected HTTP status: 201. ### 2. Select the isolated published plan List published plans and select the exact MONETIZEKIT_PLAN_ID provisioned for this run. ```go func selectPlan(cfg config) (plan, error) { var plans planList if err := requestJSON(cfg, http.MethodGet, "/plans", nil, "", http.StatusOK, &plans); err != nil { return plan{}, err } for _, candidate := range plans.Data { if candidate.ID == cfg.PlanID { return candidate, nil } } return plan{}, fmt.Errorf("isolated plan %s is not published in this workspace", cfg.PlanID) } ``` Expected HTTP status: 200. ### 3. Attach the plan Create the customer's subscription. Raw HTTP variants reuse a deterministic idempotency key. ```go func attachPlan( cfg config, customerID string, planID string, idempotencyKey string, ) (subscription, error) { var result subscription err := requestJSON( cfg, http.MethodPost, "/subscriptions", map[string]any{"customerId": customerID, "planId": planID, "status": "active"}, idempotencyKey, http.StatusCreated, &result, ) return result, err } ``` Expected HTTP status: 201. ### 4. Check and enforce an entitlement Request the feature decision and stop protected work unless `allowed` is true. ```go func requireEntitlement(cfg config, customerID string) (entitlementDecision, error) { var decision entitlementDecision path := fmt.Sprintf( "/entitlements/%s/%s", url.PathEscape(customerID), url.PathEscape(cfg.FeatureKey), ) if err := requestJSON(cfg, http.MethodGet, path, nil, "", http.StatusOK, &decision); err != nil { return entitlementDecision{}, err } if !decision.Allowed { return entitlementDecision{}, fmt.Errorf( "entitlement denied (%s): %s", decision.ReasonCode, decision.Reason, ) } return decision, nil } ``` Expected HTTP status: 200. ### 5. Submit usage Record one metered event with a deterministic idempotency key that remains stable across retries. ```go func submitUsage(cfg config, customerID string, idempotencyKey string) (map[string]any, error) { result := map[string]any{} err := requestJSON( cfg, http.MethodPost, "/usage/events", map[string]any{"customerId": customerID, "meterId": cfg.MeterID, "value": 1}, idempotencyKey, http.StatusCreated, &result, ) return result, err } ``` Expected HTTP status: 201. ### 6. Verify the observed usage Read the meter after submission and include the observed result in the smoke output. ```go func validateUsage(cfg config, customerID string) (map[string]any, error) { result := map[string]any{} path := fmt.Sprintf("/usage/%s/%s", url.PathEscape(customerID), url.PathEscape(cfg.MeterID)) err := requestJSON(cfg, http.MethodGet, path, nil, "", http.StatusOK, &result) return result, err } ``` Expected HTTP status: 200. ## Troubleshooting ### 401 missing_api_key / invalid_api_key Confirm the API key is present, active, and uses the non-production prefix for the environment you intend to test. [Read the full guide](/docs/troubleshooting/auth-issues) ### 403 missing scope Issue a key with customers:create, plans:read, subscriptions:write, entitlements:read, usage:write, usage:read, and cleanup permissions. [Read the full guide](/docs/troubleshooting/auth-issues) ### Entitlement denied Confirm MONETIZEKIT_PLAN_ID is the isolated plan that grants MONETIZEKIT_FEATURE_KEY and does not grant MONETIZEKIT_DENIED_FEATURE_KEY. [Read the full guide](/docs/guides/entitlement-patterns) ### A retry records duplicate usage Keep MONETIZEKIT_RUN_ID stable for retries of the same logical smoke run so the generated Idempotency-Key is reused. [Read the full guide](/docs/troubleshooting/metering-issues) ## Deploy + smoke test Platform: Docker Compose. 1. Build the Go binary and inject the seven quickstart environment variables. 2. Run the service image before invoking the binary's smoke entry point. ```bash (cd examples/docs-quickstarts/go && go run . --smoke) ``` Expected: One JSON object with outcome "passed", allowed and denied entitlement decisions, and observed usage data, followed by successful subscription/customer cleanup. ## CLI links Use the CLI to authenticate and inspect the same workspace after the smoke test. ```bash monetizekit customers list ``` ```bash monetizekit workspace list ``` --- ## Spring Quickstart Source: https://learning.monetizekit.app/docs/quickstarts/spring SHA-256: `ad1f76195304c03e7ddd2e3e69f6e799c9437a522e1f1f340c6286907faec1e2` # Spring Quickstart Complete the raw-HTTP MonetizeKit activation journey in a Spring service. Spring uses the Raw HTTP path in Java. Complete every step with an isolated non-production workspace before deploying. ## Prerequisites - Java 21+ - Maven - A scoped non-production API key ## Environment setup ```bash MONETIZEKIT_BASE_URL=https://app.monetizekit.app/api/v1 MONETIZEKIT_API_KEY=${MONETIZEKIT_API_KEY} MONETIZEKIT_PLAN_ID=${MONETIZEKIT_PLAN_ID} MONETIZEKIT_FEATURE_KEY=${MONETIZEKIT_FEATURE_KEY} MONETIZEKIT_DENIED_FEATURE_KEY=${MONETIZEKIT_DENIED_FEATURE_KEY} MONETIZEKIT_METER_ID=${MONETIZEKIT_METER_ID} MONETIZEKIT_RUN_ID=replace-with-a-unique-run-id ``` ## Install commands ```bash cd examples/docs-quickstarts/spring && mvn dependency:go-offline ``` ## Happy path ### 1. Create a customer Create a unique test customer. Raw HTTP variants send a deterministic idempotency key; the current Node SDK does not expose one for customer creation. ```java private static Customer createCustomer(Config config, String idempotencyKey) throws Exception { String payload = """ {"name":%s,"email":%s} """.formatted( jsonString("Docs quickstart " + config.runId()), jsonString("docs-quickstart+" + config.runId() + "@example.com") ).trim(); ApiResponse response = requestJson( config, "POST", "/customers", payload, idempotencyKey, 201 ); return new Customer(stringField(response.body(), "id")); } ``` Expected HTTP status: 201. ### 2. Select the isolated published plan List published plans and select the exact MONETIZEKIT_PLAN_ID provisioned for this run. ```java private static Plan selectPlan(Config config) throws Exception { ApiResponse response = requestJson(config, "GET", "/plans", null, null, 200); Matcher matcher = Pattern.compile( "\\\"id\\\"\\s*:\\s*\\\"((?:\\\\.|[^\\\"])*)\\\"", Pattern.DOTALL ).matcher(response.body()); while (matcher.find()) { String candidateId = matcher.group(1); if (candidateId.equals(config.planId())) { return new Plan(candidateId); } } throw new IllegalStateException( "Isolated plan " + config.planId() + " is not published in this workspace" ); } ``` Expected HTTP status: 200. ### 3. Attach the plan Create the customer's subscription. Raw HTTP variants reuse a deterministic idempotency key. ```java private static Subscription attachPlan( Config config, String customerId, String planId, String idempotencyKey ) throws Exception { String payload = """ {"customerId":%s,"planId":%s,"status":"active"} """.formatted(jsonString(customerId), jsonString(planId)).trim(); ApiResponse response = requestJson( config, "POST", "/subscriptions", payload, idempotencyKey, 201 ); return new Subscription(stringField(response.body(), "id")); } ``` Expected HTTP status: 201. ### 4. Check and enforce an entitlement Request the feature decision and stop protected work unless `allowed` is true. ```java private static EntitlementDecision requireEntitlement( Config config, String customerId ) throws Exception { String path = "/entitlements/" + pathSegment(customerId) + "/" + pathSegment(config.featureKey()); ApiResponse response = requestJson(config, "GET", path, null, null, 200); EntitlementDecision decision = new EntitlementDecision( booleanField(response.body(), "allowed"), stringField(response.body(), "featureKey"), stringField(response.body(), "reason"), stringField(response.body(), "reasonCode") ); if (!decision.allowed()) { throw new IllegalStateException( "Entitlement denied (" + decision.reasonCode() + "): " + decision.reason() ); } return decision; } ``` Expected HTTP status: 200. ### 5. Submit usage Record one metered event with a deterministic idempotency key that remains stable across retries. ```java private static String submitUsage( Config config, String customerId, String idempotencyKey ) throws Exception { String payload = """ {"customerId":%s,"meterId":%s,"value":1} """.formatted(jsonString(customerId), jsonString(config.meterId())).trim(); return requestJson( config, "POST", "/usage/events", payload, idempotencyKey, 201 ).body(); } ``` Expected HTTP status: 201. ### 6. Verify the observed usage Read the meter after submission and include the observed result in the smoke output. ```java private static String validateUsage(Config config, String customerId) throws Exception { String path = "/usage/" + pathSegment(customerId) + "/" + pathSegment(config.meterId()); return requestJson(config, "GET", path, null, null, 200).body(); } ``` Expected HTTP status: 200. ## Troubleshooting ### 401 missing_api_key / invalid_api_key Confirm the API key is present, active, and uses the non-production prefix for the environment you intend to test. [Read the full guide](/docs/troubleshooting/auth-issues) ### 403 missing scope Issue a key with customers:create, plans:read, subscriptions:write, entitlements:read, usage:write, usage:read, and cleanup permissions. [Read the full guide](/docs/troubleshooting/auth-issues) ### Entitlement denied Confirm MONETIZEKIT_PLAN_ID is the isolated plan that grants MONETIZEKIT_FEATURE_KEY and does not grant MONETIZEKIT_DENIED_FEATURE_KEY. [Read the full guide](/docs/guides/entitlement-patterns) ### A retry records duplicate usage Keep MONETIZEKIT_RUN_ID stable for retries of the same logical smoke run so the generated Idempotency-Key is reused. [Read the full guide](/docs/troubleshooting/metering-issues) ## Deploy + smoke test Platform: Docker Compose. 1. Build the Spring Boot jar and inject the seven quickstart environment variables. 2. Run the service image before invoking the jar's smoke entry point. ```bash (cd examples/docs-quickstarts/spring && mvn -q package && java -jar target/monetizekit-docs-quickstart-1.0.0.jar --smoke) ``` Expected: One JSON object with outcome "passed", allowed and denied entitlement decisions, and observed usage data, followed by successful subscription/customer cleanup. ## CLI links Use the CLI to authenticate and inspect the same workspace after the smoke test. ```bash monetizekit auth service-token create docs-quickstart --scopes customers:view --ttl 30d ``` ```bash monetizekit customers list ``` --- ## Tools and SDKs Source: https://learning.monetizekit.app/docs/tools SHA-256: `d8e3b90e5b7ac90ebd895360f1709b055a414d9e452d5bb2721867f410f0060a` # Tools and SDKs Choose the CLI, an official SDK, Postman, or an AI-assistant integration. The CLI, official SDKs, Postman collection, and AI-assistant integrations. ### CLI Reference Install and operate MonetizeKit from scripts and terminals. [Open guide](/docs/tools/cli) ### SDKs Install the Node, React, and Embed SDKs for application integration. [Open guide](/docs/tools/sdks) ### Postman Collections Download domain collections and environment templates for quick API validation. [Open guide](/docs/tools/postman) ### MCP & IDE Integrations Configure one-click MCP setup for Cursor and Claude Code, plus usage patterns and token scope guidance. [Open guide](/docs/tools/mcp-ide) --- ## CLI Reference Source: https://learning.monetizekit.app/docs/tools/cli SHA-256: `54521386df70f76a521ae44633ec7e2402e2bb07c322f97e039f8aeb4d1481b2` # CLI Reference Install and operate MonetizeKit from scripts and terminals. ```bash npm i -g @monetizekit/cli ``` ### Common commands ```bash monetizekit auth login ``` Authenticate the local CLI session ```bash monetizekit auth service-token create docs-ci --scopes customers:view --ttl 30d ``` Create scoped service tokens ```bash monetizekit workspace list ``` List accessible workspaces ```bash monetizekit workspace use ``` Set active workspace context ```bash monetizekit catalog import --dir ./catalog ``` Import catalog-as-code changes Full details: see the `monetizekit-cli` spec deliverables in this repository. For MCP-based IDE tooling instead of the CLI, see [MCP & IDE Integrations](/docs/tools/mcp-ide) . --- ## Postman Collections Source: https://learning.monetizekit.app/docs/tools/postman SHA-256: `51f42d6ca67459740d5d797e3b1c79116a1d2e0b342e96f0eab6341177b4a761` # Postman Collections Download domain collections and environment templates for quick API validation. Download domain collections and environment templates generated from the runtime OpenAPI contract. The HTML page adds download controls; this document remains the complete inventory and setup reference. ## Collections | Collection | Description | Requests | Version | Last updated | File | | --- | --- | --- | --- | --- | --- | | General API | General endpoints generated from runtime OpenAPI. | 1 | 1.0.0 | 2026-03-16 | monetizekit-general.postman_collection.json | | Customers API | Customers endpoints generated from runtime OpenAPI. | 11 | 1.0.0 | 2026-03-16 | monetizekit-customers.postman_collection.json | | Entitlements API | Entitlements endpoints generated from runtime OpenAPI. | 4 | 1.0.0 | 2026-03-16 | monetizekit-entitlements.postman_collection.json | | Usage API | Usage endpoints generated from runtime OpenAPI. | 4 | 1.0.0 | 2026-03-16 | monetizekit-usage.postman_collection.json | | Credits API | Credits endpoints generated from runtime OpenAPI. | 9 | 1.0.0 | 2026-03-16 | monetizekit-credits.postman_collection.json | | Catalog API | Catalog endpoints generated from runtime OpenAPI. | 4 | 1.0.0 | 2026-03-16 | monetizekit-catalog.postman_collection.json | | Complete API | All runtime API operations generated from OpenAPI. | 33 | 1.0.0 | 2026-03-16 | monetizekit-complete.postman_collection.json | ## Environment templates > [!NOTE] No embedded secrets > > Environment downloads contain placeholder values only. Replace each API-key placeholder from your secure secret store after import. | Environment | File | Variables | | --- | --- | --- | | MonetizeKit Dev | monetizekit-dev.postman_environment.json | baseUrl (default), workspaceId (default), apiKey (secret) | | MonetizeKit Staging | monetizekit-staging.postman_environment.json | baseUrl (default), workspaceId (default), apiKey (secret) | | MonetizeKit Production | monetizekit-production.postman_environment.json | baseUrl (default), workspaceId (default), apiKey (secret) | ## Setup guide 1. Import a collection JSON into Postman. 2. Import the matching environment template. 3. Replace `apiKey` with a scoped service token from Settings → API Keys. See [Authentication](/docs/getting-started/authentication) for scope guidance. 4. Run a GET request first, then POST flows with generated idempotency headers. Public workspace: [https://www.postman.com/monetizekit/workspace/monetizekit-public](https://www.postman.com/monetizekit/workspace/monetizekit-public) --- ## SDKs Source: https://learning.monetizekit.app/docs/tools/sdks SHA-256: `8088ff34e544cd771785725b48252b0258ceec88e9d706f845bd4ebddec1211b` # SDKs Install the Node, React, and Embed SDKs for application integration. ### @monetizekit/node ```bash npm install @monetizekit/node ``` ```bash pnpm add @monetizekit/node ``` ```bash yarn add @monetizekit/node ``` ```bash bun add @monetizekit/node ``` ### @monetizekit/react ```bash npm install @monetizekit/react ``` ```bash pnpm add @monetizekit/react ``` ```bash yarn add @monetizekit/react ``` ```bash bun add @monetizekit/react ``` ### Pricing presentation templates Use dashboard-authored templates to control plan visibility, order, labels, badges, feature groups, locale overrides, and page-specific skins while keeping pricing synced to the live catalog. ```typescript ``` ```typescript const { plans, template, groups } = usePricingTemplate("homepage") ``` ```bash curl -H 'Authorization: Bearer pk_live_xxx' 'https://app.monetizekit.app/api/v1/plans?template=homepage&locale=en-US' ``` ### @monetizekit/embed ```html ``` ```bash npm install @monetizekit/embed ``` ```bash pnpm add @monetizekit/embed ``` ```bash yarn add @monetizekit/embed ``` ```bash bun add @monetizekit/embed ``` ### @monetizekit/types ```bash npm install -D @monetizekit/types ``` ```bash pnpm add -D @monetizekit/types ``` ```bash yarn add -D @monetizekit/types ``` ```bash bun add -D @monetizekit/types ``` For complete API surfaces, refer to the SDK spec documentation. --- ## MCP & IDE Integrations Source: https://learning.monetizekit.app/docs/tools/mcp-ide SHA-256: `2f993397c6ad2c2021859d54c2fa99e0daf5146595c22368da55852cdb0d48ef` # MCP & IDE Integrations Configure one-click MCP setup for Cursor and Claude Code, plus usage patterns and token scope guidance. ### MCP Server Endpoint: `{MONETIZEKIT_MCP_SERVER_URL}` (JSON-RPC MCP endpoint; for the in-app adapter use `https://your-domain/api/mcp`). Recommended read-only MCP permissions: `catalog:view`, `customers:read`, `entitlements:read`, `usage:read`, `integrations:view`, `observability:view`, `audit:view` — see the [Authentication guide](/docs/getting-started/authentication) for how scoped keys and service tokens work more generally. Use elevated scopes only for managed write workflows and rotate keys regularly. ```bash monetizekit auth service-token create docs-mcp --scopes catalog:view,customers:read,entitlements:read,usage:read,integrations:view,observability:view,audit:view --ttl 30d ``` ```json { "mcpServers": { "monetizekit-mcp": { "url": "https://app.monetizekit.app/api/mcp", "headers": { "Authorization": "Bearer ${MONETIZEKIT_MCP_TOKEN}" }, "env": { "MONETIZEKIT_MCP_TOKEN": "${MONETIZEKIT_MCP_TOKEN}" } } } } ``` ### Cursor IDE Use `.cursor/mcp.json` template or run `monetizekit init --cursor`. Reference: `docs/cursor/installation.md` and `docs/cursor/security.md`. ### Claude Code + Skill Pack Import the `monetizekit-claude-skill-pack` bundle and configure MCP connector URL + scoped token. Reference files: `monetizekit-claude-skill-pack/manifest.json`, `monetizekit-claude-skill-pack/docs/installation.md`. ```bash claude mcp add monetizekit-mcp https://app.monetizekit.app/api/mcp --header "Authorization: Bearer ${MONETIZEKIT_MCP_TOKEN}" ``` ### Usage quick start After installation, ensure your token includes `observability:view`, then ask your assistant to call `docs.get_manifest` first and `docs.get_section` for grounded answers. ```bash Prompt: "Run tools/list, then docs.get_manifest, then docs.get_section { section: \"openapi\" }, and cite endpoint paths in your answer." ``` --- ## Troubleshooting Source: https://learning.monetizekit.app/docs/troubleshooting SHA-256: `b83b92ccfd9343dc9d506e1ae59bf265ea23d55355bc966c25fcae355fda8eb6` # Troubleshooting Choose a focused recovery guide for common integration and runtime failures. Diagnose common integration and runtime problems. ### Error Codes Reference for common API failures and remediation steps. [Open guide](/docs/troubleshooting/error-codes) ### Auth and Permission Issues Diagnose invalid keys, scope mismatches, and token lifecycle issues. [Open guide](/docs/troubleshooting/auth-issues) ### Webhook Delivery Issues Fix signature mismatches, timeout failures, and endpoint availability problems. [Open guide](/docs/troubleshooting/webhook-issues) ### Metering and Usage Anomalies Identify duplicate events, missing events, and threshold misconfiguration. [Open guide](/docs/troubleshooting/metering-issues) --- ## Error Codes Source: https://learning.monetizekit.app/docs/troubleshooting/error-codes SHA-256: `8e136b7c37f2c5859f1387bb8d2448a92e2ca2de97b8588128bae5c1644b5b92` # Error Codes Reference for common API failures and remediation steps. ### INVALID_API_KEY (401) API key is missing, revoked, or malformed. Common causes • Missing Authorization header • Revoked key • Wrong environment key Resolution Regenerate a scoped key and retry with correct environment. ### INSUFFICIENT_SCOPE (403) API key does not have required permission scope. Common causes • Key missing `entitlements:read` • Write attempted with read-only key Resolution Issue a key with minimum required scope for the endpoint. ### RESOURCE_NOT_FOUND (404) Requested entity does not exist in workspace. Common causes • Customer ID typo • Cross-workspace identifier Resolution Verify resource IDs and workspace context. ### FREE_TIER_CAP_EXCEEDED (402) Free-tier monthly API cap reached; upgrade required to continue. Common causes • Free workspace exceeded its API call allowance • Write request attempted after the cap Resolution Upgrade to a paid plan or wait for the next billing period. ### RATE_LIMIT_EXCEEDED (429) Request rate exceeded current allowance. A per-key burst limit applies only when your workspace's effective `api_rate_limit_per_minute` entitlement — its plan value, plus any approved override MonetizeKit has granted your workspace — is positive; absent or `0` means no burst limit, the limiter is skipped, and no `X-RateLimit-*` headers are sent. The one exception is a Free workspace over its monthly quota, whose reads are throttled to 20 requests/minute. Responses checked against a limit carry `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset`; responses with no limit in force omit them. Common causes • Burst traffic • Missing backoff logic Resolution Read X-RateLimit-Reset and retry after that reset time with jittered backoff. For key/scope issues (`INVALID_API_KEY`, `INSUFFICIENT_SCOPE`), see the [Authentication guide](/docs/getting-started/authentication) and the [Auth and Permission Issues guide](/docs/troubleshooting/auth-issues). --- ## Auth and Permission Issues Source: https://learning.monetizekit.app/docs/troubleshooting/auth-issues SHA-256: `65255b09c1136a7e7c6c65ca912d052b0f04f0215ee639fc6af76efb937786e2` # Auth and Permission Issues Diagnose invalid keys, scope mismatches, and token lifecycle issues. • Invalid key: confirm key prefix and environment match (test vs live). • Expired/revoked key: rotate from Settings → API Keys and update secret store. • Insufficient scopes: compare endpoint requirement with token scope list — see the [Authentication guide](/docs/getting-started/authentication) for key types and recommended scopes. --- ## Webhook Delivery Issues Source: https://learning.monetizekit.app/docs/troubleshooting/webhook-issues SHA-256: `2f6a568428063554f426eaaa1b73afe6ccfa97186b845cbea0647adad7e8fb29` # Webhook Delivery Issues Fix signature mismatches, timeout failures, and endpoint availability problems. • Signature mismatch: verify HMAC secret and raw body usage — see [Webhook Verification and Retries](/docs/guides/webhooks) for the exact signing scheme. • Timeout: reduce handler latency or queue work asynchronously. • Endpoint unreachable: validate DNS, TLS chain, and firewall allowlists. --- ## Metering and Usage Anomalies Source: https://learning.monetizekit.app/docs/troubleshooting/metering-issues SHA-256: `16205e8303c1b693ce6639106e2966387e4c39ae2ed22a689596a23a3bd5a028` # Metering and Usage Anomalies Identify duplicate events, missing events, and threshold misconfiguration. • Duplicate events: enforce deterministic idempotency keys — see the [Usage Metering Best Practices guide](/docs/guides/metering) for idempotency key strategy. • Missing events: confirm producer retries and endpoint status. • Threshold mismatch: validate meter key mapping and environment scope. --- ## API Version Notes Source: https://learning.monetizekit.app/docs/changelog SHA-256: `2c14585b13f248d7eccd9c95d6ebcf4d49b50251c4825cb3c454017aef3cad65` # API Version Notes Review the release timeline and notable changes to public API behavior. ## v2.3.0 · 2026-03-15 Interactive docs launch: OpenAPI explorer, GraphQL explorer, and tools pages. - `added` — Added interactive OpenAPI explorer with Try-It panel. - `added` — Added GraphQL schema browser and query runner. - `changed` — Consolidated MCP and IDE integration documentation under Tools. ## v2.2.0 · 2026-02-01 Entitlement tracing improvements. - `added` — Added request-id traceability to entitlement responses. - `deprecated` — Marked legacy integrations webhook listing endpoint for removal. - `fixed` — Improved pagination cursor stability for plan list endpoint. ## v2.1.0 · 2025-12-14 Catalog and usage API refinements. - `changed` — Updated usage payload validation with stronger typing. - `fixed` — Corrected rate limit headers on list endpoints. --- ## Deprecations Source: https://learning.monetizekit.app/docs/changelog/deprecations SHA-256: `e18654e7cd23e18dac8495c045ebc016237ef5e0a882c0c92d4e3eb26a78d005` # Deprecations Deprecated endpoints and fields with migration windows. ## Deprecation policy MonetizeKit provides a minimum of one minor release with warnings before removal; enterprise deployments may receive extended windows. See the [Migration Guide](/docs/guides/migration) for how to detect and roll out around a deprecation safely. ## Deprecated surface | Item | Type | Deprecated | Removal | Migration | Guide | | --- | --- | --- | --- | --- | --- | | `GET /integrations/legacy-webhooks` | endpoint | 2026-02-01 | v2.4 (2026-09-30) | Use /webhooks/endpoints for endpoint management and replay operations. | [Migration guide](/docs/changelog/deprecations) | | `Plan.legacyFlags` | field | 2026-02-01 | v2.4 (2026-09-30) | Replace legacyFlags with typed entitlements arrays. | [Migration guide](/docs/changelog/deprecations) | | `LegacyPlan` | type | 2026-01-10 | v2.4 (2026-09-30) | Move all references from LegacyPlan to Plan. | [Migration guide](/docs/changelog/deprecations) | --- ## Breaking Changes Source: https://learning.monetizekit.app/docs/changelog/breaking-changes SHA-256: `555e62b43ba17d1bb2d4700d7ceeea8ba765f094d1520e9b664cf606f60de710` # Breaking Changes Track incompatible API changes, exact removal dates, and required replacements. ## v2.0.0 Removed v1 plan payload aliases and enforced canonical key names. ### Required migration 1. Replace `plan_code` with `key` in create and update payloads. 2. Update validation layer to reject unknown alias fields. ## v1.9.0 Webhook signature algorithm changed from SHA1 to HMAC-SHA256. ### Required migration 1. Recompute signatures using HMAC-SHA256 with shared secret. 2. Reject webhook payloads missing timestamp and signature headers.