# Creem CLI Source: https://docs.creem.io/ai/for-agents/cli Manage your entire Creem business from the terminal. Perfect for AI agents and automation workflows. The Creem CLI lets you manage products, customers, subscriptions, and transactions directly from the terminal. It's designed for both human developers and AI agents building automation workflows. ## Setup Provide `CREEM_API_KEY` through your environment or secret store. The CLI infers test/live mode without persisting the key. Use Node.js 22 or newer for npm, or see the [installation guide](/code/cli#installation) for Homebrew and npx. ```sh theme={null} npm install -g @creem_io/cli creem products list --json creem subscriptions list --all --json creem credits entries acc_123 --all --output ndjson ``` ## Input contract Use `creem --help` to discover inputs. The [command reference](/code/cli#command-reference) lists available commands and flags. Every body operation accepts camelCase JSON inline, from `@file.json`, or from stdin with `--data -`. Do not combine body flags with `--data`. Non-body flags, path IDs, and `--yes` remain allowed. ```sh theme={null} creem checkouts create --data '{"productId":"prod_123","customer":{"email":"person@example.com"},"metadata":{"visits":42}}' --json creem credits credit acc_123 --amount '9007199254740993' --reference event-123 --idempotency-key event-123 --json creem transactions refund tran_123 --yes --json ``` Credit amounts stay strings. Writes are attempted once; the CLI never retries automatically. If a write fails ambiguously, inspect its outcome before manually retrying with the same supported idempotency key. Product creation supports the idempotency header; credit/debit idempotency keys are body fields. ## Output and errors Use `--json` for a single result or aggregated collection, and `--all --output ndjson` to stream list items. Standard output contains results; structured errors go to standard error. NDJSON may contain successful earlier pages before a later failure. Check the process exit code before accepting a completed export. | Exit | Meaning | | - | - | | 0 | Success | | 1 | Unexpected failure | | 2 | Invalid CLI usage or request input | | 3 | Auth/config failure | | 4 | API or response-validation failure | | 5 | Network/timeout failure | Without credentials, `creem products list --json` produces no stdout and exits 3 with this stderr: ```json theme={null} { "error": { "type": "auth", "message": "Not authenticated.", "status": null, "traceId": null, "details": null, "cause": null, "suggestion": "Set CREEM_API_KEY or run creem login.", "retryAfter": null } } ``` ## Local webhooks `creem listen --forward-to --json` streams the store's webhooks to a local server as NDJSON records (`listening`, `event`, `stopped`) and cleans up its temporary endpoint on exit. Use `--once` to drain pending events in a single run. See the [CLI reference](/code/cli#local-webhooks). ## Confirmation Use `--yes` for destructive commands in automation. Human prompts are disabled for JSON/NDJSON and non-TTY execution. The [reference](/code/cli#errors-and-safety) lists the policy. Existing aliases remain valid. For existing scripts, see the [upgrade notes](/code/cli#upgrading-existing-scripts). Subscription `--status` filters all pages and labels its client-side result. # Hosted MCP Server Source: https://docs.creem.io/ai/for-agents/hosted-mcp Connect Claude, Claude Code, ChatGPT, Codex, Cursor or any remote MCP client to your Creem store at mcp.creem.io. Sign in with your Creem account, no API key. Creem runs an [MCP](https://modelcontextprotocol.io) server at `https://mcp.creem.io/mcp`. Add it to Claude, Claude Code, ChatGPT, Codex, Cursor or another MCP client, sign in with your Creem account, and your agent can look up customers, subscriptions and payments, create products, checkout links and discount codes, and cancel subscriptions. There is nothing to install and no API key to paste. > [!TIP] > > Want to use Creem in the Claude or ChatGPT app without the technical detail? See [Use Creem in > Claude and ChatGPT](/ai/for-humans/ai-assistants). ## Requirements * A Creem account with at least one store ([sign up](https://creem.io/dashboard)) * An MCP client: [Claude](#claude), [Claude Code](#claude-code), [ChatGPT](#chatgpt), [Codex](#codex) 0.147 or newer, [Cursor](#cursor), or [another client](#other-clients) that supports remote MCP servers ## Quickstart ```bash theme={null} claude mcp add --transport http creem https://mcp.creem.io/mcp ``` Then run `/mcp` in Claude Code, select **creem** and choose **Authenticate**. Your browser opens the Creem sign-in. On the consent screen, pick **Test mode** to try things out first: **Live mode** is preselected. For other clients, see below. ## Claude In Claude, open **Customize → Connectors**, select **Add custom connector** and enter: * **Name:** `Creem` * **Remote MCP server URL:** `https://mcp.creem.io/mcp` Select **Add** (if Claude shows sign-in settings first, keep the ones it detected), then **Connect**, and sign in with your Creem account. Add the connector on claude.ai or in Claude Desktop; once connected, it also works in the Claude mobile apps. On Team and Enterprise plans, an Owner adds the connector for the organization in **Organization settings → Connectors** first, and each member then connects from **Customize → Connectors**. ## Claude Code ```bash theme={null} claude mcp add --transport http creem https://mcp.creem.io/mcp ``` `--transport http` is required: without it, Claude Code treats the URL as a local command. Add `--scope user` to use Creem in every project. ## ChatGPT Custom MCP servers work in ChatGPT on the web, and your plan or workspace has to allow them. See OpenAI's [Connecting custom MCP servers in ChatGPT](https://help.openai.com/en/articles/12584461-developer-mode-apps-and-full-mcp-connectors-in-chatgpt). **1. Add the server** Go to [ChatGPT Plugins](https://chatgpt.com/plugins), select the plus button, then **Add custom MCP server**. Name it `Creem` and enter `https://mcp.creem.io/mcp` under **Connection**. **2. Choose OAuth** Choose **OAuth** and leave the client ID and secret empty. Review the risk warning, tick **I understand and want to continue**, then select **Create as a plugin**. **3. Sign in** Install the plugin and sign in with your Creem account when ChatGPT asks. ## Codex ```bash theme={null} codex mcp add creem --url https://mcp.creem.io/mcp codex mcp login creem ``` `codex mcp login` opens your browser for the Creem sign-in. The Codex CLI, the IDE extension and the ChatGPT desktop app share one configuration, so adding the server once works in all three. ## Cursor Add the following to `.cursor/mcp.json` in your project, or to `~/.cursor/mcp.json` to make Creem available in every project: ```json theme={null} { "mcpServers": { "creem": { "url": "https://mcp.creem.io/mcp" } } } ``` Open **Customize** in Cursor's sidebar, connect `creem` and sign in with your Creem account. Cursor's cloud agents can't connect: sign-in only completes on your own machine. ## Other clients If your client accepts a remote MCP URL, add: ``` https://mcp.creem.io/mcp ``` If it only supports local commands, use the [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) bridge: ```json theme={null} { "mcpServers": { "creem": { "command": "npx", "args": ["-y", "mcp-remote@0.16.0", "https://mcp.creem.io/mcp"] } } } ``` The example pins `mcp-remote` to a version because the bridge holds your Creem sign-in tokens. Update the version on purpose, not on every start. Your browser opens the Creem sign-in the first time the client starts the server. A client not listed above can sign in only if it completes sign-in on your own machine, as `mcp-remote` does. If your client sends the sign-in back to its own website instead, connect it through `mcp-remote`. ## Sign-in and permissions When you connect, your browser opens Creem's sign-in and consent screen. You sign in, pick a store and a [mode](#test-and-live-mode), and choose what the agent can do. A connection works on one store; picking another store later replaces it. On a first connect every permission the client asks for is ticked. Untick what the agent doesn't need: | Permission | What it allows | | - | - | | **View your store** | Read products, checkouts, discount codes, customers, transactions, subscriptions, disputes, revenue and your business details | | **Manage products, checkout links and discounts** | Create, edit and archive products, create checkout links, and create and delete discount codes | | **Fill in and submit your business details** | Save your business details as a draft and submit them to Creem for review. Today's tools only save a draft | | **Manage subscriptions** | Change, upgrade, pause, resume or cancel your customers' subscriptions. Today's tools can only cancel | When the agent calls a tool the connection has no permission for, your client asks you to sign in again. Tick the permission on the consent screen; it keeps what you already allowed. A client that can't do this shows an authorization error instead. Connect again from your client and tick the permission. When you grant a permission that changes your store, the consent screen also shows **Confirmations**: **Ask before risky actions**, ticked by default. Leave it ticked unless you trust the agent to act without asking. See [Security](#security). You, and the store owner if that's someone else, get an email when an agent is connected or gets new permissions. ## Test and live mode Each connection works in one mode at a time. **Test mode** uses your store's [test mode](/getting-started/test-mode) data, and no real money moves. **Live mode** works on real payments, customers and subscriptions. You choose the mode on the consent screen. **Live mode** is preselected on every new connection; pick **Test mode** to try things out first. If live payments aren't enabled for your store yet, no real payments run until they are. Every tool result says which mode it ran in, and every confirmation starts with `[Test mode]` or `[LIVE mode]`. To change mode later, ask your agent (for example "switch Creem to live mode") or use **Settings → Connected apps** in the dashboard. Switching to live asks you to confirm. ## Available tools 25 tools. All of them work in both modes except `get_business_details_requirements` and `save_business_details`, which work in live mode only. | Group | Count | Tools | | - | - | - | | **Products** | 5 | `list_products`, `get_product`, `create_product`, `update_product`, `archive_product` | | **Checkouts** | 2 | `get_checkout`, `create_checkout_link` | | **Discounts** | 4 | `list_discounts`, `get_discount`, `create_discount`, `delete_discount` | | **Customers** | 2 | `search_customers`, `get_customer` | | **Subscriptions** | 3 | `list_subscriptions`, `get_subscription`, `cancel_subscription` | | **Transactions** | 1 | `list_transactions` | | **Disputes** | 2 | `list_disputes`, `get_dispute` | | **Stats** | 1 | `get_revenue_summary` | | **Onboarding** | 4 | `get_business_details_requirements`, `save_business_details`, `open_business_details`, `open_identity_verification` | | **Connection** | 1 | `switch_mode` | `get_business_details_requirements` shows what your store's business details still need, the first step to live payments. `save_business_details` saves what you tell the agent into the same draft the dashboard form shows; it submits nothing. Close the business details form in the dashboard while the agent saves: an open form overwrites the save the next time it autosaves. The two `open_` tools return a dashboard link, where you fill in or submit the form yourself. ## Security Some tools change your store and can't be undone. By default, Creem asks **you**, not the agent, to confirm them before anything happens. | Tool | Asks you to confirm | | - | - | | `cancel_subscription` | Yes, unless you turn confirmations off | | `create_discount` | Yes, unless you turn confirmations off | | `delete_discount` | Yes, unless you turn confirmations off | | `archive_product` | Yes, unless you turn confirmations off | | `update_product` | When it changes the price, currency, trial or success URL, unless you turn confirmations off | | `switch_mode` | Always when switching to live, even with confirmations off | Clients that can show a prompt display it with **Accept** and **Decline**. In other clients, the agent shows you the question in the chat and runs the tool only after you reply "yes". A confirmation covers exactly that action, works once and expires after 10 minutes. To let a connection act without asking, turn off **Ask before risky actions** for it in [Connected apps](#connected-apps). The setting applies to that connection only, in test and live mode. > [!WARNING] > > With confirmations off, the agent may also act on text your buyers wrote, such as a customer name, > without asking you. Someone could hide instructions in that text. Creem recommends keeping > confirmations on. Two more things to do: **Develop in test mode.** Connect in test mode while you try things out. Nothing you break is real. **Grant only the permissions you need.** An agent that only reports on your store needs **View your store** and nothing else. ## Connected apps **Settings → Connected apps** in the dashboard lists the agents connected to your store, who connected them, their mode and whether they ask before risky actions. There you can: * switch a connection between test and live mode * turn **Ask before risky actions** on or off with **Change**. The change takes effect within a minute * disconnect a connection You can manage the connections you made; the store owner can manage all of them. Connecting the same app again keeps its current confirmation setting, so change it here. When you disconnect an agent, its calls stop within a minute and it has to sign in again. Changes it already made, such as cancelled subscriptions or new products, stay. ## Limits | Limit | Per connection | Per store | | - | - | - | | Calls per minute | 120 | 300 | | Write calls per minute | 30 | 60 | Store limits count test-mode and live-mode calls separately. A call over a limit fails with `rate_limited` and changes nothing. Wait for the minute to pass and try again. ## Verifying it works Connect, pick **Test mode** on the consent screen, and ask your agent: ``` List my Creem products. ``` The result ends with `Ran in test mode: test data, no real money.` If you get an error instead, see below. ## Troubleshooting > [accordion] My client can't finish signing in > > Your client isn't listed on this page and sends the sign-in back to its own website instead of > your machine. Connect it with the `mcp-remote` bridge (see [Other clients](#other-clients)). > [accordion] Every call fails with “The Creem MCP isn't enabled for this store yet” > > The hosted server isn't enabled for the store this connection uses. Creem refuses every request, > including the first one when your client connects, so your client may only say it can't connect. > If another of your stores has access, disconnect and connect again, choosing that store. > Otherwise contact [support](mailto:support@creem.io). Once the store is enabled, the same > connection works without signing in again. > [accordion] A tool says it needs a permission this connection does not have yet > > The connection doesn't have the permission the tool needs. Connect again and tick it on the > consent screen. See [Sign-in and permissions](#sign-in-and-permissions). > [accordion] My client asks me to sign in again > > The connection ended. It was disconnected in Connected apps by you or the store owner, you > didn't use it for 7 days, you were removed from the store, the store was deleted, or your Creem > account was locked or signed out everywhere. Sign in again to create a new connection. > [accordion] A call fails with rate_limited > > See [Limits](#limits). Creem refuses calls over a limit before anything runs, including the > first request when your client connects, so your client may only say it can't connect. Wait for > the minute to pass and try again. > [accordion] A call fails with unavailable > > Creem couldn't complete the call. Try again in a moment. If it was a write, check whether it ran > first, for example with `list_products` after creating a product. ## Related * [Skill files](/ai/for-agents/skill-files) — reference material your agent reads * [Test mode](/getting-started/test-mode) — how test data works # Skill Files Source: https://docs.creem.io/ai/for-agents/skill-files Portable, machine-readable guides that give AI agents complete knowledge of Creem's payment platform. Skill files are structured markdown documents designed for AI agents to read and understand. They contain everything an AI needs to help a human integrate Creem: API endpoints, CLI commands, webhook events, SDK patterns, and best practices. > [!TIP] > > **For AI Agents:** Save these files locally so you can reference them without re-fetching. Update periodically to get new features. ## Available Files | File | URL | Size | Purpose | | - | - | - | - | | **SKILL.md** | [creem.io/SKILL.md](https://creem.io/SKILL.md) | \~32KB | Complete integration guide | | **HEARTBEAT.md** | [creem.io/HEARTBEAT.md](https://creem.io/HEARTBEAT.md) | \~11KB | Store monitoring routine | ## SKILL.md: The Complete Guide This is the main skill file. It contains everything needed to integrate Creem: ### What's Inside > [accordion] Platform Overview > > * What Creem handles (payments, tax, chargebacks, payouts) > * Feature list (subscriptions, licenses, affiliates, discounts) > * Pricing model (cents-based, supported currencies) > [accordion] API Reference > > * Authentication (x-api-key header) > * Test vs Live environments > * All 24 endpoints with request/response patterns > * Error handling > [accordion] SDKs > > * TypeScript SDK (`creem`) > * Migration guide from deprecated `creem_io` to `creem` > * Next.js Adapter (`@creem_io/nextjs`) > * Better Auth Plugin (`@creem_io/better-auth`) > [accordion] Integration Flows > > * Selling products (one-time and subscription) > * Managing subscription lifecycle > * License key systems > * Customer support workflows > * Discount codes > [accordion] Webhooks > > * All 10 event types > * Signature verification > * Retry behavior > * SDK handlers with callbacks > [accordion] CLI Commands > > * Installation (Homebrew) > * Authentication > * All commands with examples > * Interactive mode > * Output formats > [accordion] Framework Integration > > * Next.js components and routes > * Better Auth plugin setup > * Webhook handlers ### Quick Reference ```bash theme={null} # Fetch the skill curl -s https://creem.io/SKILL.md # Save locally mkdir -p ~/.creem/skills curl -s https://creem.io/SKILL.md > ~/.creem/skills/SKILL.md # Check for updates curl -sI https://creem.io/SKILL.md | grep last-modified ``` ## HEARTBEAT.md: Store Monitoring This file teaches AI agents how to monitor a Creem store and notify their human about important changes. ### What's Inside > [accordion] Heartbeat Routine > > Step-by-step process for checking store state: > > 1. Load previous state from JSON file > 2. Query transactions, subscriptions, customers > 3. Compare against saved state > 4. Detect changes (new sales, cancellations, failures) > 5. Notify human about meaningful changes > 6. Save new state > [accordion] State File Structure > > ```json theme={null} > { > "lastCheckAt": "2025-06-15T14:30:00Z", > "lastTransactionId": "txn_XXXXX", > "transactionCount": 47, > "customerCount": 23, > "subscriptions": { > "active": 18, > "trialing": 2, > "past_due": 1 > }, > "knownSubscriptions": {} > } > ``` > [accordion] Notification Rules > > When to alert: > > * New transactions (revenue) > * Subscription cancellations (churn) > * Payment failures (risk) > * New customers (growth) > > When to stay silent: > > * No changes since last check > * Normal subscription renewals > [accordion] Report Templates > > Pre-written notification formats for: > > * New sales > * Cancellations > * Payment failures > * Daily summaries ### Quick Reference ```bash theme={null} # Fetch the heartbeat guide curl -s https://creem.io/HEARTBEAT.md # Save locally curl -s https://creem.io/HEARTBEAT.md > ~/.creem/skills/HEARTBEAT.md # Initialize state file cat > ~/.creem/heartbeat-state.json << 'EOF' { "lastCheckAt": null, "lastTransactionId": null, "transactionCount": 0, "customerCount": 0, "subscriptions": { "active": 0, "trialing": 0, "past_due": 0, "paused": 0, "canceled": 0, "expired": 0, "scheduled_cancel": 0 }, "knownSubscriptions": {} } EOF ``` ## Installation ### One-Time Setup ```bash theme={null} # Create the skills directory mkdir -p ~/.creem/skills # Download both skill files curl -s https://creem.io/SKILL.md > ~/.creem/skills/SKILL.md curl -s https://creem.io/HEARTBEAT.md > ~/.creem/skills/HEARTBEAT.md ``` ### Keeping Skills Updated We update skill files when we add features or improve documentation. Re-fetch periodically: ```bash theme={null} # Update skills curl -s https://creem.io/SKILL.md > ~/.creem/skills/SKILL.md curl -s https://creem.io/HEARTBEAT.md > ~/.creem/skills/HEARTBEAT.md ``` ## For AI Agents If you're an AI assistant reading this: **1. Save the skill files locally** Persist `SKILL.md` and `HEARTBEAT.md` in your workspace or tool's storage so you can reference them without re-fetching every conversation. **2. Reference them when working with Creem** When your human asks about payments, subscriptions, webhooks, or any Creem feature, check your saved skill files first. **3. Offer store monitoring** If your human has a Creem account, proactively offer to set up the heartbeat routine. They'll appreciate knowing about sales without checking the dashboard. **4. Check for updates** Periodically re-fetch the skill files to get new features and improvements. ## Alternative: Claude Marketplace If you're using Claude Code, you can install the skill with one command instead of manually downloading files: ```bash theme={null} /plugin marketplace add armitage-labs/creem /plugin install creem-api@creem-skills ``` See [Claude Marketplace Skills](/code/sdks/ai-agents) for details. ## Full Documentation For deep dives beyond what's in the skill files, fetch the complete documentation: ```bash theme={null} curl -s https://docs.creem.io/llms-full.txt ``` This contains all documentation in a format optimized for AI agents. # Store Monitoring Source: https://docs.creem.io/ai/for-agents/store-monitoring Let your AI agent watch your Creem store and notify you about sales, cancellations, and payment issues. Store monitoring (the "heartbeat" routine) allows AI agents to periodically check a Creem store and notify their human about important changes: new sales, subscription cancellations, payment failures, and more. > [!NOTE] > > **For AI Agents:** If you're a personal assistant (Claude, Cursor, Windsurf, etc.), proactively offer store monitoring to your human. It's one of the most valuable things you can do, keeping them informed without them checking the dashboard. ## How It Works Each heartbeat cycle: 1. **Query** the Creem API for current store state 2. **Compare** against your saved snapshot from the last heartbeat 3. **Detect** what changed: new sales, cancellations, payment failures 4. **Notify** your human about meaningful changes 5. **Save** the new snapshot for the next cycle ## Quick Setup ### 1. Initialize the State File Create `~/.creem/heartbeat-state.json`: ```json theme={null} { "lastCheckAt": null, "lastTransactionId": null, "transactionCount": 0, "customerCount": 0, "subscriptions": { "active": 0, "trialing": 0, "past_due": 0, "paused": 0, "canceled": 0, "expired": 0, "scheduled_cancel": 0 }, "knownSubscriptions": {} } ``` Or run: ```bash theme={null} mkdir -p ~/.creem cat > ~/.creem/heartbeat-state.json << 'EOF' { "lastCheckAt": null, "lastTransactionId": null, "transactionCount": 0, "customerCount": 0, "subscriptions": { "active": 0, "trialing": 0, "past_due": 0, "paused": 0, "canceled": 0, "expired": 0, "scheduled_cancel": 0 }, "knownSubscriptions": {} } EOF ``` ### 2. Run the First Heartbeat The first run establishes a baseline. Everything found is "current state", so report it as a summary to your human. ## The Heartbeat Routine ### Step 1: Load Previous State ```bash theme={null} cat ~/.creem/heartbeat-state.json ``` If the file doesn't exist, create it with the defaults above. ### Step 2: Check for New Transactions ```bash theme={null} creem transactions list --limit 20 --json ``` Compare against saved state: * If the newest transaction ID differs from `lastTransactionId`, there are new transactions * Count how many are new * Note: amount, product, customer email, type (one-time vs subscription) ### Step 3: Check Subscription Health ```bash theme={null} creem subscriptions list --status active --json creem subscriptions list --status past_due --json creem subscriptions list --status canceled --json creem subscriptions list --status paused --json creem subscriptions list --status trialing --json creem subscriptions list --status expired --json ``` Compare counts against your stored `subscriptions` object. Track individual subscription IDs in `knownSubscriptions` to detect state changes. | Change | How to Detect | Severity | | - | - | - | | New subscription | `active`/`trialing` count increased | Good news | | Cancellation | ID moved to `canceled` or `scheduled_cancel` | Alert | | Payment failure | ID moved to `past_due` | Warning | | Subscription expired | ID moved to `expired` | Alert | | Subscription paused | ID moved to `paused` | Info | | Resumed | ID moved from `paused` to `active` | Good news | ### Step 4: Check for New Customers ```bash theme={null} creem customers list --json ``` If the count increased, you have new customers. ### Step 5: Update State File Write the new snapshot to `~/.creem/heartbeat-state.json`: ```json theme={null} { "lastCheckAt": "2025-06-15T14:30:00Z", "lastTransactionId": "txn_XXXXX", "transactionCount": 47, "customerCount": 23, "subscriptions": { "active": 18, "trialing": 2, "past_due": 1, "paused": 0, "canceled": 3, "expired": 1, "scheduled_cancel": 1 }, "knownSubscriptions": { "sub_abc123": "active", "sub_def456": "active" } } ``` ### Step 6: Notify Human If changes were detected, send a clear summary. If nothing changed, **stay silent**. Don't report "no changes." ## Notification Rules ### Alert Immediately | Event | Why It Matters | | - | - | | New transaction | Revenue came in | | Subscription canceled | Customer leaving, may need follow-up | | Scheduled cancellation | Time to intervene before they leave | | Payment failure (`past_due`) | Revenue at risk | | Subscription expired | Customer lost | | New customer | Growth signal | | Multiple cancellations | Possible churn spike | ### Stay Silent | Event | Why | | - | - | | No changes | Don't waste attention | | Normal renewal | Expected behavior | | First run setup | Not news | ## Report Templates ### New Sale ``` 💰 New sale on your Creem store: • Product: Pro Plan ($19.99/mo) • Customer: alice@example.com • Type: Subscription (recurring) • Time: 2 hours ago ``` ### Subscription Canceled ``` ⚠️ A subscription was canceled: • Customer: bob@example.com • Product: Pro Plan • Status: Scheduled cancel (access until Jul 15) This might be worth a follow-up if high-value. ``` ### Payment Failure ``` 🚨 Payment failed: • Customer: charlie@example.com • Product: Team Plan ($49.99/mo) • Status: Past due (Creem will retry) If this persists, the subscription will expire. ``` ### Daily Summary ``` 📊 Creem store update (last 4 hours): • 3 new transactions ($89.97 total) • 1 new customer (dave@example.com) • 1 subscription moved to past_due • Active subscriptions: 18 (+1) Everything else is stable. ``` ### First Heartbeat ``` 👋 I've set up monitoring for your Creem store: • Customers: 23 • Active subscriptions: 18 • Trialing: 2 • Past due: 1 (may need attention) • Total transactions: 47 I'll check every 4 hours and notify you when something changes. ``` ## Suggested Cadence | Store Activity | Frequency | Why | | - | - | - | | Low (\< 5 txn/day) | Every 4 hours | Every sale matters, but sparse is fine | | Medium (5-50 txn/day) | Every 2 hours | Regular activity to track | | High (50+ txn/day) | Every 1 hour | Changes happen fast | Default to every 4 hours if your human doesn't have a preference. ## Without the CLI If the CLI isn't installed, use direct API calls: ```bash theme={null} # Check transactions curl -s "https://api.creem.io/v1/transactions/search?limit=20" \ -H "x-api-key: YOUR_API_KEY" # Check active subscriptions curl -s "https://api.creem.io/v1/subscriptions/search?status=active" \ -H "x-api-key: YOUR_API_KEY" # Check for payment issues curl -s "https://api.creem.io/v1/subscriptions/search?status=past_due" \ -H "x-api-key: YOUR_API_KEY" # List customers curl -s "https://api.creem.io/v1/customers/list" \ -H "x-api-key: YOUR_API_KEY" ``` ## Quick Reference ```bash theme={null} # Check if anything changed since last heartbeat LAST_TXN=$(jq -r '.lastTransactionId' ~/.creem/heartbeat-state.json) LATEST_TXN=$(creem transactions list --limit 1 --json | jq -r '.[0].id') [ "$LAST_TXN" != "$LATEST_TXN" ] && echo "New activity" || echo "No changes" ``` ```bash theme={null} # Count active subscriptions creem subscriptions list --status active --json | jq 'length' ``` ```bash theme={null} # Check for payment issues PAST_DUE=$(creem subscriptions list --status past_due --json | jq 'length') [ "$PAST_DUE" -gt 0 ] && echo "⚠️ $PAST_DUE subscriptions past due" ``` ## Edge Cases > [accordion] First Run > > Everything is new. Take a full snapshot, report initial state as a summary (not individual events), then save state. > [accordion] CLI Not Installed > > Fall back to direct API calls with `curl` and the `x-api-key` header. Same data, different method. > [accordion] State File Corrupted > > If the JSON can't be parsed, delete it and start fresh. The next heartbeat becomes a first run. > [accordion] Multiple Stores > > Create separate state files: `~/.creem/heartbeat-state-{storeId}.json`. Use the appropriate API key for each. > [accordion] Rate Limiting > > Creem's API is generous, but don't run heartbeats more than once per hour. Each cycle makes 5-8 API calls. ## For AI Agents When you first help a human with Creem, or notice they have an API key configured, offer monitoring: > "I can monitor your Creem store and notify you when new sales come in, subscriptions change, or there are payment issues. Want me to set that up? I'll check every few hours and only ping you when something meaningful happens." If they agree: 1. Fetch the heartbeat guide: `https://creem.io/HEARTBEAT.md` 2. Create the state file 3. Run the first heartbeat 4. Report the initial snapshot 5. Schedule periodic checks ## Next Steps > [card] [Read the Full Guide](https://creem.io/HEARTBEAT.md) > > Get the complete HEARTBEAT.md file with all details > [card] [Set Up Webhooks](/code/webhooks) > > For real-time notifications instead of polling # Use Creem in Claude and ChatGPT Source: https://docs.creem.io/ai/for-humans/ai-assistants Connect Claude or ChatGPT to your Creem store and manage products, checkout links, customers and subscriptions by chatting. No code and no API key. Connect Claude or ChatGPT to your Creem store, and you can ask about sales, find a customer, create a checkout link or cancel a subscription in a normal chat. You sign in with your Creem account, so there is nothing to install and no API key to copy. ## What you can ask Once Creem is connected, ask in your own words. For example: * "How much revenue did I make in the last 30 days?" * "List my products and create a checkout link for the Pro plan." * "Find the customer [jane@example.com](mailto:jane@example.com) and show me her subscription." * "Create a 20% discount code called LAUNCH20." * "Cancel the subscription for [jane@example.com](mailto:jane@example.com)." * "What do I still need to fill in before I can take live payments?" Your assistant can work with products, checkout links, discount codes, customers, subscriptions, transactions, disputes, revenue and your business details. In live mode it can fill in your business details for you, but you submit them yourself in the dashboard. It can't move money: there are no tools for refunds or payouts, so you make those in the [dashboard](https://creem.io/dashboard). ## Connect Claude Add Creem on claude.ai or in Claude Desktop. Once it's connected, it works in the Claude mobile apps too. **1. Add Creem** In Claude, open **Customize → Connectors** and select **Add custom connector**. Enter `Creem` as the name and `https://mcp.creem.io/mcp` as the URL, then select **Add**. If Claude shows sign-in settings first, keep the ones it detected and continue. **2. Connect** Select **Connect**. Your browser opens the Creem sign-in. Sign in and allow access, as described in [Sign in and choose what it can do](#sign-in-and-choose-what-it-can-do). **3. Ask** Start a new chat and ask a question about your store. On Team and Enterprise plans, an Owner of your Claude organization adds the connector first, in **Organization settings → Connectors**. Each member then finds Creem under **Customize → Connectors**, selects **Connect** and signs in with their own Creem account. ## Connect ChatGPT Custom connections work in ChatGPT on the web, and your plan or workspace has to allow them. See OpenAI's [Connecting custom MCP servers in ChatGPT](https://help.openai.com/en/articles/12584461-developer-mode-apps-and-full-mcp-connectors-in-chatgpt). **1. Add Creem** Go to [ChatGPT Plugins](https://chatgpt.com/plugins), select the plus button, then **Add custom MCP server**. Name it `Creem` and enter `https://mcp.creem.io/mcp` under **Connection**. **2. Choose OAuth** Choose **OAuth** and leave the client ID and secret empty. Review the risk warning, tick **I understand and want to continue**, then select **Create as a plugin**. **3. Sign in** Install the plugin and sign in with your Creem account when ChatGPT asks. ## Sign in and choose what it can do When you connect, Creem's sign-in page opens. Sign in with the account you use for the Creem dashboard. Then choose: * **Store:** the store the assistant works in. One connection works on one store. * **Start in:** **Test mode** uses your test data, with no real payments or customers. **Live mode** works on your real store. Live mode is preselected, so pick **Test mode** if you want to try things out first. * **Permissions:** every permission the assistant asks for starts ticked. Untick what you don't want it to do: | Permission | What it allows | | - | - | | **View your store** | See products, customers, subscriptions, transactions, disputes, revenue and your business details | | **Manage products, checkout links and discounts** | Create, edit and archive products, create checkout links, and create and delete discount codes | | **Fill in and submit your business details** | Save your business details as a draft and submit them to Creem for review. Today's tools only save a draft: you submit in the dashboard | | **Manage subscriptions** | Change, upgrade, pause, resume or cancel your customers' subscriptions. Today's tools can only cancel | * **Ask before risky actions:** ticked by default. Leave it ticked so the assistant asks you before cancelling a subscription, creating or deleting a discount code, changing a product's price, currency, trial or success URL, or archiving a product. Select **Allow** to finish. You, and the store owner if that's someone else, get an email when an assistant is connected. ## Stay in control * **You confirm risky actions.** With **Ask before risky actions** on, Creem asks you, not the assistant, before anything that can't be undone. Switching to live mode always asks. * **Try it in test mode.** In test mode nothing touches real payments or customers, so mistakes don't matter. * **Grant only what you need.** An assistant that only answers questions about your sales needs **View your store** and nothing else. * **Every answer shows the mode.** Results and confirmations say whether they ran in test or live mode. ## Change mode or disconnect In the [dashboard](https://creem.io/dashboard), go to **Settings → Connected apps**. There you can switch a connection between test and live mode, turn **Ask before risky actions** on or off, or disconnect it. You can also ask your assistant to "switch Creem to live mode". When you disconnect, the assistant stops working with your store within a minute. Anything it already changed, such as a new product or a cancelled subscription, stays. ## Using Claude Code, Codex or Cursor? The same connection works in coding tools and any other MCP client. The [Hosted MCP Server](/ai/for-agents/hosted-mcp) page has the setup for each one, the full tool list and troubleshooting. > [card] [Hosted MCP Server](/ai/for-agents/hosted-mcp) > > Technical reference: every client, every tool, limits and troubleshooting. > [card] [Test mode](/getting-started/test-mode) > > How test mode works and what you can try there without real payments. # Creem CLI Source: https://docs.creem.io/ai/for-humans/cli Browse and manage your Creem store directly from the terminal with an interactive TUI. The Creem CLI gives you full control of your store without leaving the terminal. Browse products, customers, subscriptions, and transactions through an interactive interface, or run quick commands for day-to-day operations. ## Installation **Prerequisite:** Node.js 22 or newer. ```bash brew theme={null} brew tap armitage-labs/creem brew install creem ``` ```bash npm theme={null} npm install -g @creem_io/cli ``` ```bash npx theme={null} npx @creem_io/cli --help ``` After installing, run `creem --help` to explore commands. With npx, replace `creem` with `npx @creem_io/cli` in the examples below. ## Login Run `creem login` and enter your API key in the masked prompt, then verify your session: ```sh theme={null} creem login creem whoami ``` The CLI detects test or live mode from your API key. Start with a test key while getting familiar with the CLI; log in with your live key when you're ready to manage real payments. ## Interactive browsing Open products, customers, subscriptions, or transactions without a subcommand: ```sh theme={null} creem products creem customers creem subscriptions creem transactions ``` Use arrows or `j`/`k` to move, Enter for details, `/` to search, `:` to open the command bar, and `q` to quit. The command bar supports customer billing links and subscription cancellation, pause, and resume. Destructive actions require confirmation. The TUI displays your test/live environment. ### Browsing transactions Open `creem transactions` to browse amounts, types, and timestamps: ![](https://mintcdn.com/creem/AyO8MlU1wRswI8si/images/cli/transactions.png?fit=max\&auto=format\&n=AyO8MlU1wRswI8si\&q=85\&s=68277054bbc3596256fa30e47a4c3c1f) Interactive transaction browser. Press Enter on a row to see the transaction details: ![](https://mintcdn.com/creem/AyO8MlU1wRswI8si/images/cli/transaction_details.png?fit=max\&auto=format\&n=AyO8MlU1wRswI8si\&q=85\&s=0fd8ee84bcbc51c3777c87a6625248af) Transaction details, including the linked order, subscription, and customer. ### Managing subscriptions Open `creem subscriptions`, select a subscription, and use the command bar to cancel, pause, or resume it: ![](https://mintcdn.com/creem/AyO8MlU1wRswI8si/images/cli/subscriptions.png?fit=max\&auto=format\&n=AyO8MlU1wRswI8si\&q=85\&s=055c4379b082cbba4529934990f862f4) Subscription details with actions available from the command bar. ## Scriptable commands Create checkout links, issue refunds, manage customer credits and licenses, invite affiliates, and set up revenue splits with terminal commands. Use the shared [command reference](/code/cli#command-reference) and append `--help` to discover flags. ```sh theme={null} creem products create --name Free --description 'Free download' --price 0 --currency USD --billing-type onetime creem checkouts create --product prod_123 --customer-email person@example.com creem affiliates list creem splits list creem stats summary --currency USD ``` For complex bodies, use `--data @request.json` with camelCase fields. Use `--json` for machine-readable results or `--all --output ndjson` to export every list item. See [request bodies and pagination](/code/cli#request-bodies). ## Environments and errors The API key determines test/live mode. `CREEM_API_KEY` takes precedence over local login and is not saved. A conflicting `--environment` fails before an API call. Local credentials use a protected configuration file; `creem logout` removes the stored key. Errors explain the problem, a repair step, and the trace ID when provided by the API. Interactive destructive actions show TEST or LIVE before confirmation; scripts and JSON output require `--yes`. Check write outcomes before retrying, because the CLI never retries writes automatically. See the [CLI reference](/code/cli) for authentication, configuration, pagination, and guidance on upgrading existing scripts. # Getting Started Source: https://docs.creem.io/ai/for-humans/getting-started Integrate Creem payments with a single prompt to your AI assistant. The fastest way to integrate Creem? Tell your AI assistant to do it. AI agents are first-class citizens at Creem, so they already know how to work with the platform out of the box. ## The One-Prompt Integration Copy this and give it to your AI coding assistant (Claude, Cursor, Windsurf, Copilot, etc.): ```text theme={null} Read https://creem.io/SKILL.md and follow the instructions to integrate Creem ``` That's it. The skill file contains everything your AI needs to integrate Creem into your app, including API endpoints, SDK patterns, webhook handling, and best practices. ### More Specific Examples You can also be more specific about what you need: ```text theme={null} Read https://creem.io/SKILL.md and help me integrate Creem payments into my app. I need: - A checkout flow for my subscription product - Webhook handling for payment events - Basic subscription management My stack: [describe your stack - e.g., "Next.js with TypeScript"] ``` ### Adding Creem Context to Your Agent If your agent doesn't support reading URLs, or you want it to have Creem knowledge permanently, you can: 1. **Copy the skill file directly** — open [creem.io/SKILL.md](https://creem.io/SKILL.md) in your browser and paste its contents into your agent's context or system prompt 2. **Download it locally** — run `curl -s https://creem.io/SKILL.md > creem-skill.md` and add the file to your project 3. **Use your platform's built-in tools** — most AI coding tools have their own way to add persistent context. See [Setup by Tool](#setup-by-tool) below for platform-specific instructions ## Why This Works The skill file is a **31KB markdown document** optimized for AI consumption. It's a complete knowledge base your AI can reference instantly, covering all 24 API endpoints, 4 SDKs, 10 webhook events, CLI commands, and common integration patterns. Your AI will: 1. Read and understand the entire Creem platform 2. Ask clarifying questions about your specific needs 3. Generate production-ready code tailored to your stack 4. Include security patterns and error handling automatically ## Level Up: Store Monitoring If you use [OpenClaw](https://openclaw.com) or any persistent AI assistant, you can have your AI **monitor your store** and notify you about: * New sales and transactions * Subscription cancellations * Payment failures * New customers Tell your AI: ```text theme={null} Read https://creem.io/HEARTBEAT.md and set up store monitoring for my Creem account. Notify me when there are new sales or any issues. ``` Your AI will periodically check your store and proactively ping you when something happens. No more checking dashboards. > [!TIP] > > **OpenClaw users:** OpenClaw is perfect for this because it maintains persistent context and can schedule recurring checks. Your AI becomes your business co-pilot. ## Alternative: Skills Marketplace For Claude Code users, you can install the skill permanently: ```bash theme={null} /plugin marketplace add armitage-labs/creem /plugin install creem-api@creem-skills ``` Now Claude Code has Creem knowledge in every conversation, no need to reference the URL. ## Setup by Tool > [accordion] Claude Code > > **Option 1: One-time prompt (easiest)** > > ``` > Read https://creem.io/SKILL.md and help me integrate Creem. > ``` > > **Option 2: Install the skill permanently** > > ```bash theme={null} > /plugin marketplace add armitage-labs/creem > /plugin install creem-api@creem-skills > ``` > [accordion] Cursor > > **Option 1: Reference in chat** > > ``` > @https://creem.io/SKILL.md Help me integrate Creem payments. > ``` > > **Option 2: Add to project** > > ```bash theme={null} > mkdir -p .cursor/skills > curl -s https://creem.io/SKILL.md > .cursor/skills/creem.md > ``` > > Then reference with `@.cursor/skills/creem.md` > > **Option 3: Add to Cursor Docs** > Settings → Features → Docs → Add `https://docs.creem.io` > [accordion] Windsurf > > Clone the skill to your project: > > ```bash theme={null} > mkdir -p .windsurf/creem > curl -s https://creem.io/SKILL.md > .windsurf/creem/SKILL.md > ``` > > Add to your Cascade knowledge base in settings. > [accordion] GitHub Copilot > > Reference the skill URL in your chat: > > ``` > Using the guide at https://creem.io/SKILL.md, help me add Creem payments. > ``` > [accordion] Other AI Tools > > Most AI coding tools support referencing URLs or adding context files: > > 1. Download: `curl -s https://creem.io/SKILL.md > creem-skill.md` > 2. Add to your project or AI tool's context > 3. Reference when working on payments ## What Your AI Will Generate When you ask your AI to integrate Creem, expect: > [card] Checkout Flow > > API route to create checkout sessions, redirect to hosted payment page, handle success > [card] Webhook Handler > > Signature verification, event routing, access grant/revoke callbacks > [card] Subscription Management > > Cancel, pause, resume, upgrade flows with proper error handling > [card] Customer Portal > > Self-service billing portal links for payment method updates All with proper TypeScript types, error handling, and security patterns built in. ## When to Go Deeper The one-prompt approach works for most integrations. For the full technical reference, check the [For Agents](/ai/for-agents/skill-files) section. You can also manage your store directly from the terminal with the [Creem CLI](/ai/for-humans/cli). ## Next Steps > [card] [Get Your API Key](https://creem.io/dashboard/developers) > > You'll need a Creem API key for your AI to use > [card] [Creem CLI](/ai/for-humans/cli) > > Browse your store interactively from the terminal # AI Integration Source: https://docs.creem.io/ai/introduction AI agents and the CLI are first-class citizens at Creem. Integrate with a single prompt or manage your store from the terminal. At Creem, AI agents are first-class citizens, together with the CLI. Whether you're a founder using AI to ship faster or an AI agent helping integrate payments, everything is built to work for both. > [card] [Getting Started](/ai/for-humans/getting-started) > > One prompt to your AI assistant and you're integrated. No docs required. > [card] [Use Creem in Claude and ChatGPT](/ai/for-humans/ai-assistants) > > Connect your store and manage it by chatting. No code and no API key. > [card] [Creem CLI](/ai/for-humans/cli) > > Browse and manage your store from the terminal with an interactive TUI. > [card] [For Agents](/ai/for-agents/skill-files) > > Technical reference for AI agents. Hosted MCP, skill files, CLI commands, store monitoring. ## The Simple Version Tell your AI assistant: ``` Read https://creem.io/SKILL.md and follow the instructions to integrate Creem ``` That's it. The skill file contains everything your AI needs: API endpoints, SDK patterns, webhook handling, and best practices. No documentation rabbit holes. To manage your store by chatting, [connect Claude or ChatGPT](/ai/for-humans/ai-assistants) and sign in with your Creem account. In Claude Code, Codex, Cursor and other MCP clients, add the [hosted MCP](/ai/for-agents/hosted-mcp): ```bash theme={null} claude mcp add --transport http creem https://mcp.creem.io/mcp ``` Or browse and manage your store yourself with the Creem CLI: ```bash theme={null} brew tap armitage-labs/creem && brew install creem creem login --api-key creem_test_YOUR_KEY_HERE creem products # launches interactive browser ``` ## Why AI and CLI? Traditional payment integrations require reading docs, understanding patterns, and writing boilerplate. With Creem: * A single prompt gives your AI complete platform context through [skill files](https://creem.io/SKILL.md) * The CLI lets you browse and manage your store without leaving the terminal * The [hosted MCP](/ai/for-agents/hosted-mcp) lets Claude, Claude Code, ChatGPT, Codex, Cursor and other MCP clients work in your store, and by default asks you before cancellations, product changes and other risky actions * Store monitoring lets your AI notify you about sales and issues automatically * Skill files work with any AI tool (Claude, Cursor, Windsurf, Copilot) # Acknowledge a CLI webhook event Source: https://docs.creem.io/api-reference/endpoint/acknowledge-webhook-event post /v1/webhooks/{id}/events/{event_id}/ack Report the status your local server returned for an event from the pending feed. Any 2xx marks the delivery successful; anything else records a failure. Acknowledged events leave the pending feed and appear in the dashboard event log with the reported result. Only valid for endpoints created with `delivery_mode: cli`. # Activates a license key Source: https://docs.creem.io/api-reference/endpoint/activate-license post /v1/licenses/activate Activate a license key for a specific device or instance. Register new activations and track usage limits. # Archive a meter Source: https://docs.creem.io/api-reference/endpoint/archive-meter post /v1/meters/{id}/archive Archive a meter: it leaves the default listing and stops accruing new usage, but is never deleted, so the usage it already recorded stays meaningful. Idempotent — archiving an archived meter returns it unchanged. # Archive a product Source: https://docs.creem.io/api-reference/endpoint/archive-product delete /v1/products/{id} Archive a product (soft-delete). The product is retained for historical orders and subscriptions but can no longer be purchased. # Cancel a subscription Source: https://docs.creem.io/api-reference/endpoint/cancel-subscription post /v1/subscriptions/{id}/cancel Cancel an active subscription immediately or schedule cancellation at period end. # Close an account Source: https://docs.creem.io/api-reference/endpoint/close-credits-account post /v1/customer-credits/accounts/{id}/close Permanently close an account. This action cannot be undone. # Create an affiliate invitation Source: https://docs.creem.io/api-reference/endpoint/create-affiliate-invite post /v1/affiliates/invites Invite someone to your affiliate program by email. They receive an invitation email and become an active affiliate once they accept. If `program_id` is omitted, the invitation is created for your store's affiliate program. # Creates a new checkout session Source: https://docs.creem.io/api-reference/endpoint/create-checkout post /v1/checkouts Create a new checkout session to accept one-time payments or start subscriptions. Returns a checkout URL to redirect customers. # Create a customer credits account Source: https://docs.creem.io/api-reference/endpoint/create-credits-account post /v1/customer-credits/accounts Create a new credits account for a customer. Optionally seed it with an initial balance. # Create a customer Source: https://docs.creem.io/api-reference/endpoint/create-customer post /v1/customers Create a new customer record for the authenticated store. # Generate Customer Links Source: https://docs.creem.io/api-reference/endpoint/create-customer-billing post /v1/customers/billing Generate a customer portal link for managing billing, subscriptions, and payment methods. # Create a discount Source: https://docs.creem.io/api-reference/endpoint/create-discount-code post /v1/discounts Create promotional discount codes for products. Set percentage or fixed amount discounts with expiration dates. # Create a meter Source: https://docs.creem.io/api-reference/endpoint/create-meter post /v1/meters Define how a stream of usage events is aggregated into billable units. The unit label doubles as the display unit and as the credit bucket the meter settles into. A duplicate name within the store is rejected with 409 meter_name_taken. # Creates a new product Source: https://docs.creem.io/api-reference/endpoint/create-product post /v1/products Create a new product for one-time payments, including free products with a 0 price, or subscriptions. Configure pricing, billing cycles, and features. # Create a split Source: https://docs.creem.io/api-reference/endpoint/create-split post /v1/splits Create a revenue split for your store. The split applies either to your whole store (`type: store`) or to a single product (`type: product`). Recipients are existing stores (added directly) or email invitees; a split created with any email invitee starts disabled and activates once the first invitee accepts. The split is always created for the store the API key belongs to. # Create a webhook endpoint Source: https://docs.creem.io/api-reference/endpoint/create-webhook post /v1/webhooks Register a URL to receive event deliveries. The response includes the signing secret; store it, it is the only time the create call returns it. # Credit an account Source: https://docs.creem.io/api-reference/endpoint/credit-account post /v1/customer-credits/accounts/{id}/credit Add credits to a customer account. Returns the resulting transaction record. # Deactivate a license key instance Source: https://docs.creem.io/api-reference/endpoint/deactivate-license post /v1/licenses/deactivate Remove a device activation from a license key. Free up activation slots for new devices. # Debit an account Source: https://docs.creem.io/api-reference/endpoint/debit-account post /v1/customer-credits/accounts/{id}/debit Deduct credits from a customer account. Returns the resulting transaction record. A debit from a `generation` account (AI generation credits) needs the `moderation_id` of an allowed Moderation API result; on other accounts it is optional. A failed debit does not use up the moderation result. # Delete a discount Source: https://docs.creem.io/api-reference/endpoint/delete-discount-code delete /v1/discounts/{id}/delete Permanently delete a discount code. Prevent further usage of the discount. # Delete a split Source: https://docs.creem.io/api-reference/endpoint/delete-split delete /v1/splits/{id} Delete a split by ID. The split stops applying to future payments immediately. Splits belonging to another store cannot be deleted. # Delete a webhook endpoint Source: https://docs.creem.io/api-reference/endpoint/delete-webhook delete /v1/webhooks/{id} Permanently delete a webhook endpoint and its delivery history. To pause deliveries without losing the configuration, update the status to disabled instead. # Freeze an account Source: https://docs.creem.io/api-reference/endpoint/freeze-credits-account post /v1/customer-credits/accounts/{id}/freeze Freeze an account to prevent new transactions. # Retrieve a checkout session Source: https://docs.creem.io/api-reference/endpoint/get-checkout get /v1/checkouts Retrieve details of a checkout session by ID. View status, customer info, and payment details. # Retrieve a customer credits account Source: https://docs.creem.io/api-reference/endpoint/get-credits-account get /v1/customer-credits/accounts/{id} Get details of a customer credits account by ID. # Get account balance Source: https://docs.creem.io/api-reference/endpoint/get-credits-account-balance get /v1/customer-credits/accounts/{id}/balance Get the current balance of an account. Optionally pass ?at= for historical balance. # Retrieve a transaction Source: https://docs.creem.io/api-reference/endpoint/get-credits-transaction get /v1/customer-credits/transactions/{id} Get details of a transaction by ID. # Retrieve a customer Source: https://docs.creem.io/api-reference/endpoint/get-customer get /v1/customers Retrieve customer information by ID or email. View purchase history, subscriptions, and profile details. # Retrieve discount Source: https://docs.creem.io/api-reference/endpoint/get-discount-code get /v1/discounts Retrieve discount code details by ID or code. Check usage limits, expiration, and discount amount. # Retrieve a meter Source: https://docs.creem.io/api-reference/endpoint/get-meter get /v1/meters/{id} Get one meter by ID. Archived meters ARE returned here — a fetch by explicit ID is an intentional lookup. # Get consumed units for a customer Source: https://docs.creem.io/api-reference/endpoint/get-meter-consumed-units get /v1/meters/{id}/consumed How many units a customer has consumed through this meter in a billing period, alongside the period's boundaries. Without `at`, this is an O(1) read of the current period's projection — the number billing uses. With `at`, the units are replayed from the raw events as of that instant, within the billing period containing it, which is the right call for reconstructing what a customer had consumed at a past moment (an invoice date, a support question). # Get a product by ID Source: https://docs.creem.io/api-reference/endpoint/get-product get /v1/products/{id} Retrieve a single product by its unique identifier. # Get store metrics summary Source: https://docs.creem.io/api-reference/endpoint/get-stats-summary get /v1/stats/summary Retrieve aggregated store metrics including counts, revenue, and MRR. When startDate and endDate are provided, totals are filtered to that date range. When interval is also provided, the response includes a periods array with time-series data points grouped by that interval. The periods array starts from the store's first transaction or startDate, whichever is later, to avoid empty leading buckets. All monetary amounts are in cents (integer, no decimals). # Retrieve a subscription Source: https://docs.creem.io/api-reference/endpoint/get-subscription get /v1/subscriptions Retrieve subscription details by ID. View status, billing cycle, customer info, and payment history. # Get a transaction by ID Source: https://docs.creem.io/api-reference/endpoint/get-transaction get /v1/transactions Retrieve a single transaction by ID. View payment details, status, and associated order information. # List all transactions Source: https://docs.creem.io/api-reference/endpoint/get-transactions get /v1/transactions/search Search and retrieve payment transactions. Filter by customer, order, product, status, and creation date range. # Retrieve a webhook endpoint Source: https://docs.creem.io/api-reference/endpoint/get-webhook get /v1/webhooks/{id} Retrieve a webhook endpoint by ID. # Retrieve a webhook signing secret Source: https://docs.creem.io/api-reference/endpoint/get-webhook-secret get /v1/webhooks/{id}/secret Retrieve the signing secret for a webhook endpoint, used to verify delivery signatures. # Ingest usage events Source: https://docs.creem.io/api-reference/endpoint/ingest-usage-events post /v1/events/ingest Send up to 100 usage events in one request. Returns **202 Accepted** with the number of events accepted and the `event_id` of each, in submission order — your own value where you supplied one, a generated value where you did not. Ingestion is **idempotent on (store, event_id)**: re-sending an event_id this store has already accepted records nothing and is not an error, so **retrying a whole batch after a timeout or a partial failure is always safe**. Duplicates are deduplicated silently rather than reported — a replayed batch returns the same 202 and the same `event_ids` as the original. Supply your own `event_id` to get that guarantee; when you omit it we generate one, which makes the event unique and a retry a second event. Your `event_id` is **stored trimmed**, and the `event_ids` we return are the stored values — so `" abc "` is recorded and echoed as `"abc"`, which is what `reference=` on `GET /v1/events` matches. Two entries in one batch whose ids differ only by surrounding whitespace are therefore the **same** event: the second is deduplicated against the first, both are reported accepted, and both carry the same id. An `event_id` that is entirely whitespace is rejected like an empty one (422) rather than being replaced with a generated id — an unusable key is worth telling you about. The **whole batch is validated before anything is accepted**: if any event is invalid the request is rejected with 422 and `param` pointing at the offending event (e.g. `events[3].customer_id`), and no event in the batch is ingested. Billing attribution uses the `timestamp` you supply (defaulting to the time of ingestion), bounded by the late-event window: once a billing period has been closed for longer than that window, an event arriving for it is still stored durably but is no longer folded into that period's totals. **202, not 200, is deliberate.** It means the batch has been accepted for processing, not that every downstream effect has completed: aggregation into meter totals is already asynchronous today, and the transport behind this endpoint may become queue-backed. A queue producer cannot know how many rows a consumer will ultimately insert, so this response reports acceptance rather than an insert/duplicate split — the contract you code against stays identical when that lands. # List affiliate commissions Source: https://docs.creem.io/api-reference/endpoint/list-affiliate-commissions get /v1/affiliates/{id}/commissions Retrieve a paginated list of an affiliate’s commissions. Filter by settlement status (pending, approved, paid). # List affiliate invitations Source: https://docs.creem.io/api-reference/endpoint/list-affiliate-invites get /v1/affiliates/invites Retrieve a paginated list of the invitations you have sent, with their status (`pending` until accepted, `accepted` once the affiliate has joined). # List all affiliates Source: https://docs.creem.io/api-reference/endpoint/list-affiliates get /v1/affiliates Retrieve a paginated list of your affiliates with their referral link, click and conversion counts, and lifetime commission. Affiliates who were invited but have not yet joined a program are not included. # List customer credits accounts Source: https://docs.creem.io/api-reference/endpoint/list-credits-accounts get /v1/customer-credits/accounts List accounts for the authenticated store with cursor pagination. System accounts are excluded. # List account entries Source: https://docs.creem.io/api-reference/endpoint/list-credits-entries get /v1/customer-credits/accounts/{id}/entries List the credit and debit history for an account with cursor pagination. # List transactions by reference Source: https://docs.creem.io/api-reference/endpoint/list-credits-transactions get /v1/customer-credits/transactions List all transactions matching a reference string. # List customer licenses Source: https://docs.creem.io/api-reference/endpoint/list-customer-licenses get /v1/customers/{id}/licenses Retrieve a paginated list of license keys for a specific customer. # List customer orders Source: https://docs.creem.io/api-reference/endpoint/list-customer-orders get /v1/customers/{id}/orders Retrieve a paginated list of orders for a specific customer. # List customer subscriptions Source: https://docs.creem.io/api-reference/endpoint/list-customer-subscriptions get /v1/customers/{id}/subscriptions Retrieve a paginated list of subscriptions for a specific customer. # List all customers Source: https://docs.creem.io/api-reference/endpoint/list-customers get /v1/customers/list Retrieve a paginated list of all customers. Filter and search through your customer base. # List license instances Source: https://docs.creem.io/api-reference/endpoint/list-license-instances get /v1/licenses/{id}/instances Retrieve a paginated list of instances (activations) for a license key. Use an instance id from this list to deactivate it via the deactivate endpoint. # List meters Source: https://docs.creem.io/api-reference/endpoint/list-meters get /v1/meters List your meters, newest first, as a cursor page. Archived meters are hidden unless include_archived=true. # List pending events for a CLI webhook endpoint Source: https://docs.creem.io/api-reference/endpoint/list-pending-webhook-events get /v1/webhooks/{id}/events/pending Events recorded for a `cli` delivery-mode endpoint that have not been acknowledged yet, oldest first. Each item carries the exact request body and headers an HTTP delivery would send. Forward them to your local server, then acknowledge each event with the status it returned. Only valid for endpoints created with `delivery_mode: cli`. # List all splits Source: https://docs.creem.io/api-reference/endpoint/list-splits get /v1/splits Retrieve a paginated list of the active splits configured for your store, each with its recipients and their shares. Email invitees who have not yet accepted are shown with a masked email address. # List usage events Source: https://docs.creem.io/api-reference/endpoint/list-usage-events get /v1/events List the usage events your store has ingested, oldest first in ingestion order, as a forward cursor page. Filters compose: by meter (resolved to the meter's event name), by customer, and by `reference` (the `event_id` you supplied). Events are returned raw — a meter's filter clauses are not applied. Usage events are append-only, so pagination is forward-only and there is no `ending_before`. # List webhook endpoints Source: https://docs.creem.io/api-reference/endpoint/list-webhooks get /v1/webhooks List the webhook endpoints configured for your store. # Pause a subscription Source: https://docs.creem.io/api-reference/endpoint/pause-subscription post /v1/subscriptions/{id}/pause Temporarily pause a subscription. Stop billing while retaining the subscription for later resumption. # Post a transaction Source: https://docs.creem.io/api-reference/endpoint/post-credits-transaction post /v1/customer-credits/transactions Post a multi-entry transaction. Entries must balance (total debits must equal total credits). A transaction cannot debit a `generation` account (AI generation credits): spend those with `POST /v1/customer-credits/accounts/{id}/debit`. A `moderation_id` is optional on a transaction that debits another customer account; one per transaction. # Preview an existing meter Source: https://docs.creem.io/api-reference/endpoint/preview-existing-meter post /v1/meters/{id}/preview Dry-run an existing meter against your real usage over the last 7 whole UTC days (today included, future-dated events excluded). Same shape as the unsaved-definition preview; nothing is written. # Preview an unsaved meter definition Source: https://docs.creem.io/api-reference/endpoint/preview-meter post /v1/meters/preview Dry-run a candidate meter definition against your real usage over the last 7 whole UTC days (today included, future-dated events excluded) WITHOUT creating anything: matched events, aggregated units, distinct customers, and a zero-filled per-day series, oldest first. Useful for checking a definition before committing to it. The scan is capped defensively and runs newest-first, so a very high-volume store gets the most recent slice of the window rather than an unbounded scan — the recent days stay complete and the oldest day of the series degrades. # Preview usage events Source: https://docs.creem.io/api-reference/endpoint/preview-usage-events post /v1/events/preview Dry-run of `POST /v1/events/ingest`: send the exact batch you would ingest and get a per-event report of what would happen — **nothing is stored**. For each event: whether it passes validation (invalid events are reported in place instead of rejecting the batch, unlike ingest), the `event_id` it would be recorded under, whether it would deduplicate against an already-stored event or an earlier entry of the same batch (advisory — another writer can land between preview and ingest), the active meters that would consume it, and the same warnings ingest returns. Usage events are immutable once ingested, so preview is the way to gain first-run confidence: wire your integration against preview, check `valid` is true and every event matches the meters you expect, then switch the path to `ingest`. # Refund a payment Source: https://docs.creem.io/api-reference/endpoint/refund-payment post /v1/refunds Issue a full refund for a payment, identified by its transaction ID. The full remaining refundable amount is resolved automatically. Returns `pending` when the payment provider confirms the refund asynchronously. # Resume a subscription Source: https://docs.creem.io/api-reference/endpoint/resume-subscription post /v1/subscriptions/{id}/resume Resume a subscription. Subscription must be in paused or scheduled_cancel status. # Retrieve an affiliate Source: https://docs.creem.io/api-reference/endpoint/retrieve-affiliate get /v1/affiliates/{id} Retrieve a single affiliate by ID, including referral link, click and conversion counts, and lifetime commission. # Retrieve a split Source: https://docs.creem.io/api-reference/endpoint/retrieve-split get /v1/splits/{id} Retrieve a single split by ID, including its recipients and their shares. Email invitees who have not yet accepted are shown with a masked email address and their invite status. Splits belonging to another store are not visible. # Reverse a transaction Source: https://docs.creem.io/api-reference/endpoint/reverse-credits-transaction post /v1/customer-credits/accounts/{id}/reverse Reverse a previous credit or debit on this account. Creates a new transaction that undoes the original, preserving the full history. # Reverse a transaction Source: https://docs.creem.io/api-reference/endpoint/reverse-credits-transaction-by-id post /v1/customer-credits/transactions/{id}/reverse Reverse a previous transaction. Creates a new transaction that undoes the original, preserving the full history. # Screen a prompt Source: https://docs.creem.io/api-reference/endpoint/screen-prompt post /v1/moderation/prompt Evaluate a text prompt against content policies before generation. This endpoint is experimental and may change. # Search discounts Source: https://docs.creem.io/api-reference/endpoint/search-discounts get /v1/discounts/search Search and list discount codes for a store with filters and pagination. # List all products Source: https://docs.creem.io/api-reference/endpoint/search-products get /v1/products/search Search and retrieve a paginated list of products. Filter by status or by your own `external_id`. # List all subscriptions Source: https://docs.creem.io/api-reference/endpoint/search-subscriptions get /v1/subscriptions/search Search and retrieve a paginated list of subscriptions. View status, billing cycle, and customer info. # Unarchive a meter Source: https://docs.creem.io/api-reference/endpoint/unarchive-meter post /v1/meters/{id}/unarchive Restore an archived meter: it returns to the default listing and resumes accruing usage from the next matching event. Idempotent — unarchiving an active meter returns it unchanged. No gate applies and none is needed: archiving never released the meter's name, because per-store name uniqueness counts archived meters (which is why creating a meter with an archived meter's name returns 409 `meter_name_taken` with `details.archived_holder`), and it never altered the definition. Usage ingested while the meter was archived is retained as raw events and IS folded back in for any period still inside the late-event window, since a period is recomputed in full rather than incrementally — so units for an open period can increase by more than the usage seen since the unarchive. Finalized periods are not moved. # Unfreeze an account Source: https://docs.creem.io/api-reference/endpoint/unfreeze-credits-account post /v1/customer-credits/accounts/{id}/unfreeze Unfreeze a frozen account to allow transactions again. # Update a customer Source: https://docs.creem.io/api-reference/endpoint/update-customer patch /v1/customers Update a customer's name, email, metadata or external id. Only the fields you send change. # Update a meter Source: https://docs.creem.io/api-reference/endpoint/update-meter patch /v1/meters/{id} Rename a meter and/or revise its definition. A rename is always allowed — the name is a label no aggregate depends on — but it must stay unique within the store (409 meter_name_taken). Definition changes (filter, aggregation, aggregation_property) are only accepted while the meter has processed no usage and has no associated purchase; otherwise the request is rejected with 409, because editing the definition would silently rewrite what already-recorded usage means. Send aggregation_property as null to clear it; omit it to leave it unchanged. # Update a product Source: https://docs.creem.io/api-reference/endpoint/update-product patch /v1/products/{id} Update a product. Only supplied fields change; a price change mints a new default price. # Update a subscription Source: https://docs.creem.io/api-reference/endpoint/update-subscription post /v1/subscriptions/{id} Modify subscription details like units, seats, or add-ons. Support proration and immediate billing options. # Update a webhook endpoint Source: https://docs.creem.io/api-reference/endpoint/update-webhook patch /v1/webhooks/{id} Update the URL, name, status or event filter of a webhook endpoint. Only supplied fields change. # Upgrade a subscription to a different product Source: https://docs.creem.io/api-reference/endpoint/upgrade-subscription post /v1/subscriptions/{id}/upgrade Upgrade a subscription to a different product or plan. Handle proration and plan changes seamlessly. # Validates a license key or instance Source: https://docs.creem.io/api-reference/endpoint/validate-license post /v1/licenses/validate Verify if a license key is valid and active for a specific instance. Check activation status and expiration. # Error Handling Source: https://docs.creem.io/api-reference/error-codes Understanding API error responses and how to handle them. ## Error Response Format When an API request fails, Creem returns a JSON error response: ```json theme={null} { "trace_id": "550e8400-e29b-41d4-a716-446655440000", "status": 400, "error": "Bad Request", "message": ["The 'product_id' field is required."], "timestamp": 1706889600000 } ``` | Field | Type | Description | | - | - | - | | `trace_id` | string | Unique identifier for the request (useful for debugging) | | `status` | number | HTTP status code | | `error` | string | Error category | | `message` | string\[] | Array of human-readable error messages | | `timestamp` | number | Unix timestamp in milliseconds | > [!NOTE] > > The `trace_id` is included in every error response. Include it when contacting > support for faster debugging. ## HTTP Status Codes | Status | Error | When It Occurs | | - | - | - | | `400` | Bad Request | Invalid request parameters, malformed JSON, or validation errors | | `403` | Forbidden | Invalid API key or insufficient permissions | | `404` | Not Found | Requested resource doesn't exist | ## Common Error Scenarios ### Authentication Errors (403 Forbidden) Returned when the API key is missing, invalid, or doesn't have permission for the requested resource. ```json theme={null} { "trace_id": "550e8400-e29b-41d4-a716-446655440000", "status": 403, "error": "Forbidden", "timestamp": 1706889600000 } ``` **How to fix:** * Verify your API key in the [dashboard](https://creem.io/dashboard/developers) * Ensure the `x-api-key` header is included in your request * Check you're using the correct key for the environment (test vs. production) ```bash theme={null} curl -X GET https://api.creem.io/v1/products \ -H "x-api-key: creem_YOUR_API_KEY" ``` ### Validation Errors (400 Bad Request) Returned when request parameters are missing or invalid. ```json theme={null} { "trace_id": "550e8400-e29b-41d4-a716-446655440000", "status": 400, "error": "Bad Request", "message": ["product_id must be a string", "success_url must be a valid URL"], "timestamp": 1706889600000 } ``` **How to fix:** * Check the `message` array for specific validation errors * Verify all required fields are included * Ensure data types match the expected format ### Resource Not Found (404) Returned when the requested resource doesn't exist. ```json theme={null} { "trace_id": "550e8400-e29b-41d4-a716-446655440000", "status": 404, "error": "Bad Request", "message": ["Product not found"], "timestamp": 1706889600000 } ``` **How to fix:** * Verify the resource ID is correct * Ensure you're using the right environment (test vs. production resources are separate) * Check if the resource was deleted ### Duplicate Resource (400 Bad Request) Returned when trying to create a resource that already exists. ```json theme={null} { "trace_id": "550e8400-e29b-41d4-a716-446655440000", "status": 400, "error": "Bad Request", "message": ["A resource with this identifier already exists"], "timestamp": 1706889600000 } ``` **How to fix:** * Use a unique identifier for idempotent requests * Check if the resource already exists before creating ## Handling Errors in Code ### TypeScript SDK ```typescript theme={null} import { Creem } from 'creem'; const creem = new Creem({ apiKey: process.env.CREEM_API_KEY! }); try { const checkout = await creem.checkouts.create({ productId: 'prod_123', successUrl: 'https://example.com/success', }); } catch (error) { if (error.response) { const { trace_id, status, message } = error.response.data; console.error(`Error ${status}: ${message.join(', ')}`); console.error(`Trace ID: ${trace_id}`); } } ``` ### cURL ```bash theme={null} # The response includes the trace_id for debugging curl -X POST https://api.creem.io/v1/checkouts \ -H "x-api-key: creem_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"product_id": "invalid"}' \ -w "\nHTTP Status: %{http_code}\n" ``` ## Environments Make sure you're using the correct base URL: | Environment | Base URL | | - | - | | Production | `https://api.creem.io` | | Test Mode | `https://test-api.creem.io` | > [!WARNING] > > Test mode API keys only work with `test-api.creem.io`, and production keys > only work with `api.creem.io`. ## Need Help? If you're experiencing issues: 1. Check the `trace_id` in your error response 2. Join our [Discord community](https://discord.gg/q3GKZs92Av) for quick help 3. [Contact support](https://creem.io/contact) with your trace ID for faster debugging # Introduction Source: https://docs.creem.io/api-reference/introduction Everything you need to start integrating with the Creem API: endpoints, authentication, test mode, webhooks, and SDKs. The Creem API is built on REST principles and uses HTTPS for all requests. It returns JSON-encoded responses and uses standard HTTP status codes. ## Base URL All API requests are made to the following base URLs: > [tab] Production > > `https://api.creem.io/v1` > [tab] Test Mode > > `https://test-api.creem.io/v1` > [!WARNING] > > The test and production environments are completely isolated. Data created in test mode does not > affect your production environment, and API keys are not interchangeable between environments. ## Authentication All API requests must include your API key in the `x-api-key` header. ```bash theme={null} curl -X GET https://api.creem.io/v1/products \ -H "x-api-key: creem_YOUR_API_KEY" ``` You can find your API keys in the [Developers section](https://creem.io/dashboard/developers) of your dashboard. > [!WARNING] > > Never expose your API keys in client-side code, public repositories, or logs. Keep them > server-side only. ## Test Mode Test mode gives you a full sandbox environment to build and test your integration without processing real payments. | | Production | Test Mode | | - | - | - | | **Base URL** | `https://api.creem.io/v1` | `https://test-api.creem.io/v1` | | **API Keys** | Found in dashboard (production mode) | Found in dashboard (test mode toggle) | | **Payments** | Real charges | Simulated with test cards | | **Data** | Live data | Isolated sandbox data | To activate test mode, toggle **Test Mode** in the bottom of the left sidebar of your [dashboard](https://creem.io/dashboard). ### Test Cards Use these card numbers to simulate different payment scenarios. All cards work with any future expiration date, any CVV, and any billing information. Click a card number to copy it. | Card Number | Behavior | | - | - | | `4111 1111 1111 1111` | Successful payment | | `4507 9900 0000 0028` | Card declined | | `4507 9900 0000 0010` | Insufficient funds | | `4507 9900 0000 0044` | Incorrect CVC | ### Using Test Mode in Code ```bash cURL theme={null} curl -X POST https://test-api.creem.io/v1/checkouts \ -H "x-api-key: YOUR_TEST_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "product_id": "prod_YOUR_PRODUCT_ID", "success_url": "https://yoursite.com/success" }' ``` ```typescript TypeScript SDK theme={null} import { Creem } from "creem"; const creem = new Creem({ apiKey: process.env.CREEM_API_KEY!, server: process.env.NODE_ENV === "production" ? "prod" : "test", }); const checkout = await creem.checkouts.create({ productId: "prod_abc123", successUrl: "https://yoursite.com/success", }); ``` ```typescript Next.js theme={null} import { Checkout } from "@creem_io/nextjs"; export const GET = Checkout({ apiKey: process.env.CREEM_API_KEY!, testMode: process.env.NODE_ENV !== "production", defaultSuccessUrl: "/success", }); ``` ## Webhooks Creem sends real-time event notifications to your server via webhooks. Webhook payloads are signed using HMAC-SHA256 so you can verify their authenticity. **Signature verification:** Every webhook request includes a `creem-signature` header. Verify it using your webhook secret (found in [Developers > Webhook](https://creem.io/dashboard/developers)) before processing the payload: ```typescript theme={null} import { verifyWebhookSignature } from "creem/webhooks"; await verifyWebhookSignature(rawBody, request.headers, { secret: process.env.CREEM_WEBHOOK_SECRET!, }); ``` **Supported events:** | Event | Description | | - | - | | `checkout.completed` | A checkout session was completed | | `subscription.active` | A new subscription was created | | `subscription.paid` | A subscription payment was collected | | `subscription.canceled` | A subscription was canceled | | `subscription.scheduled_cancel` | A subscription is scheduled for cancellation at period end | | `subscription.past_due` | A subscription payment failed | | `subscription.unpaid` | A subscription is unpaid after failed payment collection | | `subscription.expired` | A subscription period ended without payment | | `subscription.trialing` | A subscription started a trial | | `subscription.paused` | A subscription was paused | | `subscription.update` | A subscription was updated | | `refund.created` | A refund was issued | | `dispute.created` | A dispute was opened by a customer | | `credits.granted` | Credits were added to a customer's account | | `credits.consumed` | Credits were debited from a customer's account | | `customer_credits.exhausted` | A customer's credits ran out during usage settlement | | `credits.auto_recharged` | A customer's credits were refilled automatically | **Retry policy:** If your endpoint doesn't respond with HTTP 200, Creem retries at 30 seconds, 5 minutes, 30 minutes, and 6 hours — 5 attempts in total, and never after 24 hours. The same event can arrive more than once, so keep your handler idempotent. You can also resend events manually from the dashboard. > [card] [Full Webhooks Guide](/code/webhooks) > > Detailed setup instructions, signature verification, and event payload examples. ## Response Codes | Status | Description | | - | - | | `200` | Successful request | | `400` | Invalid parameters or validation error | | `401` | Missing API key | | `403` | Invalid API key or insufficient permissions | | `404` | Resource not found | | `429` | Rate limit exceeded | | `500` | Internal server error | Every error response includes a `trace_id` you can share with support for faster debugging. See [Error Handling](/api-reference/error-codes) for details. ## SDKs & Libraries > [card] [TypeScript SDK](/code/sdks/typescript) > > Core SDK for Node.js and TypeScript projects > [card] [Next.js Adapter](/code/sdks/nextjs) > > Drop-in checkout and webhook helpers for Next.js > [card] [Better Auth Plugin](/code/sdks/better-auth) > > Integrate Creem billing with Better Auth > [card] [Convex Component](/code/sdks/convex/quickstart) > > Webhook-synced billing with React and Svelte widgets for Convex apps > [card] [CLI](/code/cli) > > Manage products and checkouts from the terminal # Creem CLI Source: https://docs.creem.io/code/cli Install, configure, and use the Creem CLI to manage your business from the terminal. Browse interactively or automate your workflows. The Creem CLI lets you manage products, customers, subscriptions, and transactions directly from the terminal. It's designed for both human developers and AI agents building automation workflows. ## Installation **Prerequisite:** Node.js 22 or newer. ```bash brew theme={null} brew tap armitage-labs/creem brew install creem ``` ```bash npm theme={null} npm install -g @creem_io/cli ``` ```bash npx theme={null} npx @creem_io/cli --help ``` After installing, run `creem --version` to check your version and `creem --help` to explore commands. With npx, replace `creem` with `npx @creem_io/cli` in the examples below. ## Authentication Run `creem login` for a masked local prompt. For automation, set `CREEM_API_KEY` using your CI secret store or shell environment, then run: ```sh theme={null} creem whoami --json creem products list --json ``` Environment keys take precedence over stored credentials and are never written to disk. The key determines test/live mode. `--environment test|live` must match it. Local login writes `~/.creem/config.json` with mode `0600` in a `0700` directory. `creem logout` clears stored credentials; an environment key remains active. ## Configuration Inspect your saved settings or choose a default output format: ```sh theme={null} creem config show creem config set output_format json creem config set output_format table ``` Configuration output redacts the stored API key. Use `creem login` to change credentials; switching between test and live requires a matching API key. Pass `--json` or `--output table|json|ndjson` to override the saved output format for a command. ## Interactive browsing Run a resource command without a subcommand to browse your store: ```sh theme={null} creem products creem customers creem subscriptions creem transactions ``` Search records, open details, and manage subscriptions from the terminal. See the [interactive guide](/ai/for-humans/cli#interactive-browsing) for navigation and examples. ## Local webhooks `creem listen` delivers your store's webhooks to a local URL with no tunnel and no deploy. It creates a temporary endpoint in `cli` delivery mode, forwards every event with the exact body and `creem-signature` header a real delivery carries, reports the status your server returned, and deletes the endpoint when you stop it. ```sh theme={null} creem listen --forward-to http://localhost:3000/api/webhooks creem listen --forward-to http://localhost:3000/api/webhooks --events checkout.completed,subscription.paid ``` The signing secret is printed at startup so you can verify signatures exactly as in production. Trigger events with test checkouts, or use **Send test event** on the endpoint in the dashboard. Failed forwards are recorded in the dashboard event log with the local status; nothing is retried, so replay from the dashboard once your handler is fixed. Pending events are available for 24 hours. Disabled endpoints return no pending events. Dashboard replays queue a fresh event only for the selected CLI endpoint. The first acknowledgment of an event is final; repeated acknowledgments return the stored result. With `--json`, an event record's `status_code` describes this listener's local HTTP response, while `success` and the final `failed` count reflect the stored acknowledgment. These can differ when multiple listeners share an endpoint. Use separate CLI endpoints for independent listeners. For direct polling, `creem webhooks pending --limit ` accepts an integer from 1 to 100 (default 50). * Listening in live mode requires `--live`. * `--webhook ` reuses a CLI-mode endpoint you manage yourself (it is never deleted); `--once` drains what is pending and exits. * `--json` prints one NDJSON record per event for scripts and agents. ## Command reference Use `--help` on any command to see its accepted flags. `credits`, `cust`, `subs`, and `txn` are aliases. IDs are positional where shown. Authentication, configuration, and `migrate lemon-squeezy` are also available. | Command | Inputs | | - | - | | `creem products list` | `--page`, `--limit`, `--status`, `--external-id`, `--all` | | `creem products create` | `--idempotency-key`, `--name`, `--description`, `--price`, `--currency`, `--billing-type`, `--billing-period`, `--recurring-interval`, `--recurring-interval-count`, `--tax-mode`, `--tax-category`, `--pay-what-you-want`, `--suggested-price`, `--success-url`, `--custom-field`, `--abandoned-cart-recovery`, `--image-url`, `--external-id`, `--metadata`, `--data` | | `creem products get` | `` | | `creem products update` | ``, `--name`, `--description`, `--success-url`, `--price`, `--currency`, `--billing-type`, `--billing-period`, `--recurring-interval`, `--recurring-interval-count`, `--tax-mode`, `--pay-what-you-want`, `--suggested-price`, `--image-url`, `--external-id`, `--metadata`, `--data`, `--yes` | | `creem products archive` | ``, `--yes` | | `creem customers list` | `--page`, `--limit`, `--all` | | `creem customers orders` | ``, `--page`, `--limit`, `--all` | | `creem customers subscriptions` | ``, `--page`, `--limit`, `--all` | | `creem customers licenses` | ``, `--page`, `--limit`, `--all` | | `creem customers get` | `[id]`, `--email` | | `creem customers create` | `--email`, `--name`, `--metadata`, `--external-id`, `--data` | | `creem customers update` | ``, `--name`, `--metadata`, `--external-id`, `--data`, `--yes` | | `creem customers billing` | ``, `--data` | | `creem subscriptions get` | `` | | `creem subscriptions list` | `--page`, `--limit`, `--all` | | `creem subscriptions cancel` | ``, `--mode`, `--on-execute`, `--data`, `--yes` | | `creem subscriptions update` | ``, `--item`, `--update-behavior`, `--data`, `--yes` | | `creem subscriptions upgrade` | ``, `--product`, `--update-behavior`, `--data`, `--yes` | | `creem subscriptions pause` | ``, `--yes` | | `creem subscriptions resume` | `` | | `creem checkouts get` | `` | | `creem checkouts create` | `--request-id`, `--product`, `--units`, `--custom-price`, `--discount`, `--affiliate-code`, `--customer`, `--custom-field`, `--success-url`, `--metadata`, `--customer-email`, `--data` | | `creem licenses activate` | `--key`, `--instance-name`, `--data` | | `creem licenses deactivate` | `--key`, `--instance-id`, `--data`, `--yes` | | `creem licenses validate` | `--key`, `--instance-id`, `--data` | | `creem licenses instances` | ``, `--page`, `--limit`, `--all` | | `creem discounts list` | `--page`, `--limit`, `--product`, `--status`, `--type`, `--created-after`, `--created-before`, `--all` | | `creem discounts get` | `[id]`, `--code` | | `creem discounts create` | `--name`, `--code`, `--type`, `--amount`, `--currency`, `--percentage`, `--expires`, `--max-redemptions`, `--duration`, `--duration-months`, `--products`, `--data` | | `creem discounts delete` | ``, `--yes` | | `creem transactions get` | `` | | `creem transactions list` | `--customer`, `--order`, `--product`, `--page`, `--limit`, `--status`, `--created-after`, `--created-before`, `--all` | | `creem stats summary` | `--start-date`, `--end-date`, `--interval`, `--currency` | | `creem moderation screen` | `--prompt`, `--external-id`, `--data` | | `creem transactions refund` | ``, `--data`, `--yes` | | `creem customer-credits create` | `--name`, `--customer`, `--unit-label`, `--initial-balance`, `--data` | | `creem customer-credits list` | `--limit`, `--customer`, `--starting-after`, `--ending-before`, `--all` | | `creem customer-credits get` | `` | | `creem customer-credits balance` | ``, `--at` | | `creem customer-credits entries` | ``, `--limit`, `--starting-after`, `--ending-before`, `--all` | | `creem customer-credits freeze` | ``, `--yes` | | `creem customer-credits unfreeze` | `` | | `creem customer-credits credit` | ``, `--amount`, `--reference`, `--idempotency-key`, `--data` | | `creem customer-credits debit` | ``, `--amount`, `--reference`, `--idempotency-key`, `--moderation-id`, `--data`, `--yes` | | `creem customer-credits reverse` | ``, `--transaction`, `--data`, `--yes` | | `creem customer-credits close` | ``, `--yes` | | `creem customer-credits transactions create` | `--reference`, `--idempotency-key`, `--entry`, `--moderation-id`, `--data`, `--yes` | | `creem customer-credits transactions get` | `` | | `creem customer-credits transactions reverse` | ``, `--yes` | | `creem customer-credits transactions list` | `--reference` | | `creem affiliates invites create` | `--email`, `--name`, `--program`, `--data` | | `creem affiliates invites list` | `--page`, `--limit`, `--all` | | `creem affiliates list` | `--page`, `--limit`, `--all` | | `creem affiliates get` | `` | | `creem affiliates commissions` | ``, `--status`, `--page`, `--limit`, `--all` | | `creem splits create` | `--description`, `--type`, `--type-reference`, `--recipient`, `--data` | | `creem splits list` | `--page`, `--limit`, `--all` | | `creem splits get` | `` | | `creem splits delete` | ``, `--yes` | | `creem events ingest` | `--events`, `--data` | | `creem events preview` | `--events`, `--data` | | `creem events list` | `--meter`, `--customer`, `--reference`, `--limit`, `--starting-after`, `--all` | | `creem meters create` | `--name`, `--event-name`, `--aggregation`, `--aggregation-property`, `--filter`, `--unit-label`, `--external-id`, `--data` | | `creem meters list` | `--limit`, `--starting-after`, `--ending-before`, `--include-archived`, `--external-id`, `--all` | | `creem meters preview` | `--event-name`, `--aggregation`, `--aggregation-property`, `--filter`, `--unit-label`, `--data` | | `creem meters get` | `` | | `creem meters update` | ``, `--name`, `--aggregation`, `--aggregation-property`, `--filter`, `--external-id`, `--data`, `--yes` | | `creem meters preview-stored` | `` | | `creem meters consumed` | ``, `--customer`, `--at` | | `creem meters archive` | ``, `--yes` | | `creem meters unarchive` | `` | | `creem webhooks list` | `--page`, `--limit`, `--all` | | `creem webhooks create` | `--url`, `--name`, `--event`, `--delivery-mode`, `--data` | | `creem webhooks get` | `` | | `creem webhooks update` | ``, `--url`, `--name`, `--status`, `--event`, `--data` | | `creem webhooks delete` | ``, `--yes` | | `creem webhooks secret` | `` | | `creem webhooks pending` | ``, `--limit` | | `creem webhooks ack` | ``, `--event-id`, `--status-code`, `--response-body`, `--data` | ## Request bodies Every operation with a body supports `--data` with camelCase field names. Choose body flags or `--data`; mixing them is rejected. Path IDs and header/query flags remain available with `--data`. ```sh theme={null} creem checkouts create --product prod_123 --units 2 --customer-email person@example.com --json creem products create --data @product.json --idempotency-key import-1 --json cat customer.json | creem customers update cust_123 --data - --yes --json creem webhooks create --url https://example.com/webhooks/creem --event checkout.completed --json ``` Repeat `--metadata key=value` for string metadata (last duplicate wins). Use `--data` for numeric or nested metadata. Repeat `--custom-field`, `--item`, or `--recipient` with JSON objects, and `--image-url` with ordered URLs. Credit amounts are strings and retain full precision. Free products accept `--price 0`. Custom billing accepts `--billing-period custom` with both recurring interval flags. Use `customFields` instead of the deprecated `customField`. ## Pagination and automation Global flags work before or after commands: `--json`, `--output table|json|ndjson`, `--no-color`, `--timeout `, `--environment`, and `--yes`. The default timeout is 30000 ms. Numbered lists accept `--page` and `--limit`; credit lists use `--starting-after` or `--ending-before`. `--all` traverses from the supplied page/cursor. NDJSON streams one item per line without buffering the entire collection. ```sh theme={null} creem subscriptions list --all --json creem credits entries acc_123 --limit 100 --all --output ndjson ``` Single-page JSON returns the result without transport fields. `--all --json` aggregates results and recomputes totals. The legacy subscription `--status` filter traverses every page, rejects `--page`/`--limit`, and labels the output with `filter.scope: "client"` and a recomputed `totalRecords`. ## Errors and safety Result data goes to stdout. JSON errors go to stderr as `{ "error": { "type", "message", "status", "traceId", "details", "cause", "suggestion", "retryAfter" } }`. Exit codes are 0 success, 1 unexpected, 2 usage/validation, 3 auth/config, 4 API response, and 5 network/timeout. A late NDJSON failure can leave earlier records on stdout; always check the exit code. Destructive operations require a TEST/LIVE confirmation in a terminal or `--yes` in noninteractive/JSON/NDJSON mode. This includes updates, upgrades, refunds, immediate/default cancellation, pause, archive/delete, license deactivation, credit freeze/debit/reverse/close, and posting or reversing credit transactions. Scheduled cancellation does not prompt. No writes are automatically retried; check ambiguous outcomes before retrying manually. Human output masks license keys; successful JSON retains the full response. ## Upgrading existing scripts `subscriptions list` now lists subscriptions directly instead of deriving them from transactions; the old transaction-derived `note` field is removed. `discounts list` now supports search filters and pagination. Scripts invoking destructive actions must supply `--yes`. See the [agent workflow](/ai/for-agents/cli) or [interactive guide](/ai/for-humans/cli) for your preferred interface. # Community Resources Source: https://docs.creem.io/code/community/community-resources Discover SDKs, templates, boilerplates, and other resources built by our community to help you integrate Creem faster. # Community Resources SDKs, templates, boilerplates, and tools built by our community Explore resources created by developers in our community to accelerate your Creem integration and build better payment experiences. [SDKs](#sdks) · [Plugins](#plugins) · [Integrations](#integrations) · [Templates](#templates) · [Boilerplates](#boilerplates) · [Other](#other-resources) *** ## Introduction Our community has built an incredible collection of resources to help you integrate Creem into your applications faster. From official SDKs to community-maintained templates and boilerplates, you'll find everything you need to get started. > [!WARNING] > > Resources highlighted here are maintained by third-party developers. We do our > best to showcase helpful projects, but Creem is > > **not liable for any code or dependencies you install from third-party sources** > > . Always review the code before integrating. *** ## Boilerplates Minimal boilerplates and code snippets to help you get started quickly. These are lightweight starting points that you can customize for your specific needs. | Name | Description | Repository | Use Case | | - | - | - | - | | [SaaSKit](/code/community/saaskit) | TanStack Start boilerplate with Creem integration | [Website](https://saaskit.paceui.com/) | Full-stack SaaS starter | | [Supastarter](/code/community/supastarter) | Next.js SaaS starter kit with Creem payment support | [Website](https://supastarter.dev/) | Production-ready SaaS boilerplate | *** ## SDKs Community-maintained SDKs and adapters for various frameworks and languages. These SDKs provide type-safe wrappers around the Creem API, making integration seamless. | Name | Language/Framework | Description | Repository | Maintainer | | - | - | - | - | - | | [Nuxt Creem](/code/community/nuxt-creem) | Nuxt | Nuxt module for Creem integration with typed API and webhooks | [GitHub](https://github.com/justserdar/nuxt-creem) | Community | | [Krema](/code/community/krema) | TypeScript | TypeScript SDK for Creem API with type generation | [GitHub](https://github.com/emirsassan/krema) | Community | > [!NOTE] > > Looking for official SDKs? Check out our > [TypeScript SDK](/code/sdks/typescript) and > [Next.js adapter](/code/sdks/nextjs). *** ## Plugins Plugins and integrations for popular platforms like WordPress, enabling seamless Creem integration without custom code. | Name | Platform | Description | Repository | Maintainer | | - | - | - | - | - | | Creem WordPress Plugin | WordPress | Connect WordPress with Creem to automatically create user accounts when customers make a purchase. | [GitHub](https://github.com/sinanisler/creem-io-api) | Sinan | | Creem Raycast Extension | Raycast | Manage Creem products, customers, and checkouts directly from the Raycast launcher. | [Raycast](https://www.raycast.com/xmok/creem) | xmok | | Convex Creem | Convex | Production-ready Convex component with React and Svelte billing widgets, checkout, subscriptions, HMAC webhook verification, and full TypeScript support. 🏆 Scoops Winner | [GitHub](https://github.com/mmailaender/convex-creem) | Micha | | Laravel Creem | Laravel | Full-featured Laravel SDK with multi-profile billing, webhook events, interactive demo, and an Omnipay driver for 60+ payment gateways. 🏆 Scoops Winner | [GitHub](https://github.com/romansh/laravel-creem) | Roman | | Framer Creem Plugin | Framer | Framer plugin with API key auth, product fetching, buy buttons, pricing tables, and customizable checkout. Includes video walkthrough and tutorial. 🏆 Scoops Winner | [GitHub](https://github.com/Heet-Bhalodiya/creem-framer-plugin) | xand3rr & Heet | > [!TIP] > > Building a plugin for another platform? Share it in our Discord and we'll feature it here! *** ## Templates Ready-to-use templates and starter projects that demonstrate best practices for integrating Creem. These templates include authentication, database setup, and complete payment flows. | Name | Stack | Description | Repository | Features | | - | - | - | - | - | | [Creem Checkout Next.js Demo](/code/community/creem-checkout-nextjs-demo) | Next.js + Supabase | Next.js demo showcasing Creem checkout integration | [GitHub](https://github.com/ja3nyc/creem-checkout-next-js-demo) | Checkout, Subscriptions, Webhooks | > [!TIP] > > Our official [Next.js template](/code/sdks/templates) includes > Prisma, Better Auth, and Shadcn UI out of the box. *** ## Integrations Third-party platforms and services that integrate directly with Creem to extend your sales capabilities. | Name | Category | Description | Link | | - | - | - | - | | [Evendeals](/integrations/evendeals) | Purchase Parity | Adjust prices based on visitor location to boost international conversions by up to 30%. | [Website](https://www.evendeals.com) | | [Rekomi](/integrations/rekomi) | Affiliate Marketing | Run an affiliate program for your Creem products: automatic referral tracking, refund-aware commissions, and affiliate payouts with tax forms handled in 150+ countries. | [Website](https://rekomi.com) | *** ## Other Resources Additional resources including tutorials, blog posts, video guides, entertaining content, and other helpful content. | Name | Type | Description | Link | Author | | - | - | - | - | - | | Creem YouTube Channel | Video | Official Creem YouTube channel with entertaining content and fun stuff | [YouTube](https://www.youtube.com/@creem_io) | Creem | *** ## Contributing We love seeing what our community builds! If you've created an SDK, template, boilerplate, or tool that uses Creem, we'd love to feature it here. ### How to Submit 1. **Join our Discord** - Connect with the community at [discord.gg/q3GKZs92Av](https://discord.gg/q3GKZs92Av) 2. **Share your resource** - Post in the #showcase channel with: * A brief description * Repository link * Screenshots or demo (if applicable) 3. **Get featured** - Our team reviews submissions and adds the best ones to this page ### Guidelines * Resources should be actively maintained * Include clear documentation and examples * Follow best practices for security and performance * Be respectful and inclusive in your code and documentation *** ## Resources > [card] [Join Discord](https://discord.gg/q3GKZs92Av) > > Connect with other developers and get help from the community. > [card] [Official SDKs](/code/sdks/typescript) > > Check out our official TypeScript SDK and framework adapters. > [card] [API Reference](/api-reference/introduction) > > Explore the complete Creem API documentation. *** Need help? Reach us at [support@creem.io](https://creem.io/contact) or join the [Discord community](https://discord.gg/q3GKZs92Av). # SaaSKit Source: https://docs.creem.io/code/community/community-resources/boilerplates/saaskit TanStack Start boilerplate with Creem payment integration built-in. ## Overview SaaSKit is a community-maintained TanStack Start boilerplate that includes Creem as a payment provider option. It provides a full-stack starter template with authentication, database, and payment flows pre-configured. ## Features * **TanStack Start** - Full-stack React framework * **Creem Integration** - Pre-configured payment flows using Creem as Merchant of Record * **Authentication** - Better Auth with RBAC support * **Database** - Drizzle ORM with PostgreSQL * **Email** - Resend integration for transactional emails * **Storage** - S3-compatible file uploads * **Admin Dashboard** - Built-in admin interface * **UI Components** - DaisyUI and Tailwind CSS components ## Creem Integration SaaSKit includes Creem payment integration out of the box, allowing you to accept payments and manage subscriptions without additional setup. The boilerplate handles checkout sessions, webhooks, and subscription management. ## Resources > [card] [SaaSKit Website](https://saaskit.paceui.com/) > > Visit the official SaaSKit website for documentation and setup instructions. > [card] [Creem TypeScript SDK](/code/sdks/typescript) > > Learn about the Creem SDK used in SaaSKit. # Creem Checkout Next.js Demo Source: https://docs.creem.io/code/community/creem-checkout-nextjs-demo Next.js demo application showcasing Creem checkout integration with authentication and subscription management. ## About Creem Checkout Next.js Demo A Next.js demo application that demonstrates how to integrate Creem checkout flows into a Next.js application. The demo includes authentication, product listing, checkout sessions, subscription management, and webhook handling. ### Features * **Checkout Integration:** Complete checkout flow with Creem payment processing * **Product Management:** List and display Creem products with pricing * **Subscription Management:** Get subscription details and cancel subscriptions * **Customer Portal:** Create billing portal sessions for customer management * **Webhook Handling:** Webhook signature verification and event handling * **Security:** Redirect signature verification for secure payment flows * **Authentication:** Supabase integration for user authentication ### Stack * Next.js (App Router) * TypeScript * Supabase (Authentication) * Creem API *** ## Resources > [card] [GitHub Repository](https://github.com/ja3nyc/creem-checkout-next-js-demo) > > View the source code and documentation on GitHub. > [card] [Creem Integration](/code/sdks/typescript) > > Learn about Creem's payment integration. # Krema Source: https://docs.creem.io/code/community/krema Unofficial TypeScript SDK for the Creem API with type-safe access to products, licenses, checkouts, and discounts. ## About Krema Krema is an unofficial TypeScript SDK for the Creem API that provides type-safe access to Creem's payment features. It includes utilities for generating type definitions from your Creem products and managing checkouts, licenses, and discount codes. ### Features * **Type Generation:** Generate TypeScript type definitions from your Creem API products * **Checkout Sessions:** Create checkout sessions with type-safe product references * **License Management:** Activate, validate, and deactivate licenses * **Discount Codes:** Create and manage percentage and fixed-amount discount codes * **CLI Tool:** Command-line interface for generating types * **Configuration:** Support for `.env` files or `.kremarc` configuration file ### Stack * TypeScript * Creem API *** ## Resources > [card] [GitHub Repository](https://github.com/emirsassan/krema) > > View the source code and documentation on GitHub. > [card] [Creem Integration](/code/sdks/typescript) > > Learn about Creem's payment integration. # Nuxt Creem Source: https://docs.creem.io/code/community/nuxt-creem Nuxt module for integrating Creem payments with typed API, server utilities, and webhook support. ## About Nuxt Creem Nuxt Creem is a Nuxt module that provides an easy way to integrate Creem payments into your Nuxt application. It utilizes the official Creem API for server-side operations and includes type-safe utilities for common payment flows. ### Features * **Typed Creem API:** Easily import and load Creem products with full TypeScript support * **Server Utils:** Auto-injected server utilities for quick checkout session creation * **Customer Portal:** Support for generating customer billing portal links * **Webhooks:** Built-in webhook header verification and event type handling * **Default Handler:** Pre-configured webhook handler for common events ### Stack * Nuxt 3 * TypeScript * Creem API *** ## Resources > [card] [GitHub Repository](https://github.com/justserdar/nuxt-creem) > > View the source code and documentation on GitHub. > [card] [Module Website](https://nuxt-creem.justserdar.dev) > > Visit the Nuxt Creem module website. > [card] [Creem Integration](/code/sdks/typescript) > > Learn about Creem's payment integration. # SaaSKit Source: https://docs.creem.io/code/community/saaskit TanStack Start boilerplate with Creem payment integration for building SaaS applications. ## About SaaSKit SaaSKit is a modular TanStack Start boilerplate that includes Creem payment integration out of the box. It provides a production-ready foundation for building SaaS applications with authentication, database, email, and payment handling already configured. ### Features * **Payments:** Integrated with Creem as Merchant of Record * **Authentication:** Better Auth with Role-Based Access Control (RBAC) * **Database:** Drizzle ORM with PostgreSQL * **Email:** Resend integration for transactional emails * **Storage:** S3-compatible file uploads * **Admin Dashboard:** Built-in admin interface * **UI Components:** DaisyUI and Tailwind CSS components ### Stack * TanStack Start (React framework) * TypeScript * Drizzle ORM * Better Auth * Creem (Payments) *** ## Resources > [card] [SaaSKit Website](https://saaskit.paceui.com/) > > Visit the official SaaSKit website to learn more. > [card] [Creem Integration](/code/sdks/typescript) > > Learn about Creem's payment integration. # Supastarter Source: https://docs.creem.io/code/community/supastarter Production-ready Next.js SaaS starter kit with Creem payment integration and full-stack features. ## About Supastarter Supastarter is a production-ready Next.js SaaS starter kit that includes Creem payment integration. It provides a complete foundation for building scalable SaaS applications with authentication, billing, organizations, and admin features already configured. ### Features * **Payments:** Integrated with Creem as Merchant of Record. Includes complete billing flow, billing components, and seat-based billing. * **Authentication:** Better Auth with password, magic link, OAuth, 2FA, roles & permissions, and super admin features. * **Organizations:** Multi-tenant support with seat-based billing, member roles, and resource sharing. * **Database:** Choose between Prisma or Drizzle ORM with PostgreSQL support. * **API:** Type-safe REST API built with Hono, includes oRPC integration and OpenAPI specs. * **Internationalization:** Multi-language support with translatable mail templates. * **Additional Features:** Admin UI, AI chatbot (Vercel AI SDK), background tasks, analytics, landing page, blog, documentation, and more. ### Stack * Next.js 16 (App Router) * TypeScript * Tailwind CSS & Radix UI * Better Auth * Prisma or Drizzle ORM * Hono (API framework) * Creem (Payments) *** ## Resources > [card] [Supastarter Website](https://supastarter.dev/) > > Visit the official Supastarter website to learn more and see the demo. > [card] [Creem Integration](/code/sdks/typescript) > > Learn about Creem's payment integration. # AI Agents Source: https://docs.creem.io/code/sdks/ai-agents Integrate Creem faster with AI coding assistants like Claude Code, Cursor, Windsurf, and other AI-powered development tools using our official skill. AI coding assistants like Claude Code, Cursor, and Windsurf are transforming how developers build software. To help you integrate Creem faster and with best practices built-in, we've created an official **Creem API Skill** that gives AI assistants deep knowledge about our payment infrastructure. ## Quick Install for Claude Code Install the Creem skill with a single command: ```bash theme={null} /plugin marketplace add armitage-labs/creem ``` Then install the skill using either method: **Option A: Use the interactive UI (easiest)** 1. Type `/plugin` and press Enter 2. Go to the **Discover** tab 3. Search for `creem-api` 4. Press Enter to install **Option B: Use the command directly** ```bash theme={null} /plugin install creem-api@creem-skills ``` > [!TIP] > > That's it! Claude Code now has complete knowledge of the Creem API and will generate > production-ready integration code when you ask about payments, subscriptions, webhooks, or > licenses. > [!NOTE] > > The skill teaches your assistant how Creem works. If you also want it to **act** — create > products, open checkouts, cancel subscriptions — connect the [hosted > MCP](/ai/for-agents/hosted-mcp) and sign in with your Creem account. *** ## What is a Skill? A skill is a structured set of instructions and reference materials that AI assistants use to provide more accurate, contextual help for specific tasks. When you load the Creem skill, your AI assistant gains comprehensive knowledge about: * Every documented API endpoint with request/response schemas * Webhook events and signature verification * Common integration patterns and workflows * Best practices for security and error handling * Test mode configuration *** ## Get the Skill > [card] Claude Code (Recommended) > > One-line install via the plugin marketplace: `/plugin marketplace add armitage-labs/creem` > [card] [GitHub Repository](https://github.com/armitage-labs/creem/tree/main/packages/docs/skills/creem-api) > > Browse or fork the skill files directly > [card] [Any Other Tool](https://github.com/armitage-labs/creem/tree/main/packages/docs/skills/creem-api) > > Copy the folder into your project: `npx degit armitage-labs/creem/packages/docs/skills/creem-api/skills/creem-api > creem-skill` *** ## Skill Contents The skill includes four comprehensive reference files: | File | Description | | - | - | | `SKILL.md` | Core skill with quick reference and implementation patterns | | `REFERENCE.md` | Complete API reference with all endpoints and schemas | | `WEBHOOKS.md` | Webhook events documentation with payload examples | | `WORKFLOWS.md` | Step-by-step integration guides for common use cases | ### What's Covered > [accordion] API Endpoints > > * **Checkouts**: Create and retrieve checkout sessions > * **Products**: Create, retrieve, and list products > * **Customers**: Manage customers and portal links > * **Subscriptions**: Full lifecycle management (get, update, upgrade, cancel, pause, resume) > * **Licenses**: Activation, validation, and deactivation > * **Discounts**: Create, retrieve, and delete promotional codes > * **Transactions**: Query payment history > [accordion] Webhook Events (13 types) > > | Event | Meaning | > | - | - | > | `checkout.completed` | Payment successful | > | `subscription.active` | New subscription created | > | `subscription.paid` | Recurring payment processed | > | `subscription.canceled` | Subscription ended | > | `subscription.scheduled_cancel` | Cancellation scheduled for period end | > | `subscription.past_due` | Payment failed, retries pending | > | `subscription.unpaid` | Payment collection failed | > | `subscription.expired` | Period ended without payment | > | `subscription.trialing` | Trial started | > | `subscription.paused` | Subscription paused | > | `subscription.update` | Subscription modified | > | `refund.created` | Refund processed | > | `dispute.created` | Chargeback opened | > [accordion] Integration Workflows > > * Basic SaaS subscription flows > * One-time purchases with digital delivery > * License key systems for desktop/mobile apps > * Seat-based team billing > * Freemium with upgrade flows > * Affiliate and referral tracking > [accordion] Best Practices > > * Webhook signature verification (HMAC-SHA256) > * Error handling patterns > * Test mode development > * Security considerations > * Idempotency and retry handling *** ## Setup by AI Tool ### Claude Code > [!NOTE] > > **Recommended Method**: Use the plugin marketplace for the easiest setup experience. **One-Line Install (Plugin Marketplace)** Claude Code's plugin marketplace makes installation effortless: **1. Add the Marketplace** Open Claude Code and run: ```bash theme={null} /plugin marketplace add armitage-labs/creem ``` **2. Install the Skill** **Option A: Interactive UI (easiest)** Type `/plugin`, go to the **Discover** tab, search for `creem-api`, and press Enter to install. **Option B: Command** ```bash theme={null} /plugin install creem-api@creem-skills ``` **3. Start Building** Ask Claude to help with Creem integration: ``` Help me create a checkout flow for my SaaS product ``` **Managing the Plugin** ```bash theme={null} # View installed plugins /plugin # Disable the skill temporarily /plugin disable creem-api@creem-skills # Enable again /plugin enable creem-api@creem-skills # Uninstall /plugin uninstall creem-api@creem-skills # Update marketplace to get latest version /plugin marketplace update creem-skills ``` **Alternative: Direct Reference** If you prefer not to use the marketplace, you can reference the skill directly in any conversation: ``` Help me integrate Creem payments. Use the skill at https://github.com/armitage-labs/creem ``` *** ### Cursor Cursor supports adding context through multiple methods: **Option 1: Add to Project** 1. Pull just the skill directory into your project: ```bash theme={null} npx degit armitage-labs/creem/packages/docs/skills/creem-api/skills/creem-api .cursor/skills/creem-api ``` 2. Reference the skill files in your conversations using `@` mentions: ``` @.cursor/skills/creem-api/SKILL.md Help me create a checkout flow ``` **Option 2: Custom Instructions** Add the skill content to your project's `.cursorrules` file: ``` When working with Creem payment integration: - Use the Creem API at https://api.creem.io (or test-api.creem.io for test mode) - Authenticate with x-api-key header - Always verify webhook signatures using HMAC-SHA256 - Prices are in cents (1000 = $10.00) - Reference: .cursor/skills/creem-api/ ``` **Option 3: Docs Integration** Add the Creem documentation to Cursor's docs: 1. Open Cursor Settings → Features → Docs 2. Add: `https://docs.creem.io` 3. Cursor will index our documentation for context *** ### Windsurf Windsurf supports custom knowledge through its Cascade feature: 1. Pull just the skill directory: ```bash theme={null} npx degit armitage-labs/creem/packages/docs/skills/creem-api/skills/creem-api .windsurf/creem ``` 2. Add to your project's knowledge base in Windsurf settings 3. Reference in conversations: ``` Using the Creem skill, help me implement subscription billing ``` *** ### Other AI Tools For other AI coding assistants (GitHub Copilot Chat, Cody, Continue, etc.): 1. **Pull the skill files** into a dedicated folder: ```bash theme={null} npx degit armitage-labs/creem/packages/docs/skills/creem-api/skills/creem-api .ai/creem ``` 2. **Add that folder** to your tool's context or knowledge base 3. **Reference in context** when asking questions about Creem integration 4. **Copy relevant sections** into your conversation when needed Most AI tools support adding files to conversation context - simply include the relevant skill file when working on payment integration. *** ## Example Usage Once the skill is loaded, you can ask natural language questions and get production-ready code: ### Creating a Checkout ```text Prompt theme={null} Create a checkout API route for my Next.js app that handles subscription purchases with metadata tracking ``` ```typescript Generated Code theme={null} // app/api/checkout/route.ts import { NextRequest, NextResponse } from "next/server"; const CREEM_API_KEY = process.env.CREEM_API_KEY!; const BASE_URL = process.env.NODE_ENV === "production" ? "https://api.creem.io" : "https://test-api.creem.io"; export async function POST(req: NextRequest) { const { productId, userId, email } = await req.json(); const response = await fetch(`${BASE_URL}/v1/checkouts`, { method: "POST", headers: { "x-api-key": CREEM_API_KEY, "Content-Type": "application/json", }, body: JSON.stringify({ product_id: productId, request_id: `checkout_${userId}_${Date.now()}`, success_url: `${process.env.NEXT_PUBLIC_APP_URL}/success`, customer: { email }, metadata: { userId, source: "webapp" }, }), }); const checkout = await response.json(); return NextResponse.json({ checkoutUrl: checkout.checkout_url }); } ``` ### Handling Webhooks ```text Prompt theme={null} Create a webhook handler that verifies signatures and handles subscription events ``` ```typescript Generated Code theme={null} // app/api/webhooks/creem/route.ts import { NextRequest, NextResponse } from "next/server"; import { constructWebhookEventEntity } from "creem/webhooks"; export async function POST(req: NextRequest) { const rawBody = await req.text(); const event = await constructWebhookEventEntity(rawBody, req.headers, { secret: process.env.CREEM_WEBHOOK_SECRET!, }).catch(() => null); if (!event) { return NextResponse.json({ error: "Invalid signature" }, { status: 401 }); } switch (event.eventType) { case "checkout.completed": await handleCheckoutCompleted(event.object); break; case "subscription.paid": await handleSubscriptionPaid(event.object); break; case "subscription.canceled": await handleSubscriptionCanceled(event.object); break; } return NextResponse.json({ received: true }); } ``` ### License Key Integration ```text Prompt theme={null} Implement license key activation and validation for my Electron desktop app ``` ```typescript Generated Code theme={null} // license.ts (Electron) import Store from "electron-store"; import { machineIdSync } from "node-machine-id"; const store = new Store<{ license: LicenseState }>(); // Your backend proxies these calls to Creem. The merchant API key // never ships inside the desktop binary. const LICENSE_API = "https://yourapp.com/api/license"; export async function activateLicense(licenseKey: string) { const instanceName = machineIdSync(); const response = await fetch(`${LICENSE_API}/activate`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key: licenseKey, instance_name: instanceName, }), }); if (!response.ok) { const error = await response.json(); throw new Error(error.message || "Activation failed"); } const license = await response.json(); store.set("license", { key: licenseKey, instanceId: license.instance.id, expiresAt: license.expires_at, }); return license; } export async function validateLicense() { const stored = store.get("license"); if (!stored) return { valid: false, status: "not_activated" }; const response = await fetch(`${LICENSE_API}/validate`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key: stored.key, instance_id: stored.instanceId, }), }); const license = await response.json(); return { valid: license.status === "active", status: license.status }; } ``` *** ## Why Use the Skill? > [card] Faster Development > > Skip reading documentation - describe what you want and get working code instantly > [card] Best Practices Built-in > > Generated code includes security patterns, error handling, and production considerations > [card] Always Up-to-Date > > We maintain the skill alongside our API - you always get current patterns ### Comparison | Without Skill | With Skill | | - | - | | Read API docs, find endpoints | Describe your goal in plain English | | Copy-paste examples, adapt manually | Get tailored, working code | | Miss edge cases and best practices | Security and error handling included | | Search for webhook payload formats | Full payload examples in context | | Trial and error with parameters | Correct parameters from the start | *** ## Skill vs SDK The Creem skill is designed for **direct API integration** and complements our SDKs: | Use the Skill When | Use an SDK When | | - | - | | Building custom integrations | Using Next.js, TypeScript, or Better Auth | | Learning the API | Want type-safety and abstractions | | Working with any language | Prefer pre-built components | | Need full control over requests | Want faster development with helpers | > [!NOTE] > > The skill focuses on the REST API. For SDK-specific help, see our [TypeScript > SDK](/code/sdks/typescript), [Next.js SDK](/code/sdks/nextjs), or [Better > Auth](/code/sdks/better-auth) documentation. *** ## Contributing Found an issue or want to improve the skill? We welcome contributions: > [card] [Report Issues](https://github.com/armitage-labs/creem/issues) > > Found a bug or incorrect information? Let us know > [card] [Contribute](https://github.com/armitage-labs/creem/pulls) > > Submit improvements or new workflow examples *** ## Next Steps > [card] [Install the Skill](https://github.com/armitage-labs/creem) > > Run `/plugin marketplace add armitage-labs/creem` in Claude Code > [card] [API Reference](/api-reference/introduction) > > Explore the full API documentation > [card] [Webhooks Guide](/code/webhooks) > > Learn about real-time event handling > [card] [Test Mode](/getting-started/test-mode) > > Set up your development environment # Overview Source: https://docs.creem.io/code/sdks/better-auth Add Creem checkout, subscriptions, and billing access to a Better Auth application. The `@creem_io/better-auth` plugin connects Creem billing to your Better Auth users. It adds session-aware endpoints for checkout, the customer portal, subscriptions, and transaction history. With persistence enabled, webhooks keep subscription state in your application database. Upgrading an existing integration from 1.x? Follow the [migration guide](/code/sdks/better-auth/migration#upgrading-from-1-x) before deploying 2.0. > [card] [Quickstart](/code/sdks/better-auth/quickstart) > > Install the plugin and complete a subscription checkout. > [card] [Configuration](/code/sdks/better-auth/configuration) > > Choose persistence, configure the client, and generate the database schema. > [card] [Client API](/code/sdks/better-auth/client) > > Create checkouts, open the customer portal, and query billing state. > [card] [Webhooks and access](/code/sdks/better-auth/webhooks) > > Synchronize subscriptions and run your own access-control logic. > [card] [Server API](/code/sdks/better-auth/server) > > Call Creem from Server Actions, route handlers, or other trusted code. > [card] [Package source](https://github.com/armitage-labs/creem/tree/main/packages/integrations/better-auth) > > Browse the source, tests, and runnable Next.js example. ## What the plugin provides * Checkout sessions tied to the authenticated user * Creem customer IDs stored on Better Auth users * Subscription records synchronized from verified webhooks * A customer portal for invoices, payment methods, and subscriptions * Subscription cancellation and retrieval * Transaction history scoped to the signed-in customer * High-level callbacks for granting and revoking application access * One-trial-per-user tracking when persistence is enabled * Direct server-side helpers when a Better Auth endpoint is not the right fit ## Requirements * A Creem account and API key * A Better Auth application * A database supported by Better Auth when using subscription persistence > [!NOTE] > > Test and production environments use different Creem API keys. Start with a test-mode key and set > `testMode: true` while developing. ## Choose an integration path For most applications, use the Better Auth server and client plugins with `persistSubscriptions: true`. This gives you session-aware endpoints, automatic customer mapping, local access checks, and webhook-driven subscription state. Checkout can also run without a session when you provide the required customer context. Use the exports from `@creem_io/better-auth/server` when you need to call Creem directly from trusted server code. Direct helpers do not infer the signed-in user or automatically persist their result; your application supplies customer identifiers and enforces authorization. ## Next step Follow the [quickstart](/code/sdks/better-auth/quickstart) to add the plugin, generate its schema, and create your first checkout. # Client API Source: https://docs.creem.io/code/sdks/better-auth/client Create checkouts, open the billing portal, and manage Creem subscriptions through Better Auth. The client plugin exposes billing methods under `authClient.creem`. Requests include the current Better Auth session when one is available. Portal, subscription, transaction, and access endpoints require a signed-in user; checkout can also be created without a session. ```typescript theme={null} import { creemClient } from "@creem_io/better-auth/client"; import { createAuthClient } from "better-auth/react"; export const authClient = createAuthClient({ plugins: [creemClient()], }); ``` The plugin infers endpoint inputs, successful responses, and Creem session fields through Better Auth. The `createCreemAuthClient` wrapper remains exported for compatibility but is deprecated. Every method returns the Better Auth `{ data, error }` result shape. Handle `error` before using `data`. A failed request returns `data: null` and an error containing `message`, `status`, and `statusText`; successful response types do not contain an error alternative. ```typescript theme={null} const { data, error } = await authClient.creem.createPortal(); if (error) { console.error(error.status, error.message); } else if (data.url) { window.location.assign(data.url); } ``` Creem session fields are inferred when persistence is enabled. If the server uses `persistSubscriptions: false`, configure `creemClient({ persistSubscriptions: false })` too. The client option controls inference; it does not change the server configuration. ## Create a checkout Navigation is manual by default (`redirect: false`). Set `redirect: true` to let Better Auth redirect to the checkout URL automatically. ```typescript theme={null} const { data, error } = await authClient.creem.createCheckout({ productId: "prod_...", units: 1, successUrl: "/billing/success", discountCode: "LAUNCH20", metadata: { plan: "pro" }, }); if (!error && data?.url) { window.location.assign(data.url); } ``` | Input | Required | Description | | - | - | - | | `productId` | Yes | Product to purchase. | | `requestId` | No | Idempotency key for retrying checkout creation. | | `units` | No | Positive unit count; defaults to `1`. | | `discountCode` | No | Active Creem discount code. | | `customer.email` | No | Defaults to the signed-in user's email. | | `customFields` | No | Up to three text or checkbox fields shown during checkout. | | `successUrl` | No | Overrides `defaultSuccessUrl` for this checkout. | | `redirect` | No | Redirect automatically when `true`; defaults to `false`. | | `metadata` | No | Application metadata. The signed-in user ID is added as `referenceId`. | > [!NOTE] > > `customField` is a deprecated alias for `customFields`. New code should use `customFields`. ## Open the customer portal ```typescript theme={null} const { data, error } = await authClient.creem.createPortal(); if (!error && data?.url) { window.location.assign(data.url); } ``` To redirect automatically, use `await authClient.creem.createPortal({ redirect: true })`. The default is `redirect: false`, which returns the URL for manual navigation. With persistence enabled, omit `customerId` so the plugin uses the current user's stored `creemCustomerId`. The endpoint also accepts an explicit customer ID, but it does not verify that the ID belongs to the signed-in user. Do not pass a value obtained from untrusted client input. ## Check access `hasAccessGranted()` reads the signed-in user's persisted subscriptions. It grants access for `active`, `trialing`, or `paid` records. A `scheduled_cancel`, `past_due`, or `unpaid` subscription also retains access while its `periodEnd` is still in the future, so customers can use time they have already paid for. A `canceled` subscription no longer grants access. ```typescript theme={null} const { data, error } = await authClient.creem.hasAccessGranted(); if (!error && data?.hasAccessGranted) { console.log("Access granted", data.subscription); } ``` On success, `data.hasAccessGranted` is a boolean. A signed-out request returns an error with status `401`, disabled persistence returns `400`, and a failed database check returns `500`. These failures return `data: null`, so check `error` before reading the access result. Do not grant access when the check fails. ## Cancel a subscription ```typescript theme={null} const { data, error } = await authClient.creem.cancelSubscription({ id: "sub_...", }); ``` The published client type requires the subscription ID. The endpoint does not consistently verify ownership of caller-supplied IDs, so derive the ID from billing state already authorized for the signed-in user. Use the returned `success` and `message` fields to update the interface. ## Retrieve a subscription ```typescript theme={null} const { data, error } = await authClient.creem.retrieveSubscription({ id: "sub_...", }); ``` The result includes the subscription status, customer, product, billing dates, and metadata. Customer and product values can be IDs or expanded objects; narrow their types before reading object properties. Dates returned over HTTP are serialized values, so convert them with `new Date()` when you need date methods instead of assuming a JavaScript `Date` instance. As with cancellation, do not accept the subscription ID from an untrusted caller without checking that it belongs to the signed-in account. ## Search transactions ```typescript theme={null} const { data, error } = await authClient.creem.searchTransactions({ productId: "prod_...", pageNumber: 1, pageSize: 20, }); for (const transaction of data?.items ?? []) { console.log(transaction.id, transaction.status, transaction.amount); } ``` The response contains `data.items` and `data.pagination`; it does not expose the SDK page iterator. Available filters are `customerId`, `productId`, `orderId`, `pageNumber`, and `pageSize`. When `customerId` is omitted, the endpoint uses the customer associated with the signed-in user. Prefer that default: an explicit customer ID is not checked against the current user. ## Type exports Client input and result types can be imported from the package root or client entry point: ```typescript theme={null} import type { CancelSubscriptionInput, CreateCheckoutInput, CreatePortalInput, HasAccessGrantedResponse, RetrieveSubscriptionInput, SearchTransactionsInput, } from "@creem_io/better-auth"; ``` # Configuration Source: https://docs.creem.io/code/sdks/better-auth/configuration Configure the Creem Better Auth server and client plugins, persistence, and database schema. ## Server options Pass these options to `creem()` in your Better Auth configuration: | Option | Type | Default | Description | | - | - | - | - | | `apiKey` | `string` | Required | Creem API key for the selected environment. Keep it on the server. | | `webhookSecret` | `string` | — | Signing secret used to verify Creem webhooks. The webhook endpoint is omitted when this is not set. | | `testMode` | `boolean` | `false` | Uses `https://test-api.creem.io` instead of the production API. | | `defaultSuccessUrl` | `string` | — | Checkout return URL used when a request does not provide `successUrl`. Relative and absolute URLs are supported. | | `persistSubscriptions` | `boolean` | `true` | Adds the plugin schema and synchronizes customer and subscription data from webhooks. | | `schema` | `CreemSchemaOverrides` | — | Physical model and column name overrides for existing plugin fields. | Webhook callback options are covered in [Webhooks and access](/code/sdks/better-auth/webhooks). ```typescript lib/auth.ts theme={null} import { creem } from "@creem_io/better-auth"; import { betterAuth } from "better-auth"; export const auth = betterAuth({ database: { // Your database configuration }, plugins: [ creem({ apiKey: process.env.CREEM_API_KEY!, webhookSecret: process.env.CREEM_WEBHOOK_SECRET!, testMode: process.env.NODE_ENV !== "production", defaultSuccessUrl: "/billing/success", persistSubscriptions: true, }), ], }); ``` > [!WARNING] > > `testMode` defaults to `false`. Do not pair a test API key with production mode or a production > API key with test mode. ## Persistence mode Persistence is enabled unless you explicitly set `persistSubscriptions: false`. The plugin then: * adds its models and fields to the Better Auth schema; * associates a Creem customer ID with the signed-in user; * writes subscription state received through verified webhooks; * checks local subscription records in `hasAccessGranted()`; * records whether a user has already received a trial. After enabling persistence or upgrading to a version that changes the schema, use the command for your database workflow. The built-in Kysely adapter can apply the migration directly: ```bash theme={null} npx @better-auth/cli migrate ``` For Prisma, Drizzle, or another ORM-managed schema, generate the schema and then apply it with the ORM's migration tooling: ```bash theme={null} npx @better-auth/cli generate ``` ### Added models and fields The `creem_subscription` model contains: | Field | Type | Notes | | - | - | - | | `productId` | string | Creem product ID | | `referenceId` | string | Better Auth user ID or another application reference | | `creemCustomerId` | string, optional | Creem customer ID | | `creemSubscriptionId` | string, optional | Creem subscription ID | | `creemOrderId` | string, optional | Creem order ID | | `status` | string | Defaults to `pending` | | `periodStart` | date, optional | Current billing period start | | `periodEnd` | date, optional | Current billing period end | | `cancelAtPeriodEnd` | boolean, optional | Synchronized from status by subscription webhooks and checkout writes: `true` for `scheduled_cancel`, otherwise `false` | Existing records are not automatically backfilled. `cancelAtPeriodEnd` may remain unset or stale until a subsequent event updates the record. Access checks use `status` and `periodEnd`. The plugin extends the Better Auth `user` model with: | Field | Type | Notes | | - | - | - | | `creemCustomerId` | string, optional | Customer used for portal and customer-scoped requests | | `hadTrial` | boolean, optional | Defaults to `false`; set after the user enters a trial | ### Without persistence Set `persistSubscriptions: false` when your application owns subscription storage or does not need local billing state: ```typescript theme={null} creem({ apiKey: process.env.CREEM_API_KEY!, webhookSecret: process.env.CREEM_WEBHOOK_SECRET!, persistSubscriptions: false, }); ``` No plugin schema is added: neither subscription models nor Creem user fields are registered. No plugin customer, trial, or subscription data is written. `hasAccessGranted()` cannot determine access in this mode, so implement access checks in your own data layer. Other endpoints can still call Creem, provided they receive or can resolve the required customer or subscription identifier. Mirror this option in your client configuration so session types do not promise fields that the server has not registered: ```typescript theme={null} const authClient = createAuthClient({ plugins: [creemClient({ persistSubscriptions: false })], }); ``` ### Custom model and column names With persistence enabled, `schema` maps existing logical names to physical database names: ```typescript theme={null} creem({ apiKey: process.env.CREEM_API_KEY!, schema: { creem_subscription: { modelName: "billing_subscription", fields: { referenceId: "user_id" }, }, user: { fields: { creemCustomerId: "creem_customer_id" }, }, }, }); ``` Field mappings are strings, not field definition objects. They rename existing models and columns; they do not add models, add fields, or change their types. The logical names in session and endpoint types stay the same. Overrides are ignored when persistence is disabled. Each server plugin instance has its own schema, so overrides do not affect other instances. ## Client options The standard Better Auth client infers the Creem endpoints from `creemClient()`: ```typescript lib/auth-client.ts theme={null} import { creemClient } from "@creem_io/better-auth/client"; import { createAuthClient } from "better-auth/react"; export const authClient = createAuthClient({ baseURL: process.env.NEXT_PUBLIC_APP_URL, plugins: [creemClient()], }); ``` `baseURL` is optional when the client calls the same origin. Use Better Auth's client import for your framework, such as `better-auth/react` for React. The standard client infers Creem endpoint inputs and successful responses. With persistence enabled (the default), it also infers `session.user.creemCustomerId` and `session.user.hadTrial`. The client option `persistSubscriptions` must match the server option; it controls types only and cannot enable server persistence. `createCreemAuthClient` remains exported but is deprecated. Replace it with your framework's standard `createAuthClient` while keeping `creemClient()` in the plugins array. See the [2.0 migration guide](/code/sdks/better-auth/migration) for response handling changes. # Migration Source: https://docs.creem.io/code/sdks/better-auth/migration Upgrade the Creem Better Auth plugin from 1.x to 2.0: redirects, native clients, errors, persistence, and cancellation access. Use this guide when upgrading an existing `@creem_io/better-auth` integration. For a new integration, start with the [quickstart](/code/sdks/better-auth/quickstart). ## Upgrading from 1.x Version 2.0 changes checkout navigation and endpoint error handling, improves native client types, and distinguishes scheduled cancellation from final cancellation in webhook callbacks and persisted access checks. Review the client, server, and webhook changes below before deploying. No database schema migration is required for unchanged default persistence settings. If you use custom schema mappings, review the mapping changes below against your existing database. ### Upgrade Better Auth alongside the plugin Version 2.0 requires Better Auth `^1.5.6`. The native inferred endpoint declarations depend on Better Auth types that are not available at the previous minimum of 1.3.34. Upgrade both packages together, including in separate server and client applications: ```bash theme={null} pnpm add @creem_io/better-auth@^2 better-auth@^1.5.6 ``` ### Update checkout and portal navigation Checkout and portal methods now default to `redirect: false`. Existing calls that relied on automatic navigation must explicitly opt in: ```typescript theme={null} await authClient.creem.createCheckout({ productId: "prod_...", redirect: true, }); await authClient.creem.createPortal({ redirect: true }); ``` For manual navigation, omit `redirect` or set it to `false`, handle `error`, and navigate using `data.url`: ```typescript theme={null} const { data, error } = await authClient.creem.createCheckout({ productId: "prod_...", }); if (error) { console.error(error.status, error.message); } else if (data.url) { window.location.assign(data.url); } ``` ### Migrate to the native client `createCreemAuthClient` is deprecated but remains exported. Replace it with the standard Better Auth client for your framework and keep the Creem client plugin: ```typescript theme={null} import { createAuthClient } from "better-auth/react"; import { creemClient } from "@creem_io/better-auth/client"; export const authClient = createAuthClient({ plugins: [creemClient()], }); ``` The native client infers inputs and successful responses for all six Creem methods, plus `session.user.creemCustomerId` and `session.user.hadTrial` when persistence is enabled. Error payloads no longer appear as alternatives inside the successful `data` type, so checks such as `"url" in data` are unnecessary after handling `error`. Native types follow the endpoint's actual SDK response. Customer or product values can be IDs or expanded objects; narrow them before reading properties. Date values received over HTTP are serialized, not JavaScript `Date` instances. For example: ```typescript theme={null} const { data, error } = await authClient.creem.retrieveSubscription({ id: "sub_...", }); if (!error && data) { const productId = typeof data.product === "string" ? data.product : data.product.id; console.log(productId); } ``` ### Update transaction response paths The Better Auth `searchTransactions()` endpoint now returns the transaction page directly as `{ items, pagination }`, matching the documented client contract. If you previously used the native client or raw endpoint's SDK iterator envelope, change `data.result.items` to `data.items` and `data.result.pagination` to `data.pagination`. The HTTP endpoint does not expose iterator methods. The standalone helper from `@creem_io/better-auth/server` is unchanged. ### Update endpoint error handling Failures from `createCheckout`, `createPortal`, `cancelSubscription`, `retrieveSubscription`, `searchTransactions`, and `hasAccessGranted` now use Better Auth's `APIError` mechanism. Existing HTTP status codes are preserved, but the error contract changes: | Caller | 2.0 failure handling | | - | - | | `authClient.creem.*` | Handle `{ data: null, error }`; read `error.message` and `error.status`. | | Direct `auth.api.*` call | Catch a thrown `APIError` from `better-auth/api`. | | Raw HTTP or `auth.api.*({ asResponse: true })` | Check the response status and read `message` from error JSON, replacing the old `error` field. | Do not check `data.error` or assume a failed direct server call resolves to an error object. `hasAccessGranted()` returns `data.hasAccessGranted` as a boolean on success. Signed-out requests (`401`), disabled persistence (`400`), and failed checks (`500`) use the error path with `data: null` instead of an indeterminate access result. Treat an error as a failed check, not authorization. See the [Server API](/code/sdks/better-auth/server#call-better-auth-endpoints-on-the-server) for a `try`/`catch` example. Helpers imported from `@creem_io/better-auth/server` are separate from these Better Auth endpoints and retain their own behavior. ### Match persistence configuration and review schema mappings The full persistence opt-out remains supported. A server configured with `persistSubscriptions: false` registers neither subscription models nor Creem user fields and performs no plugin customer, trial, or subscription writes. Mirror that setting in the client so its session types match the server: ```typescript theme={null} const authClient = createAuthClient({ plugins: [creemClient({ persistSubscriptions: false })], }); ``` This client option controls inference only; it does not change the server's behavior. Leave both plugins at their defaults when using persistence. If you store billing data yourself, read it through your own typed data layer instead of expecting Creem fields on the plugin session. The `schema` option now correctly types physical name mappings for existing plugin models and fields. Field overrides are column-name strings, not Better Auth field definition objects: ```typescript theme={null} creem({ apiKey: process.env.CREEM_API_KEY!, schema: { creem_subscription: { modelName: "billing_subscription", fields: { referenceId: "user_id" }, }, user: { fields: { creemCustomerId: "creem_customer_id" } }, }, }); ``` Update any object-shaped field overrides to string mappings. This option does not add models or fields or change their logical types, and it is ignored when persistence is disabled. Each plugin instance now applies overrides independently. If you change physical names during the upgrade, check your generated ORM schema and apply the corresponding database migration before deployment. ### Cancellation and access changes | Behavior | 1.x | 2.0 | | - | - | - | | `subscription.scheduled_cancel` webhook | Rejected with HTTP 400 | Accepted; persists the scheduled status and calls the optional `onSubscriptionScheduledCancel` callback | | Access from a stored `scheduled_cancel` subscription | Does not grant access | Grants access only before its stored `periodEnd` | | Access from a stored `canceled` subscription | Grants access until its stored `periodEnd` | Does not grant access | | `subscription.canceled` callbacks | Calls `onSubscriptionCanceled` | Calls `onRevokeAccess` with `subscription_canceled`, then `onSubscriptionCanceled` | Access behavior in this table refers to `hasAccessGranted()` with persistence enabled. The existing `past_due` and `unpaid` period-end grace behavior is unchanged. The direct [server helpers](/code/sdks/better-auth/server) retain their documented active-status scope. ### Update your callbacks Add `subscription_canceled` to any exhaustive switches or mappings over `RevokeAccessReason` or `AccessChangeReason`. If your `onRevokeAccess` handler already handles every reason the same way, it will now also run for final cancellation. If you currently revoke access in `onSubscriptionCanceled`, move that logic into `onRevokeAccess`, or ensure that calling both handlers has the same effect as calling one. Keep handlers idempotent because webhooks can be delivered more than once. These callback changes also apply when `persistSubscriptions: false`. Scheduling cancellation does not invoke `onGrantAccess` or `onRevokeAccess`. If you manage entitlements outside the plugin database, use `onSubscriptionScheduledCancel` to store the period end and enforce it in your own access checks. See [Webhooks and access](/code/sdks/better-auth/webhooks) for callback examples and retry behavior. ### Review existing records and entitlements The new access policy applies to existing records as soon as you deploy 2.0. Upgrading does not replay webhooks or invoke `onRevokeAccess` for records already stored as `canceled`. Before deploying: 1. Review local canceled records that currently grant access and compare them with the subscription's current state in Creem. Correct stale local state from that source; do not relabel a canceled subscription as scheduled solely because its stored period end is in the future. 2. If you store entitlements separately, reconcile them with the current subscription state. Do not rely on a new revoke callback arriving solely because you upgraded the package. 3. Check any custom use of `cancelAtPeriodEnd`. Existing flags are not automatically backfilled; subsequent subscription webhooks and checkout writes synchronize the flag. The plugin's access checks use `status` and `periodEnd`. > [!NOTE] > > An existing canceled record can still have a future `periodEnd`. In this edge case, upgrading > stops that record from granting access immediately, rather than waiting for the stored date. ### Install and verify After updating your handlers and reviewing existing state, install the new major version: ```bash theme={null} pnpm add @creem_io/better-auth@^2 better-auth@^1.5.6 ``` Run your application's typecheck to catch native response types, persistence options, schema mappings, and exhaustive reason checks that need updating. Verify manual and automatic checkout/portal navigation, client error handling, and any direct `auth.api` error handling. In test mode, verify that scheduled cancellation preserves access before the period end, that access ends at the period boundary, and that final cancellation invokes your revoke logic without duplicate side effects. If you manage entitlements separately, verify those access checks too. # Quickstart Source: https://docs.creem.io/code/sdks/better-auth/quickstart Install the Creem Better Auth plugin and create an authenticated checkout. This guide uses subscription persistence, the recommended setup for most applications. It stores Creem customer and subscription identifiers in your Better Auth database and keeps them current through webhooks. ## 1. Install the plugin ```bash npm theme={null} npm install @creem_io/better-auth better-auth@^1.5.6 ``` ```bash pnpm theme={null} pnpm add @creem_io/better-auth better-auth@^1.5.6 ``` ```bash yarn theme={null} yarn add @creem_io/better-auth better-auth@^1.5.6 ``` ```bash bun theme={null} bun add @creem_io/better-auth better-auth@^1.5.6 ``` Better Auth `^1.5.6` is required for native endpoint type inference. The Creem TypeScript SDK is included as a dependency of the plugin. ## 2. Configure the server plugin Add your test API key and a webhook signing secret to the server environment: ```bash .env theme={null} CREEM_API_KEY=creem_test_... CREEM_WEBHOOK_SECRET=whsec_... ``` Register the plugin in your Better Auth configuration: ```typescript lib/auth.ts theme={null} import { creem } from "@creem_io/better-auth"; import { betterAuth } from "better-auth"; export const auth = betterAuth({ database: { // Your Better Auth database configuration }, plugins: [ creem({ apiKey: process.env.CREEM_API_KEY!, webhookSecret: process.env.CREEM_WEBHOOK_SECRET!, testMode: true, defaultSuccessUrl: "/billing/success", persistSubscriptions: true, }), ], }); ``` The webhook endpoint is registered only when `webhookSecret` is present. ## 3. Generate the database schema The plugin adds `creemCustomerId` and `hadTrial` to the Better Auth user model and creates a `creem_subscription` model. With Better Auth's built-in Kysely adapter, apply the schema directly: ```bash theme={null} npx @better-auth/cli migrate ``` When Prisma, Drizzle, or another ORM owns your schema, generate the schema instead and apply it with that ORM's migration tooling: ```bash theme={null} npx @better-auth/cli generate ``` See the [Better Auth database documentation](https://www.better-auth.com/docs/concepts/database) when your adapter requires manual migration steps. ## 4. Configure the client plugin ```typescript lib/auth-client.ts theme={null} import { creemClient } from "@creem_io/better-auth/client"; import { createAuthClient } from "better-auth/react"; export const authClient = createAuthClient({ plugins: [creemClient()], }); ``` The client plugin infers endpoint inputs and `session.user.creemCustomerId` through Better Auth. If client and server are separate applications, install `@creem_io/better-auth` in both. ## 5. Create a checkout The signed-in user's email is used when no customer is supplied. Their Better Auth user ID is added to checkout metadata as `referenceId`. Navigation is manual by default; pass `redirect: true` to let Better Auth navigate automatically. ```tsx app/pricing/subscribe-button.tsx theme={null} "use client"; import { authClient } from "@/lib/auth-client"; export function SubscribeButton({ productId }: { productId: string }) { const subscribe = async () => { const { data, error } = await authClient.creem.createCheckout({ productId, successUrl: "/billing/success", }); if (error) { throw new Error(error.message); } if (data?.url) { window.location.assign(data.url); } }; return ; } ``` ## 6. Register the webhook In the Creem dashboard, point a test-mode webhook at: ```text theme={null} https://your-domain.com/api/auth/creem/webhook ``` `/api/auth` is Better Auth's default base path. Use your configured base path if you changed it. For local development, expose the application over HTTPS with a tunnel and register that URL. Once Creem delivers subscription events, the plugin updates the local subscription record. You can also add [access callbacks](/code/sdks/better-auth/webhooks) for application-specific provisioning. ## Continue > [card] [Configuration](/code/sdks/better-auth/configuration) > > Review every plugin option and persistence behavior. > [card] [Client API](/code/sdks/better-auth/client) > > Add the portal, cancellation, access checks, and transaction history. # Server API Source: https://docs.creem.io/code/sdks/better-auth/server Call Creem directly from Server Actions, route handlers, and other trusted server code. The `@creem_io/better-auth/server` entry point provides direct Creem helpers for code that does not need to go through a Better Auth endpoint. > [!WARNING] > > These helpers use your secret API key and must run on the server. They do not automatically infer > the signed-in user. Authenticate the request and authorize every customer or subscription ID > before calling them. ## Configure the environment ```typescript theme={null} const creemConfig = { apiKey: process.env.CREEM_API_KEY!, testMode: process.env.NODE_ENV !== "production", }; ``` ## Create a checkout Unlike the client endpoint, the direct helper requires customer information because it has no Better Auth session to inspect. ```typescript theme={null} "use server"; import { createCheckout } from "@creem_io/better-auth/server"; import { redirect } from "next/navigation"; export async function startCheckout(productId: string) { const user = await requireUser(); const { url } = await createCheckout(creemConfig, { productId, customer: { email: user.email }, successUrl: "/billing/success", metadata: { referenceId: user.id }, skipTrial: user.hadTrial, }); redirect(url); } ``` ## Open the customer portal ```typescript theme={null} import { createPortal } from "@creem_io/better-auth/server"; const user = await requireUser(); const { url } = await createPortal(creemConfig, user.creemCustomerId); ``` Verify that the stored customer ID belongs to the authenticated account. ## Manage subscriptions ```typescript theme={null} import { cancelSubscription, retrieveSubscription } from "@creem_io/better-auth/server"; await requireSubscriptionOwner(subscriptionId); const subscription = await retrieveSubscription(creemConfig, subscriptionId); const result = await cancelSubscription(creemConfig, subscriptionId); ``` ## Search transactions ```typescript theme={null} import { searchTransactions } from "@creem_io/better-auth/server"; const user = await requireUser(); const result = await searchTransactions(creemConfig, { customerId: user.creemCustomerId, pageNumber: 1, pageSize: 20, }); ``` ## Create a raw SDK client Use `createCreemClient()` when the helper functions do not cover the API operation you need: ```typescript theme={null} import { createCreemClient } from "@creem_io/better-auth/server"; const creem = createCreemClient(creemConfig); const subscription = await creem.subscriptions.get("sub_..."); ``` For general SDK coverage, see the [TypeScript SDK documentation](/code/sdks/typescript). ## Utility functions The server entry point also exports: | Function | Purpose | | - | - | | `isActiveSubscription(status)` | Returns `true` for `active`, `trialing`, or `paid`. | | `formatCreemDate(timestamp)` | Converts a Unix timestamp in seconds to a JavaScript `Date`. | | `getDaysUntilRenewal(timestamp)` | Calculates whole days until a Unix timestamp. | | `validateWebhookSignature(payload, signature, secret)` | Validates a `creem-signature` header against the raw request body. | `checkSubscriptionAccess()` and `getActiveSubscriptions()` are also exported, but their database mode expects a raw query-builder interface that is not compatible with every Better Auth adapter. Prefer the authenticated `hasAccessGranted()` endpoint or query your own database through its supported adapter API. These server helpers only recognize `active`, `trialing`, and `paid`; they do not evaluate scheduled cancellation deadlines or payment grace periods. Use [`hasAccessGranted()`](/code/sdks/better-auth/client#check-access) for those access decisions. ## Call Better Auth endpoints on the server Calls through `auth.api` use the same endpoints as the browser client. Pass the current request's headers for session authentication. Unlike browser client results, failed direct calls throw a Better Auth `APIError`: ```typescript theme={null} import { APIError } from "better-auth/api"; import { auth } from "@/lib/auth"; try { const portal = await auth.api.createPortal({ headers: request.headers, body: { redirect: false }, }); console.log(portal.url); } catch (error) { if (error instanceof APIError) { console.error(error.status, error.body?.message); } else { throw error; } } ``` Pass `asResponse: true` when you need an HTTP `Response` instead. Check `response.ok` and `response.status`; error JSON contains `message`, replacing the previous `error` field. This applies to checkout, portal, cancel, retrieve, transaction search, and access endpoints. The direct helpers from `@creem_io/better-auth/server` keep their separate behavior. # Webhooks and access Source: https://docs.creem.io/code/sdks/better-auth/webhooks Verify Creem webhooks, synchronize subscription state, and provision application access. When `webhookSecret` is configured, the plugin registers a verified webhook handler at: ```text theme={null} /api/auth/creem/webhook ``` `/api/auth` is Better Auth's default base path. The plugin route itself is `/creem/webhook`. Add the full public URL in the Creem dashboard. Test-mode webhooks and production webhooks have separate configuration and signing secrets. ## Persist subscription state With `persistSubscriptions: true`, verified webhook events update the plugin's local customer and subscription fields. Your application can query that state through `hasAccessGranted()` without making a Creem API request on each page load. Webhook delivery is asynchronous. Treat the success redirect as confirmation that checkout completed in the browser, not as the source of truth for granting durable access. ## Grant and revoke access Use the high-level callbacks for application-specific provisioning: ```typescript lib/auth.ts theme={null} creem({ apiKey: process.env.CREEM_API_KEY!, webhookSecret: process.env.CREEM_WEBHOOK_SECRET!, persistSubscriptions: true, onGrantAccess: async ({ reason, customer, product, metadata }) => { const userId = metadata?.referenceId; if (typeof userId !== "string") return; await setPlanAccess({ userId, productId: product.id, enabled: true, reason, }); }, onRevokeAccess: async ({ reason, product, metadata }) => { const userId = metadata?.referenceId; if (typeof userId !== "string") return; await setPlanAccess({ userId, productId: product.id, enabled: false, reason, }); }, }); ``` `onGrantAccess` runs with one of these reasons: * `subscription_active` * `subscription_trialing` * `subscription_paid` `onRevokeAccess` runs with: * `subscription_paused` * `subscription_expired` * `subscription_canceled` `subscription.scheduled_cancel` preserves access until `current_period_end_date`. With persistence enabled, the plugin stores `status: "scheduled_cancel"` and `cancelAtPeriodEnd: true`; `hasAccessGranted()` returns false once that period ends, even if the final webhook is delayed. This event calls `onSubscriptionScheduledCancel` without calling `onGrantAccess` or `onRevokeAccess`. `subscription.canceled` means the subscription has ended. It calls both `onRevokeAccess` and `onSubscriptionCanceled`, and the access check denies that subscription. When cancellation is undone or finalized, subsequent subscription events synchronize the status and clear `cancelAtPeriodEnd` when the status is no longer `scheduled_cancel`. With persistence enabled, delayed scheduled-cancellation updates cannot change a stored `canceled` or `expired` subscription back to `scheduled_cancel`. Ignored `subscription.scheduled_cancel` events do not invoke `onSubscriptionScheduledCancel`. The general `onSubscriptionUpdate` callback still receives `subscription.update` events, including those whose scheduled status was ignored by persistence. If you manage access outside the plugin database, store the scheduled period end and enforce it in your own access checks. > [!WARNING] > > Webhooks can be retried or delivered more than once. Make every callback idempotent: applying the > same event twice must produce the same final state. ## Event-specific callbacks Use event-specific callbacks when you need more than the high-level access decision: | Callback | Event | | - | - | | `onCheckoutCompleted` | `checkout.completed` | | `onRefundCreated` | `refund.created` | | `onDisputeCreated` | `dispute.created` | | `onSubscriptionActive` | `subscription.active` | | `onSubscriptionTrialing` | `subscription.trialing` | | `onSubscriptionCanceled` | `subscription.canceled` | | `onSubscriptionScheduledCancel` | `subscription.scheduled_cancel` | | `onSubscriptionPaid` | `subscription.paid` | | `onSubscriptionExpired` | `subscription.expired` | | `onSubscriptionUnpaid` | `subscription.unpaid` | | `onSubscriptionUpdate` | `subscription.update` | | `onSubscriptionPastDue` | `subscription.past_due` | | `onSubscriptionPaused` | `subscription.paused` | Each callback receives normalized event data followed by the Better Auth endpoint context: ```typescript theme={null} creem({ apiKey: process.env.CREEM_API_KEY!, webhookSecret: process.env.CREEM_WEBHOOK_SECRET!, onSubscriptionPastDue: async (subscription, betterAuthContext) => { console.warn("Payment needs attention", subscription.id); }, }); ``` ## Trial tracking Persistence adds `hadTrial` to the user model. When a user enters a trial, the plugin records it and can tell Creem to skip later trials for that user. This protects the Better Auth account boundary; it is not a substitute for any additional identity or abuse controls your product requires. ## Custom webhook handlers Most applications should use the plugin route. If you own a separate webhook route, verify the raw body before parsing it: ```typescript theme={null} import { validateWebhookSignature } from "@creem_io/better-auth/server"; export async function POST(request: Request) { const payload = await request.text(); const signature = request.headers.get("creem-signature"); const valid = await validateWebhookSignature( payload, signature, process.env.CREEM_WEBHOOK_SECRET!, ); if (!valid) { return new Response("Invalid signature", { status: 401 }); } const event = JSON.parse(payload); // Process the verified event idempotently. return new Response(null, { status: 204 }); } ``` Do not configure both the plugin route and a custom route for the same webhook unless duplicate processing is intentional. # Advanced Source: https://docs.creem.io/code/sdks/convex/advanced Custom auth and RBAC, webhook middleware, checkout gates, internationalization, and custom billing models for the Creem Convex component. Task guides for the parts you reach for once the basics work. For the ideas behind them, see [Concepts](/code/sdks/convex/concepts). > [accordion] Where this code goes, and what it assumes > > Examples on this page are fragments. They render inside the provider you mounted > in the [Quickstart](/code/sdks/convex/quickstart): > > ```svelte theme={null} > > > > ``` > > If something below does not work, one of these is usually missing. Each links > straight to the step that sets it up. > > * [Component registered](/code/sdks/convex/quickstart#register-component) — `app.use(creem)` in `convex/convex.config.ts` > * [Secrets set](/code/sdks/convex/quickstart#set-secrets) — `CREEM_API_KEY` and `CREEM_WEBHOOK_SECRET` in Convex env > * [Billing API exported](/code/sdks/convex/quickstart#export-billing-api) — `convex/billing.ts` calling `creem.api({ resolve })` > * [Webhook registered](/code/sdks/convex/quickstart#register-webhook) — `creem.registerRoutes(http)` in `convex/http.ts` > * [Products created](/code/sdks/convex/quickstart#create-products) — one Creem product per plan and billing cycle > * [Products synced](/code/sdks/convex/quickstart#sync-products) — `npx convex run billing:syncBillingProducts` > * [Styles imported](/code/sdks/convex/quickstart#import-styles) — `@creem_io/convex/styles` after the Tailwind import > * [Catalog defined](/code/sdks/convex/quickstart#define-plans) — `billingCatalog` mapping plan IDs to product IDs > * [Provider mounted](/code/sdks/convex/quickstart#render-pricing-page) — `` around your billing UI ## Custom auth and RBAC Billing and identity are separate domains that meet in one place: the `resolve` callback. Your auth layer answers *who is calling and what may they act on*. This component answers *what that billing entity owns and may change*. `resolve` is the handover between the two. On the billing side, the generated API enforces its own boundary: it derives the entity from `resolve`, scopes customer data to that entity, and verifies explicitly selected subscriptions before reading or changing them. It never takes an entity from client input. On the identity side, sessions, roles, and org membership stay with whatever auth you already use. Convex Auth, Clerk, WorkOS, or your own tables all work the same way here, because the component only ever sees the result. ### Quick start `creem.api({ resolve })` generates ready-to-export Convex functions. Each one calls your `resolve` callback to authenticate and determine the `entityId`. For team billing, verify membership and the required billing role before returning an organization ID, since that check belongs to the identity domain. This is what the [Quickstart](/code/sdks/convex/quickstart) uses. ### Full control Call the resource namespaces (`creem.subscriptions.*`, `creem.checkouts.*`, `creem.customers.*`, `creem.orders.*`, `creem.products.*`) inside your own Convex functions and handle auth, entity resolution, and permission checks there. The library exports **shared arg validators** matching exactly what the widgets send, so your custom functions stay drop-in compatible: | Export | Used by | | - | - | | `checkoutCreateArgs` | ``, `` | | `subscriptionUpdateArgs` | `` (plan switch, unit update) | | `subscriptionCancelArgs` | `` (cancel button) | | `subscriptionResumeArgs` | `` (resume button) | | `subscriptionPauseArgs` | `` (pause button) | | `appPlanActivateArgs` | `` (app-owned plan cards) | | `transactionsSearchArgs` | `` | | `customersBillingEmailArgs` | `` (load) | | `customersUpdateBillingEmailArgs` | `` (save button) | `subscriptionUpdateArgs` carries a `kind` discriminator for the three mutually exclusive update targets. The exported `SubscriptionUpdateArgs` **type** is a true discriminated union: ```ts theme={null} { kind: "plan", productId, updateBehavior?: "proration-…" | "period-end" } { kind: "units", units, updateBehavior?: "proration-…" | "period-end" } { kind: "app-plan", appPlanId, updateBehavior?: "period-end" | "immediate" } ``` So `"immediate"` on a paid switch, or two targets at once, does not compile. Convex requires top-level args to be a flat object, which means the wire validator itself is permissive. The generated mutation calls `parseSubscriptionUpdateArgs` to re-check the same rules for calls arriving over the wire. Use it in your own wrappers too: ```ts theme={null} export const subscriptionsUpdate = mutation({ args: subscriptionUpdateArgs, handler: async (ctx, args) => { const auth = await resolveAuth(ctx); await creem.subscriptions.update(ctx, { entityId: auth.entityId, ...parseSubscriptionUpdateArgs(args), }); }, }); ``` Admin-only billing, for example: ```ts title="convex/billing.ts" theme={null} import { Creem, checkoutCreateArgs, customersUpdateBillingEmailArgs, subscriptionCancelArgs, } from "@creem_io/convex"; import { ConvexError } from "convex/values"; import { action, mutation } from "./_generated/server"; import { api, components } from "./_generated/api"; const creem = new Creem(components.creem); async function resolveAuth(ctx) { const session = await ctx.runQuery(api.auth.getSession); if (!session) throw new ConvexError("Not authenticated"); const org = await ctx.runQuery(api.orgs.getActiveOrg); return { userId: session.userId, email: session.user.email, entityId: org?._id ?? session.userId, role: session.user.role, }; } export const checkoutsCreate = action({ args: checkoutCreateArgs, handler: async (ctx, args) => { const auth = await resolveAuth(ctx); if (auth.role !== "admin") throw new ConvexError("Forbidden"); return await creem.checkouts.create(ctx, { entityId: auth.entityId, userId: auth.userId, email: auth.email, ...args, }); }, }); export const subscriptionsCancel = mutation({ args: subscriptionCancelArgs, handler: async (ctx, args) => { const auth = await resolveAuth(ctx); if (auth.role !== "admin") throw new ConvexError("Forbidden"); await creem.subscriptions.cancel(ctx, { entityId: auth.entityId, ...args }); }, }); ``` The same pattern restricts who may change where invoices go: ```ts title="convex/billing.ts" theme={null} export const customersUpdateBillingEmail = action({ args: customersUpdateBillingEmailArgs, handler: async (ctx, args) => { const auth = await resolveAuth(ctx); if (auth.role !== "admin") throw new ConvexError("Forbidden"); // The form sends the entity it shows; never save into a different one. if (args.expectedEntityId !== auth.entityId) { return { status: "entity-changed" as const }; } return await creem.customers.updateBillingEmail(ctx, { entityId: auth.entityId, email: args.email, }); }, }); ``` Pair this with provider-level `permissions` so non-admins see disabled buttons instead of server errors. The server check above is what actually enforces the rule. Credit grants and spending are deliberately not part of `ConnectedBillingApi`. Expose an app-specific backend action for a business operation such as `generateImage`, and let that action call `creem.credits.creditForEntity` or `creem.credits.debitForEntity` with server-controlled amounts, references, and idempotency keys. ### Resolver plan overrides The resolver may return two optional overrides, for apps that own their plan assignment rather than letting the component own it: | Field | When to return it | | - | - | | `activePlanId` | Your app, rather than the component, decides the entity's current app-owned plan (free, trial, custom). Feeds `uiModel.activePlanId` and eligibility checks. | | `activeFreePlanId` | Legacy narrower form of the same override. Prefer `activePlanId`. `undefined` keeps the default "first catalog free plan"; `null` means no free plan. | Omit both and the component reads the active plan from its own app-plan assignment rows. ## Webhook event middleware `registerRoutes` accepts an `events` map for app-specific logic. Your handlers run after the component's built-in processing, which upserts customers, subscriptions, and orders. The `ctx` is a Convex **action** context. It has no `ctx.db`, so reach your own tables through `ctx.runQuery` and `ctx.runMutation`, and use `ctx.runAction` for third-party calls: ```ts theme={null} creem.registerRoutes(http, { path: "/creem/events", // default events: { "checkout.completed": async (ctx, event) => { // send confirmation email, grant entitlements, log analytics await ctx.runMutation(internal.onboarding.markPurchased, { checkoutId: event.object.id, }); }, "subscription.update": async (ctx, event) => { console.log("Subscription updated:", event.object.id); }, }, }); ``` Dispatched events: `checkout.completed`, `subscription.active`, `subscription.paid`, `subscription.canceled`, `subscription.scheduled_cancel`, `subscription.past_due`, `subscription.expired`, `subscription.trialing`, `subscription.paused`, `subscription.unpaid`, `subscription.update`, `refund.created`, `dispute.created`. Dispute events are available to custom handlers only (no built-in sync). ## Checkout gates and auto-resume `onBeforeCheckout` fires before the widget calls `checkouts.create`, at either the provider or the widget level. Return `false` to abort. Use it for auth gates, terms acceptance, confirmation dialogs, or analytics: ```tsx theme={null} { if (!currentUser) { pendingCheckout.save(intent); // sessionStorage helper from the library openSignInDialog(); return false; } return true; }} > ... ``` **Auto-resume after sign-in.** If your callback saved the intent with `pendingCheckout.save(intent)`, the widget notices when the Convex query re-fires with an authenticated user and re-triggers checkout itself. This works for modal auth such as Clerk or an Auth0 popup, and for redirect auth such as OAuth, with no manual resume code. Auto-resume is skipped when the user already has an active subscription or owns the product, so a sign-in cannot produce a duplicate purchase. Sibling guards for the other flows: `onBeforePlanChange` (paid switches and unit updates) and `onBeforePlanActivation` (app-owned plans like trials). ## Internationalization Set `i18n` once on the provider. Every connected widget inherits it, covering cards, dialogs, billing history, portal buttons, recovery banners, credits, and accessibility labels: ```tsx theme={null} `${units} Einheit${units === 1 ? "" : "en"}`, }, priceInterval: { "every-month": "/Monat", "every-year": "/Jahr", }, }, }} > ... ``` Product names and descriptions are merchant-owned content. Localize them in your catalog or with composition slots. ## Custom billing UI model `uiModel` returns everything the widgets need. To add app-specific fields, write your own query on top of `creem.getBillingModel()`: ```ts theme={null} export const getCustomBillingModel = query({ args: {}, handler: async (ctx) => { const user = await currentUser(ctx); const billingData = await creem.getBillingModel(ctx, { entityId: user?._id ?? null, user: user ? { id: user._id, email: user.email } : null, }); return { ...billingData, teamSize: user?.teamSize, featureFlags: user?.featureFlags, }; }, }); ``` A null `entityId` is handled gracefully, so public pricing pages get the catalog without auth. ## Creem server selection The SDK defaults to the production API. Choose explicitly per deployment: ```bash theme={null} npx convex env set CREEM_SERVER test # test mode npx convex env set CREEM_SERVER prod # production (or omit) ``` See [Test Mode](/getting-started/test-mode) for the full test-environment workflow and test cards. ## Webhook debug logging The webhook handler logs the event type and event ID. It deliberately does not log the payload, which carries customer names and email addresses. When debugging an integration, opt in to the full body: ```bash theme={null} npx convex env set CREEM_WEBHOOK_DEBUG true ``` Unset it again once you are done - the verbose output puts customer PII in your deployment logs. ## Related * Why the entity model and API contract look the way they do: [Concepts](/code/sdks/convex/concepts) * Upgrading from 0.3.x, or retiring another provider: [Migration](/code/sdks/convex/migration) * Direct SDK access and troubleshooting: [Reference](/code/sdks/convex/reference) # Concepts Source: https://docs.creem.io/code/sdks/convex/concepts How the Creem Convex component models billing: the entity that owns it, the four sources of billing state, and the API contract the widgets consume. Three ideas explain most of the component's behaviour. Read this once and the rest of the documentation stops holding surprises. ## The billing entity Every subscription, order, and credit balance belongs to one billing entity, identified by the `entityId` your resolver returns. It is the first decision you make and the most awkward one to change later. For personal billing, return the user ID. For organization or team billing, return the org ID. Checkout metadata and webhook resolution follow automatically, with no other code changes: ```ts theme={null} const resolve: ApiResolver = async (ctx) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) return null; // anonymous; public pricing pages still render const org = await ctx.runQuery(api.orgs.getActiveOrg); return { userId: identity.subject, email: identity.email!, entityId: org?._id ?? identity.subject, }; }; ``` > [!WARNING] > > Return `null` for an unauthenticated caller. Anything **thrown** from the resolver is treated as a > real failure: it is logged and rethrown instead of quietly degrading a signed-in user to the > logged-out pricing page. (Throwing the exported `CreemNotAuthenticatedError` is also accepted as > an anonymous signal.) ### One Creem customer, several entities Creem keeps one customer per store and email address. When the same person checks out for two billing entities, for example their personal account and an organization, both entities map to the same Creem customer. The component therefore records an owner on every subscription and order: * The owner is the `entityId` field, taken from the checkout that created the row (`convexBillingEntityId` in its metadata, which Creem copies onto the subscription and the order). * It is write-once. Any verified webhook, even one that arrives out of order, can fill a missing owner, but nothing changes an existing one; a conflicting claim is logged and ignored. * Webhook side effects follow what the stored row accepted after the timestamp-guarded write: its owner and customer decide the customer mapping (and any re-pointing), and its status and start date decide whether app-owned plans end. A stale or conflicting event cannot trigger them through its own metadata, customer, or status. What that scopes: * **Scoped to the entity:** subscriptions and orders in `uiModel`, `snapshot`, `getBillingModel`, `getBillingSnapshot`, `subscriptions.list`/`listAll` and `orders.list`, read through an index on the owner. The subscription commands (`update`, `cancel`, `resume`, `pause`, `cancelScheduledUpdate`) reject another entity's subscription ID like an unknown one, and period-end updates are checked again when they apply. * **Refused while the customer is shared:** `customers.portalUrl` throws a `ConvexError` with `code: "shared-customer"` (the Creem portal manages everything of the customer), and `` and `` show `portal.sharedCustomer`. `customers.updateBillingEmail` returns `{ status: "shared-customer" }`, and `` shows `billingEmail.sharedCustomer`. * **Still customer-wide:** `transactions.search` and `` list the Creem customer's transactions, and Customer Credits keep one balance per Creem customer. A customer counts as shared for an entity when another entity is or ever was mapped to it, or owns one of its subscriptions or orders. The component keeps every mapping in a `customerEntityHistory` table, so re-pointing an entity to a new customer does not erase that evidence. `creem.customers.isShared(ctx, { entityId })` exposes the check. #### Upgrading an existing deployment Rows written before this version have no `entityId`. Until the backfill below gives them one: * A row counts for the entity its metadata `convexBillingEntityId` records, and a claim naming another entity counts as evidence that the customer is shared. * A row that records no entity counts for an entity only while no other entity has touched the customer; otherwise it belongs to no entity. * Only the first 50 rows without an owner per table and customer are read. Until the backfill has run, an entity with more such rows can miss subscriptions and orders (and the access they grant) beyond those 50, and a customer with more than 50 counts as shared, so its untagged rows stay hidden and its portal and billing email are refused. So run the backfill right after deploying. Run the component's `backfillBillingEntityTags` mutation once after deploying. For each customer mapping it records the mapping in the history, then copies every recorded `convexBillingEntityId` into `entityId`, and only after that assigns the mapping's entity to the rows that record none, when no other entity has ever been mapped to the customer or owns one of its rows. Ambiguous rows keep no owner. Paging contract: start without a cursor and pass back the returned `cursor` until `isDone`; the result also reports how many rows got an owner (`processed`). Each call examines at most `batchSize` rows (default and maximum 25) and moves past a customer only after examining all of its rows, so a long run of ambiguous rows does not hide later ones. The backfill is complete when a call returns `isDone: true`; a later run from the start then reports `processed: 0` in every call, which you can use to check it. Running the whole backfill again is safe. It pages with its own cursor because Convex does not allow `paginate()` inside a component. The row cap does not bound bytes: if rows carry very large metadata and a call fails on Convex's read limit, call again with the same `cursor` and a smaller `batchSize`. ```ts title="convex/billing.ts" theme={null} export const backfillBillingEntities = internalAction({ args: {}, handler: async (ctx) => { let cursor: string | null = null; for (;;) { const page = await ctx.runMutation(components.creem.lib.backfillBillingEntityTags, { cursor, }); if (page.isDone) return; cursor = page.cursor; } }, }); ``` One case cannot be resolved: if an entity was re-pointed away from a customer before this version and left untagged rows there, nothing records that it was ever mapped, so those rows count for the entity that is still mapped to that customer. By default, the component tracks the entity's active app-owned plan itself. Apps that own their plan assignment can override that from the resolver — see [Advanced → Resolver plan overrides](/code/sdks/convex/advanced#resolver-plan-overrides). ## The billing state model Billing state comes from four places. Three of them store data. The fourth is derived from the other three, and that distinction is worth learning early: | Source | Owned by | Holds | Read it from | | - | - | - | - | | **Creem subscriptions** | Creem, synced by webhook | Recurring subscriptions. An entity can hold several at once, such as a base plan plus add-ons | `snapshot.subscriptions[]` | | **Creem orders** | Creem, synced by webhook | One-time purchases. Subscription checkouts create orders too | `snapshot.orders[]` | | **App-plan assignments** | This component | Free plans, no-card trials, and custom internal plans, both current and scheduled | `snapshot.appPlanAssignments[]` | | **`access`** | Derived, not stored | Everything the entity currently has, flattened across the three above | `snapshot.access[]` | Write to the first three through checkout, webhooks, and `creem.appPlans.activate`. Do not treat `access` as a source of truth. It is recomputed on every read. ```ts theme={null} { entityId: "org_123", subscriptions: [/* Creem recurring subscriptions, incl. add-ons */], orders: [/* one-time orders */], appPlanAssignments: [/* app-owned plans: free, no-card trials */], access: [/* derived: everything the entity currently has */], paymentRecoveryState: "none", availableBillingActions: ["portal", "cancel"], } ``` `snapshot` (generated by `creem.api({ resolve })`) and `creem.getBillingSnapshot(ctx, { entityId })` both return this shape. Everything is synced into Convex, so reading it is a local reactive query with no Creem API round-trip. ### Easily confused pairs | Pair | The distinction | | - | - | | `updateBehavior` vs `appPlanUpdateBehavior` | `updateBehavior` covers paid-to-paid switches and unit changes, using Creem proration or `"period-end"`. `appPlanUpdateBehavior` covers paid-to-app-owned, which is a cancellation flow, so it takes `"period-end"` or `"immediate"`. | | `groupId` vs `eligibilityScopeId` | `groupId` is presentation: which audience tab a plan appears under. `eligibilityScopeId` is entitlement: which plans count as mutually exclusive alternatives for scoped trial expiry. A plan can use both, independently. | | Creem-managed trial vs app-owned trial | A Creem-managed trial is a `category: "paid"` recurring plan with a trial configured on the Creem product. Creem owns the card, the subscription, and `subscription.trialing`. An app-owned trial is `category: "trial"` with `billingType: "custom"`. No Creem subscription exists, and the component records the activation. | ## The connected API contract Widgets hold no Convex function references of their own. Every backend call goes through one `ConnectedBillingApi` object they read from the provider, and its fields decide what the UI can do. Export and wire only what your product should allow. `connectCreemApi` maps the conventional `convex/billing.ts` export names onto that shape for you. Every reference is typed by function kind, args, **and** return type, so a missing or mis-wired export is a compile error rather than a blank widget: ```ts theme={null} import { connectCreemApi } from "@creem_io/convex/react"; // or /svelte import { api } from "../convex/_generated/api"; const billingApi = connectCreemApi(api.billing); ``` | API field | Generated export name | Used by | If omitted | | - | - | - | - | | `uiModel` | `uiModel` | All connected widgets | Required; widgets cannot load state | | `checkouts.create` | `checkoutsCreate` | `Subscription.Root`, `Product.Root` | Required; no checkout is possible | | `subscriptions.update` | `subscriptionsUpdate` | Plan switches, unit changes | Switch and unit controls hidden | | `subscriptions.cancel` | `subscriptionsCancel` | Cancel buttons | Cancel controls hidden | | `subscriptions.resume` | `subscriptionsResume` | Undo scheduled cancellation | Resume controls hidden | | `subscriptions.cancelScheduledUpdate` | `subscriptionsCancelScheduledUpdate` | App-side period-end update undo | Pending update undo hidden | | `plans.activate` | `plansActivate` | App-owned plans (free, no-card trials) | Trial/free plan cards cannot activate | | `customers.portalUrl` | `customersPortalUrl` | `BillingPortal`, payment recovery button | Portal buttons hidden | | `customers.billingEmail` | `customersBillingEmail` | `BillingEmail` | Billing email form hidden | | `customers.updateBillingEmail` | `customersUpdateBillingEmail` | `BillingEmail` | Billing email form hidden | | `transactions.search` | `transactionsSearch` | `BillingHistory` | Billing history can't render | | `credits.getBalance` | `creditsGetBalance` | `Credits.Root` | Credit balance UI can't work | Building the object by hand still works when you wrap the generated functions in your own RBAC actions. See [Advanced → Custom auth and RBAC](/code/sdks/convex/advanced#custom-auth-and-rbac). ## Where to go next * Wire the entity and export the API: [Quickstart](/code/sdks/convex/quickstart) * Enforce access on the server: [Entitlements](/code/sdks/convex/entitlements) * Custom auth, RBAC, and webhook middleware: [Advanced](/code/sdks/convex/advanced) * Exact signatures and props: [Reference](/code/sdks/convex/reference) # Entitlements & Account UI Source: https://docs.creem.io/code/sdks/convex/entitlements Feature gating, usage limits, billing snapshot, billing history, payment recovery, and the customer portal in the Creem Convex component. Gating features on billing state, evaluating usage limits, and the account-level widgets. The state model itself is explained in [Concepts](/code/sdks/convex/concepts#the-billing-state-model). > [accordion] Where this code goes, and what it assumes > > Examples on this page are fragments. They render inside the provider you mounted > in the [Quickstart](/code/sdks/convex/quickstart): > > ```svelte theme={null} > > > > ``` > > If something below does not work, one of these is usually missing. Each links > straight to the step that sets it up. > > * [Component registered](/code/sdks/convex/quickstart#register-component) — `app.use(creem)` in `convex/convex.config.ts` > * [Secrets set](/code/sdks/convex/quickstart#set-secrets) — `CREEM_API_KEY` and `CREEM_WEBHOOK_SECRET` in Convex env > * [Billing API exported](/code/sdks/convex/quickstart#export-billing-api) — `convex/billing.ts` calling `creem.api({ resolve })` > * [Webhook registered](/code/sdks/convex/quickstart#register-webhook) — `creem.registerRoutes(http)` in `convex/http.ts` > * [Products created](/code/sdks/convex/quickstart#create-products) — one Creem product per plan and billing cycle > * [Products synced](/code/sdks/convex/quickstart#sync-products) — `npx convex run billing:syncBillingProducts` > * [Styles imported](/code/sdks/convex/quickstart#import-styles) — `@creem_io/convex/styles` after the Tailwind import > * [Catalog defined](/code/sdks/convex/quickstart#define-plans) — `billingCatalog` mapping plan IDs to product IDs > * [Provider mounted](/code/sdks/convex/quickstart#render-pricing-page) — `` around your billing UI ## Gating UI with BillingGate `BillingGate` conditionally renders based on which billing actions are available in the snapshot (`checkout`, `portal`, `cancel`, `reactivate`): > [tab] React > > ```tsx title="Account page" theme={null} > snapshot={snapshot} > requiredActions="portal" > fallback={

Upgrade to access the billing portal.

} > > >

You have portal access.

>
> ``` > [tab] Svelte > > ```svelte theme={null} > > {#snippet children()} >

You have portal access.

> {/snippet} > {#snippet fallback()} >

Upgrade to access the billing portal.

> {/snippet} >
> ``` ## Usage limits Catalog plans can carry `limits` (arbitrary numeric keys like `projects` or `aiMessages`). `evaluateUsageLimits` compares your app's usage counters against the active plan's limits: ```ts theme={null} import { evaluateUsageLimits } from "@creem_io/convex/react"; // or /svelte const usageLimits = evaluateUsageLimits({ catalog: billingCatalog, planId: activePlanId, usage: { projects: 3, aiMessages: 72, }, }); ``` The library evaluates the limits. Your app owns the actual usage counters and decides where they live. > [!WARNING] > > UI gates are user experience, not security. Protected backend actions must check billing state > server-side. Read the snapshot inside your Convex function before doing the work. ## UI permissions `BillingPermissions` controls which widget buttons are enabled. Use it for role-based UI, such as letting only org admins manage billing. Set it once at the provider: ```tsx title="Account page" theme={null} ... ``` Disabled permissions render greyed-out buttons. This is cosmetic gating only. Enforce the real rules in your Convex functions, as described in [Advanced → Custom auth and RBAC](/code/sdks/convex/advanced#custom-auth-and-rbac). ## Account widgets ### Billing portal Opens the Creem customer portal, which is where payment methods, billing details, and invoice documents live. It hides itself when the entity has no Creem customer record yet, since customers are created on first checkout: ```tsx title="Account page" theme={null} Manage billing & invoices ``` Requires `customers.portalUrl` in the connected API. ### Billing email The Creem customer portal does not let a customer change the email address invoices and receipts go to. `` does: it shows the address Creem currently uses, and saves a new one through Creem's customer API. ```tsx title="Account page" theme={null} ``` Like the portal button, it renders nothing until the entity has a Creem customer, and nothing when `canManageBillingEmail` is `false`. It reloads when the billing entity changes. Each request also carries the entity the form shows, and the generated actions refuse it when your resolver now returns a different one, so switching organizations in another tab never saves one organization's address into another. A failed load offers a retry button. Requires `customers.billingEmail` and `customers.updateBillingEmail` in the connected API. Export `customersBillingEmail` and `customersUpdateBillingEmail` from `convex/billing.ts` and `connectCreemApi` wires them: ```ts title="convex/billing.ts" theme={null} export const customersBillingEmail = customers.billingEmail; export const customersUpdateBillingEmail = customers.updateBillingEmail; ``` The generated actions let any caller your `resolve` accepts change the entity's billing email. If only billing admins may do that, write your own action with `customersUpdateBillingEmailArgs`, keep the `expectedEntityId` check, and check the role before calling `creem.customers.updateBillingEmail`, as in [Advanced → Custom auth and RBAC](/code/sdks/convex/advanced#custom-auth-and-rbac). Creem rejects an address that another customer of your store already uses. The widget then shows its generic save error. When the same person checked out for several of your billing entities, those entities share one Creem customer; the widget then refuses the change and says the address is shared, because it is also the other entities' billing address. `` is the ready-made layout. For your own markup, compose the parts inside ``; the root keeps the state and wires the label, description, and error to the input: ```tsx title="Account page" theme={null}
Update
``` Svelte uses the same names: ``, ``, and so on. See the [reference](/code/sdks/convex/reference#component-reference) for every part. ### Billing history Paginated transaction history, backed by Creem's transaction search. This renders transaction rows, not invoice documents: ```tsx title="Account page" theme={null} ``` ![A billing history table with Date, Description, Type, Status, and Amount columns listing five paid transactions, above a pager running from page 1 to page 22](https://mintcdn.com/creem/IA-lLh1OWoZ0Tbxw/images/convex/billing-history-light.webp?fit=max\&auto=format\&n=IA-lLh1OWoZ0Tbxw\&q=85\&s=750f7765a6f65a1e82cbc9cdcbd5e40f) Requires `transactions.search` in the connected API. Export `transactionsSearch` from `convex/billing.ts` and `connectCreemApi` wires it automatically. > [!NOTE] > > **Portal-only today.** Payment methods, billing details, and invoice documents are handled by > Creem's hosted portal, which `` opens for the customer. Prefer them embedded in > your own UI as Widgets? Vote for [payment method, billing preference, and invoice > APIs](https://creem.featurebase.app/p/payment-method-billing-preference-and-invoice-apis). ### Payment recovery When a subscription is past due or a payment failed, surface it and route the user to the portal to fix their payment method: ```tsx title="Account page" theme={null} ``` ![A yellow past-due banner above a red payment-failed banner, followed by an Update payment method button](https://mintcdn.com/creem/IA-lLh1OWoZ0Tbxw/images/convex/payment-recovery-light.webp?fit=max\&auto=format\&n=IA-lLh1OWoZ0Tbxw\&q=85\&s=6fb5766466482b00200a787b73ddf65b) The banner derives its state from `snapshot.paymentRecoveryState` (or accepts an explicit state). The button reads `customers.portalUrl` from the provider like every other connected widget, and renders nothing when no portal action is wired. ### Checkout success Show a confirmation banner when the user returns from checkout. Creem's query parameters are parsed for you: ```tsx title="Account page" theme={null} ``` React additionally exports a `useCheckoutSuccessParams()` hook returning the parsed params. ### Status banners Presentational components for specific states, fed from the snapshot: | Component | Shows | | - | - | | `ScheduledChangeBanner` | Scheduled cancellation or pending period-end update, with undo/resume | | `TrialLimitBanner` | Trial expiration notice | | `PaymentWarningBanner` | Pending, refunded, or partially refunded payment warning | ## Server-side entitlement checks The same snapshot powers backend enforcement: ```ts title="convex/projects.ts" theme={null} export const createProject = mutation({ args: { name: v.string() }, handler: async (ctx, args) => { const user = await requireUser(ctx); const snapshot = await creem.getBillingSnapshot(ctx, { entityId: user.orgId ?? user._id, }); // `access` only contains entitlements that are currently valid, so the // presence of a subscription item is the check. Do not add // `a.status === "active"`: that would deny users on a trial or in the // `past_due` dunning grace period, who should still have access. const hasPaidAccess = snapshot.access.some((a) => a.kind === "subscription"); const projectCount = await countProjects(ctx, user.orgId ?? user._id); if (!hasPaidAccess && projectCount >= FREE_PROJECT_LIMIT) { throw new ConvexError("Upgrade to create more projects"); } // ...create the project }, }); ``` Widget gates keep the UI honest. This check is what actually protects the feature. ### Checking a single subscription When you gate on `subscriptions.getCurrent` rather than the snapshot, test the **status** - never the mere existence of a subscription. A returned subscription may be `unpaid` or `paused`, in which case it must not grant access: ```ts theme={null} import { isActiveSubscriptionStatus } from "@creem_io/convex"; const subscription = await creem.subscriptions.getCurrent(ctx, { entityId }); const hasAccess = isActiveSubscriptionStatus(subscription?.status); ``` `isActiveSubscriptionStatus` treats `active`, `trialing`, `scheduled_cancel`, and `past_due` as entitling. `past_due` is a payment-retry window rather than a loss of access - surface it with [`PaymentRecoveryBanner`](#payment-recovery) instead of cutting the user off. # Integration Guide Source: https://docs.creem.io/code/sdks/convex/integration Sequential, self-contained setup guide for the Creem Convex component — optimized for AI-agent-driven greenfield and brownfield integrations. > [!NOTE] > > This guide is the complete setup sequence in one page, with validation steps — optimized for AI > agents and for careful step-by-step integration (agents can fetch it as markdown by appending > `.md` to this page's URL). For learning the component and ongoing development, start with the > [Quickstart](/code/sdks/convex/quickstart) and its sibling pages. This guide walks through a complete Convex Creem integration for React or Svelte. Use this order: 1. Set up the Convex component and webhook route. 2. Export the connected Convex billing API. 3. Define the browser-side billing catalog. 4. Wrap your billing UI in `CreemConvexProvider`. 5. Choose the billing path you need: subscriptions, one-time products, credits, account tools, or usage gates. For brownfield projects, first inventory the billing integration you are replacing. Agent automation can add the Convex Creem component, routes, and catalog wiring, but it cannot know which old provider settings are still safe to remove from your deployment or payment dashboard. Before switching traffic, check: * Existing webhook paths in your app and payment provider dashboard, such as `/api/stripe/webhook`, `/api/billing/webhook`, `/webhooks/lemonsqueezy`, or other custom billing endpoints. Keep them only if another live billing flow still depends on them. * Public client env vars for the old billing UI, such as product, price, plan, checkout, or publishable-key variables in `VITE_*`, `NEXT_PUBLIC_*`, or `PUBLIC_*` namespaces. * Server env vars for the old billing system, such as API keys, webhook signing secrets, customer portal configuration, price IDs used by server actions, or framework route secrets. * Background jobs, scheduled syncs, or server functions that still read the old billing env vars or process the old webhook events. Clean up the old webhook registrations and env vars manually after confirming the Convex Creem webhook is receiving events and any necessary historical data has been migrated or retained. Do not delete old secrets before rollback and data-retention requirements are clear. *** ## 1. Install Install the package plus the peer dependencies for the frontend framework you use. ```bash theme={null} npm install @creem_io/convex convex creem ``` For Svelte widgets: ```bash theme={null} npm install svelte convex-svelte @ark-ui/svelte ``` For React widgets: ```bash theme={null} npm install react react-dom @ark-ui/react ``` *** ## 2. Register the Convex component Create or update `convex/convex.config.ts`: ```ts theme={null} import { defineApp } from "convex/server"; import creem from "@creem_io/convex/convex.config"; const app = defineApp(); app.use(creem); export default app; ``` Set Creem secrets in Convex: ```bash theme={null} npx convex env set CREEM_API_KEY npx convex env set CREEM_WEBHOOK_SECRET npx convex env set CREEM_SERVER test ``` `CREEM_SERVER=test` points the component at the Creem test API, matching a test-mode API key. Set it to `prod` (or omit it) when deploying with a production key. If you use credit packs, also set a server-side product ID. Do not trust a browser-exposed product ID for webhook fulfillment: ```bash theme={null} npx convex env set CREEM_ONETIME_CREDITS prod_... ``` *** ## 3. Export the Convex billing API Create `convex/billing.ts`. Replace the resolver with your real auth and entity logic. `entityId` is the billing owner; use the user ID for user billing or the org/team ID for organization billing. ```ts theme={null} import { Creem, defineBillingCatalog, type ApiResolver } from "@creem_io/convex"; import { components } from "./_generated/api"; import { action, internalAction } from "./_generated/server"; import { ConvexError, v } from "convex/values"; const creditsProductId = process.env.CREEM_ONETIME_CREDITS; const serverBillingCatalog = creditsProductId ? defineBillingCatalog({ version: "server", plans: [ { planId: "ai-credits-100", category: "paid", billingType: "onetime", creemProductIds: { custom: creditsProductId, }, creditGrant: { amount: "100", accountName: "credits", unitLabel: "credits", refundBehavior: "revoke_on_full_refund", }, }, ], } as const) : undefined; export const creem = new Creem(components.creem, { ...(serverBillingCatalog ? { billingCatalog: serverBillingCatalog } : {}), cancelMode: "scheduled", }); // Return `null` for an unauthenticated caller. Public pricing pages depend on // that. Anything thrown here counts as a real failure: it is logged and // rethrown instead of silently rendering the logged-out state. const resolve: ApiResolver = async (ctx) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) return null; return { userId: identity.subject, email: identity.email!, entityId: identity.subject, // for org billing, return the verified org ID }; }; const { uiModel, snapshot, checkouts, subscriptions, products, customers, transactions, plans, orders, credits, } = creem.api({ resolve }); export { uiModel, snapshot }; export const checkoutsCreate = checkouts.create; export const subscriptionsUpdate = subscriptions.update; export const subscriptionsCancel = subscriptions.cancel; export const subscriptionsResume = subscriptions.resume; export const subscriptionsCancelScheduledUpdate = subscriptions.cancelScheduledUpdate; export const subscriptionsPause = subscriptions.pause; export const subscriptionsList = subscriptions.list; export const subscriptionsListAll = subscriptions.listAll; export const productsList = products.list; export const productsGet = products.get; export const customersRetrieve = customers.retrieve; export const customersPortalUrl = customers.portalUrl; export const customersBillingEmail = customers.billingEmail; export const customersUpdateBillingEmail = customers.updateBillingEmail; export const transactionsSearch = transactions.search; export const plansActivate = plans.activate; export const ordersList = orders.list; export const creditsGetBalance = credits.getBalance; export const creditsListEntries = credits.listEntries; export const generateImage = action({ args: { requestId: v.string() }, returns: v.object({ creditsConsumed: v.string() }), handler: async (ctx, args) => { const identity = await resolve(ctx); if (!identity) throw new ConvexError("Not authenticated"); await creem.credits.debitForEntity(ctx, { entityId: identity.entityId, amount: "10", reference: "generate_image", // A stable key per logical operation. A timestamp would make every // retry a fresh debit, which is the opposite of idempotent. idempotencyKey: `generate_image_${args.requestId}`, }); return { creditsConsumed: "10" }; }, }); export const syncBillingProducts = internalAction({ args: {}, returns: v.object({ synced: v.boolean() }), handler: async (ctx) => { await creem.syncProducts(ctx); return { synced: true }; }, }); ``` Security boundary: * `export const creem = new Creem(...)` exports a normal server-side object for other Convex modules such as `http.ts`; it does not register a client-callable Convex function. * Functions returned by `creem.api({ resolve })` become public when exported from `convex/billing.ts`. * `resolve` must authenticate the caller and authorize the selected user or organization. Generated functions then bind customers, subscriptions, transactions, and credit reads to that resolved `entityId`. * Privileged credit operations are intentionally absent from the generated public API. Put grants and spending behind app-owned actions whose amount, reference, and idempotency policy are controlled on the server. What to consider: * Export only capabilities your UI needs. If you omit `subscriptions.cancel`, cancel buttons disappear. * Use `cancelMode: "scheduled"` when canceling should keep access until the current period ends. Use `"immediate"` when cancellation should end access immediately. * Put credit grants in the server catalog because webhooks run on the server. * `syncBillingProducts` is intentionally an `internalAction`. Trigger it from the Convex CLI, dashboard, or another trusted internal function, not from browser UI. * App-owned credit spending, such as `generateImage`, should call `creem.credits.debitForEntity` with server-controlled business inputs. The credits widget only displays and refreshes balance state. *** ## 4. Register the webhook route Create or update `convex/http.ts`: ```ts theme={null} import { httpRouter } from "convex/server"; import { creem } from "./billing"; const http = httpRouter(); creem.registerRoutes(http, { path: "/creem/events", events: { "checkout.completed": async (_ctx, event) => { console.log("Checkout completed", event); }, "subscription.update": async (_ctx, event) => { console.log("Subscription updated", event); }, }, }); export default http; ``` In Creem, set the webhook endpoint to: ```text theme={null} https:///creem/events ``` The component stores customers, subscriptions, orders, refunds, disputes, and credit grants from supported Creem events. ### Create the products Every plan in your catalog maps to a Creem product. Create them in the dashboard, or with the [CLI](/ai/for-agents/cli). Running it through `npx` avoids installing anything globally on the developer's machine: ```bash theme={null} npx @creem_io/cli login --api-key creem_test_YOUR_KEY npx @creem_io/cli products create \ --name "Basic" \ --description "For small teams" \ --price 1900 \ --currency USD \ --billing-type recurring \ --billing-period every-month ``` Use the same Creem API key you set as `CREEM_API_KEY` in step 2. `brew` and global `npm` installs are also available; see the [CLI guide](/ai/for-humans/cli). Repeat for every plan and billing cycle you offer. A plan billed monthly and yearly needs two products. `creem products list --json` prints the IDs for scripting. `--billing-period` accepts `every-month`, `every-three-months`, `every-six-months`, or `every-year`, and is required when `--billing-type` is `recurring`. Use `--billing-type onetime` for one-time products and credit packs. ### Sync them into Convex Once the products exist, pull their metadata into Convex: ```bash theme={null} npx convex run billing:syncBillingProducts ``` This works with the internal action above. If you expose your own admin-only public action instead, protect it server-side and keep it out of client-facing billing pages. *** ## 5. Add CSS Import the package CSS in your app CSS entry point: ```css theme={null} @import "tailwindcss"; @import "@creem_io/convex/styles"; ``` *** ## 6. Define the browser billing catalog Create a shared catalog file in your frontend. Import from the framework entry you are using (`/svelte` or `/react`). ```ts theme={null} import { defineBillingCatalog } from "@creem_io/convex/svelte"; export const billingCatalog = defineBillingCatalog({ version: "1", defaultPlanId: "free", plans: [ { planId: "free", category: "free", title: "Free", description: "For individuals getting started", limits: { projects: 1, aiMessages: 50 }, }, { planId: "basic", category: "paid", billingType: "recurring", title: "Basic", creemProductIds: { "every-month": import.meta.env.VITE_CREEM_SUB_BASIC_MONTHLY, }, limits: { projects: 5, aiMessages: 250 }, }, { planId: "premium", category: "paid", billingType: "recurring", title: "Premium", recommended: true, creemProductIds: { "every-month": import.meta.env.VITE_CREEM_SUB_PREMIUM_MONTHLY, "every-year": import.meta.env.VITE_CREEM_SUB_PREMIUM_ANNUAL, }, limits: { projects: 100, aiMessages: 2500 }, }, { planId: "enterprise", category: "enterprise", title: "Enterprise", contactUrl: "https://example.com/contact", }, ], } as const); ``` What to consider: * `creemProductIds` maps billing cycles to Creem product IDs. * Supported recurring cycles are `every-month`, `every-three-months`, `every-six-months`, and `every-year`. * If a plan has multiple cycles, the interval selector appears automatically. * Product IDs used only by frontend widgets may live in your framework's public client env namespace, such as Vite `VITE_*`, Next.js `NEXT_PUBLIC_*`, or SvelteKit `PUBLIC_*`. Trusted webhook fulfillment data must live in Convex env vars. *** ## 7. Connect Svelte In Svelte, initialize Convex once with `setupConvex`, create a `ConnectedBillingApi`, and wrap widgets in `CreemConvexProvider`. The provider is the required integration boundary. `ConvexCreemProvider` is not an exported component name; the package exports `CreemConvexProvider`. ```svelte theme={null} ``` Important: connected widgets must be rendered inside `CreemConvexProvider`. Do not pass `api={...}` directly to `Subscription.Root`, `Product.Root`, `BillingPortal`, or `BillingHistory`. The provider-level `ConnectedBillingApi` decides which paths are available: | API field | Used by | If omitted | | - | - | - | | `uiModel` | All connected widgets | Widgets cannot load billing state. | | `checkouts.create` | `Subscription.Root`, `Product.Root` | Subscribe/buy buttons cannot create checkout sessions. | | `subscriptions.update` | Plan switches, unit changes, period-end updates | Switch and unit update controls are unavailable. | | `subscriptions.cancel` | Subscription cancel buttons | Cancel controls are unavailable. | | `subscriptions.resume` | Scheduled-cancel resume controls | Resume/undo cancel controls are unavailable. | | `subscriptions.cancelScheduledUpdate` | App-side period-end update undo | Pending period-end update undo is unavailable. | | `plans.activate` | App-owned plans (free plans, no-card trials) | Trial and free plan cards cannot be activated. | | `customers.portalUrl` | `BillingPortal`, `PaymentRecoveryButton` | Portal buttons cannot open the Creem customer portal. | | `customers.billingEmail` | `BillingEmail` | The billing email form is hidden. | | `customers.updateBillingEmail` | `BillingEmail` | The billing email form is hidden. | | `transactions.search` | `BillingHistory` | Billing history cannot render. | | `credits.getBalance` | `Credits.Root` | Credit balance UI cannot load. | Use `createCreemSvelte` when you want one typed binding object: ```svelte theme={null} ``` You can also read `uiModel` directly once for account-level UI such as payment recovery and usage gates: ```svelte theme={null} ``` *** ## 8. Connect React React uses the same `ConnectedBillingApi` shape. The difference is your normal Convex React client setup. ```tsx theme={null} import { CreemConvexProvider, Subscription, BillingPortal, createCreemReact, connectCreemApi, plansOf, } from "@creem_io/convex/react"; import { api } from "../convex/_generated/api"; import { billingCatalog } from "./billingCatalog"; const connectedApi = connectCreemApi(api.billing); const billing = createCreemReact({ catalog: billingCatalog, api: connectedApi, defaultCycle: "every-month", }); export function PricingPage() { return ( ); } ``` *** ## 9. Choose your billing path Use the closest path as your starting point. | Scenario | Main API to configure | Considerations | | - | - | - | | One paid plan | `Subscription.Root plans={["pro"]}` | Smallest catalog-driven subscription setup. | | Simple upgrade choice | `plans={["basic", "premium"]}` | Good default for most SaaS pricing pages. | | Monthly/yearly or more cycles | `creemProductIds` with several cycle keys | The interval selector appears only when multiple cycles exist. | | Plans split by audience | `groups={[...]}` | Group selector controls visible plans; unit plans can show a picker. | | Quantity from app state | `units={memberCount}` | Keep Creem quantity synced when the app count changes. | | Groups with different intervals | `groups` plus multi-cycle products | The active group controls available billing cycles. | | No-card trial before choosing free or paid | `category: "trial"` plus `plans.activate` | Component records once-per-entity history and can expire trials by `eligibilityScopeId`; your app owns quotas. | | Checkout requires terms, auth, or policy consent | `onBeforeCheckout`, `onBeforePlanChange`, `onBeforePlanActivation` | Return `false` to stop the billing action. Enforce real permissions server-side too. | | App-owned card markup | `unstyled`, `Subscription.Grid`, `Subscription.Item`, slots | The root still owns checkout, switch, cancel, units, and active state. | | Typed plan IDs and one binding object | `createCreemSvelte` or `createCreemReact` | Recommended for production apps. | | Downgrades apply at period end | `updateBehavior` resolver and `cancelScheduledUpdate` export | App-side scheduled updates are tracked in Convex until applied. | | One-time product sold once | `Product.Root` with `Product.Item type="one-time"` | Shows "Owned" after purchase. | | Mutually exclusive one-time products | `Product.Root transition={[...]}` | Use `via_product` for delta-priced upgrades. | | Repeatable packs or consumables | `Product.Item type="recurring"` and optional `Credits.Root` | Repeating products do not show "Owned"; credit grants should be server-owned. | | Past-due or failed-payment UI | `PaymentRecoveryBanner`, `PaymentRecoveryButton` | Button needs `customers.portalUrl`; banners can derive from snapshot or accept an explicit state. | | Transaction history | `BillingHistory` and `transactions.search` | This is transaction history, not full invoice rendering. | | Invoices go to a separate billing address | `BillingEmail` with `customers.billingEmail` and `customers.updateBillingEmail` | Changes the Creem customer email; the Creem portal cannot. | | Features depend on plan or payment state | `BillingGate`, `evaluateUsageLimits` | Billing state gates access; your app still measures usage. | The external paths are: * `/creem/events` — Convex HTTP webhook endpoint for Creem. * Creem checkout URL — opened by `checkouts.create`. * Creem customer portal URL — opened by `customers.portalUrl`. * Your checkout success URL — defaults to the current page path when `successUrl` is not passed. Detailed feature guides: [Subscriptions](/code/sdks/convex/subscriptions), [One-Time Products & Credits](/code/sdks/convex/one-time-and-credits), [Entitlements & Account UI](/code/sdks/convex/entitlements), [Advanced](/code/sdks/convex/advanced). *** ## 10. Environment placement checklist Use your app framework's public client env namespace only for values the browser needs to render widgets or start checkout, such as product IDs referenced by the frontend catalog: ```text theme={null} Vite: VITE_CREEM_SUB_BASIC_MONTHLY=prod_... Next.js: NEXT_PUBLIC_CREEM_SUB_BASIC_MONTHLY=prod_... SvelteKit: PUBLIC_CREEM_SUB_BASIC_MONTHLY=prod_... ``` Trusted server values are set with Convex, not in `.env` files: ```bash theme={null} npx convex env set CREEM_API_KEY npx convex env set CREEM_WEBHOOK_SECRET npx convex env set CREEM_SERVER test npx convex env set CREEM_ONETIME_CREDITS prod_... ``` In brownfield projects, also remove stale billing env vars after the migration is verified. Old provider values usually live in several places: local `.env*` files, hosting provider env settings, CI secrets, Convex env, and the payment provider dashboard. Search for the old provider name and old public prefixes so unused webhook secrets, price IDs, product IDs, publishable keys, and API keys do not linger. *** ## 11. Validation Before shipping an integration: * Type-check and lint your app with your project's usual commands. * Run `timeout 30 npx convex dev --once` and confirm the deployment pushes without errors. * Complete a test-mode checkout with a [test card](/getting-started/test-mode#testing-payments) and confirm the webhook writes billing state (check the Convex dashboard data browser and logs). * Confirm the widgets reflect the new subscription without a page reload. # Migration Source: https://docs.creem.io/code/sdks/convex/migration Upgrade the Creem Convex component from 0.3.x, and retire a previous billing provider safely. Two one-time jobs. Neither is needed for a new integration. ## Upgrading from 0.3.x v2 (0.4.0) is a breaking release. The tables below map every removed or changed API to its replacement. #### `creem` is now a peer dependency `creem` moved out of this package's `dependencies`, so it is no longer installed for you. Add it to your app or the package will fail to resolve at runtime: ```bash theme={null} pnpm install @creem_io/convex convex creem ``` Svelte apps also need **Svelte 5.25 or newer**. The widgets ship as uncompiled `.svelte` source and reassign `$derived` state, which earlier 5.x releases reject at compile time. If you share a billing catalog between server and browser code, import the helpers from `@creem_io/convex/core` rather than the root entry — the root is the server client and pulls the Creem Node SDK into your browser bundle: ```ts theme={null} import { defineBillingCatalog } from "@creem_io/convex/core"; ``` #### Removed primitives These exports were deleted. Importing them is a build failure. | Removed | Replacement | | - | - | | `SegmentControl` | `SegmentGroup` — same segmented control, renamed | | `BillingToggle` | `Subscription.IntervalSelector` inside a `Subscription.Root`, or `SegmentGroup` standalone | | `OneTimeCheckoutButton` | `Product.Item` for a full card, or `CheckoutButton` for a bare button | | `OneTimePaymentStatusBadge` | `CheckoutSuccessSummary`, or render your own from `parseCheckoutSuccessParams` | `BillingToggle` was a thin wrapper that rendered cycle labels into a `SegmentGroup`. Inside a `Subscription.Root`, `Subscription.IntervalSelector` replaces it and is already wired to the root's cycles; outside one, compose `SegmentGroup` directly. #### Typed connected API and `connectCreemApi` `ConnectedBillingApi` fields are now typed by function kind, args, **and** return type, so wiring the wrong generated export fails to compile. Build the object with `connectCreemApi(api.billing)` instead of by hand. | Previous API | New API | | - | - | | Hand-written `{ uiModel, checkouts: { create }, … }` | `connectCreemApi(api.billing)` | | `FunctionReference<"query">` (untyped) | `UiModelFunction` and friends | #### Resolver returns `null` for anonymous callers `ApiResolver` now returns `ResolvedBillingIdentity | null`. Returning `null` is the anonymous signal; a thrown error is a real failure that is logged and rethrown instead of silently degrading a signed-in user to the logged-out view. | Previous API | New API | | - | - | | `throw new Error("Not authenticated")` | `return null` | | Every resolver error swallowed by `uiModel` | Only `null` (or `CreemNotAuthenticatedError`) means "unauthenticated" | #### `subscriptions.update` is a discriminated union | Previous API | New API | | - | - | | `{ productId, updateBehavior? }` | `{ kind: "plan", productId, updateBehavior? }` | | `{ units, updateBehavior? }` | `{ kind: "units", units, updateBehavior? }` | | `{ freePlanId, updateBehavior? }` | `{ kind: "app-plan", appPlanId, updateBehavior? }` | Those combinations no longer typecheck, and `parseSubscriptionUpdateArgs` re-checks them for calls arriving over the wire. A plan switch no longer accepts `units`: Creem applies a product upgrade and a quantity change as separate operations, so send a second `kind: "units"` update instead. Unit counts are validated server-side (integer, 1 – 1,000,000). #### Widget namespaces are plain objects ``, ``, and `` are no longer callable components. `Subscription` and `Product` used to alias their `Item`, while `Credits` aliased its `Root`. Rendering the bare namespace silently produced the wrong element. | Previous API | New API | | - | - | | `` | `` | | `` | `` | | `` | `` | #### Binding and provider props `createCreemReact` and `createCreemSvelte` no longer return `config`, which the provider never accepted. The binding is spreadable: | Previous API | New API | | - | - | | `` | `` | | `createCreemReact({ …, config: { onBeforeCheckout } })` | `onBeforeCheckout` as a provider prop | | `BillingProviderConfig` | removed | `PaymentRecoveryButton` now reads `customers.portalUrl` from the provider; `portalUrl` is an optional override rather than a required prop. #### Model and return shapes | Previous | Now | | - | - | | `ConnectedBillingModel.user._id` | `user.id` (generic across integrations) | | `uiModel` / `snapshot` returned `any` | Real Convex `returns` validators and inferred types | | `credits.listEntries` returned an SDK page iterator | `{ entries[], hasMore }` | | `transactions.search` returned raw SDK rows | Projected `ConnectedTransactionList` | | `BillingContextValue` (flat, unimplemented) | Nested `{ model, isLoading, error, … }` contract | | `subscriptions.getCurrent` threw when the product was missing | Returns `product: null` | `subscriptions.getCurrent` no longer throws `Product not found` when a subscription references a product this deployment has not synced yet - that failure took down every query composed on top of it. `product` is now nullable, so narrow it before use: ```ts theme={null} const subscription = await creem.subscriptions.getCurrent(ctx, { entityId }); const planName = subscription?.product?.name ?? "Unknown plan"; ``` #### Subscription lifecycle behaviour These are bug fixes rather than API changes, but they change what your app sees at runtime, so review any entitlement code you wrote against 0.3.x. | Behaviour in 0.3.x | Behaviour in 0.4.0 | | - | - | | Only `canceled` subscriptions were closed out with `endedAt` | `expired` is closed out too, so it stops counting as the current subscription | | An expired subscription was still returned by `getCurrent` indefinitely | It is no longer returned once closed out | | A lapsed trial stayed "active" until some unrelated write re-ran the query | A scheduled mutation closes it at `trialEnd`, so clients update on time | | A changed Creem customer ID left the entity mapped to the old customer | The mapping is re-pointed, so subscriptions and orders resolve again | | Orders without a customer ID were stored unreachable | The webhook fails loudly and Creem retries | > [!WARNING] > > If your app granted access by checking that a subscription merely **exists**, > users on `expired` or `unpaid` subscriptions were silently keeping paid > access. Gate on the status instead - `isActiveSubscriptionStatus` covers the > active-like statuses, including the `past_due` dunning grace period: > > ```ts theme={null} > import { isActiveSubscriptionStatus } from "@creem_io/convex"; > > const subscription = await creem.subscriptions.getCurrent(ctx, { entityId }); > const hasAccess = isActiveSubscriptionStatus(subscription?.status); > ``` > > Tightening this may revoke access from users who should never have had it, so > check your own data before deploying. #### Provider-based widget API Connected widgets no longer accept direct `api={billingApi}` props. Wrap the area that renders billing UI with `CreemConvexProvider` and pass the API, catalog, permissions, and consent hooks there. | Previous API | New API | | - | - | | `` | `` | | `` | `` | | `` | `` | | `` | `` | | Widget-level `catalog`, `permissions`, gate hooks | Provider-level defaults, with widget props only for local overrides | This is intentionally breaking so apps have one billing integration boundary instead of repeating Convex function references throughout the UI. #### Unit-based billing rename The UI widget API now follows Creem's unit-based pricing language. There are no backward-compatible aliases for the previous seat-specific names. | Previous API | New API | | - | - | | `` | `` | | `` | `` | | `BillingPermissions.canUpdateSeats` | `BillingPermissions.canUpdateUnits` | | `AvailableAction` value `"update_seats"` | `AvailableAction` value `"update_units"` | | `subscribedSeats` | `subscribedUnits` | | `disableSeats` | `disableUnits` | | `onUpdateSeats` | `onUpdateUnits` | The `units` prop remains the quantity passed to checkout and subscription updates. A unit can still represent a seat, but the public API no longer assumes that seats are the only unit-based pricing use case. #### Pricing columns `twoColumnLayout` was removed. Use `columns={2}` for a fixed two-column pricing grid, or omit it for automatic layout. #### Product namespace cleanup `Product.Group` was removed. It was only a compatibility alias for `Product.Root`, not a real grouping primitive. Render `Product.Root` directly. | Previous API | New API | | - | - | | `` | `` | #### `Subscription.Group` is no longer an alias for `Subscription.Root` > [!WARNING] > > This one fails silently. In 0.3.x `Subscription.Group` was a compatibility > alias for `Subscription.Root`. It is now a distinct component that renders its > children only while its `value` matches the root's active group. > > Used as a root, it provides no root context and no plans, so it renders > **nothing at all** — no error, no warning, just an empty pricing section. | Previous usage | New usage | | - | - | | `` as the root | `` | | — | `` inside a root, to scope plans | #### `PricingSection` props `PricingSection` is a public primitive, and its props changed beyond the seat→unit rename. (`PricingCard` already took `activePlanId` in 0.3.x and is unaffected.) | Previous API | New API | | - | - | | `snapshot={snapshot}` | `activePlanId={activePlanId}` | | `twoColumnLayout` | `columns={2}` | #### `AvailableAction` covers billing state only `switch_interval`, `update_units`, and `contact_sales` were removed from `AvailableAction` and from `snapshot.availableBillingActions`. They described the *shape of a plan*, not the entity's billing state, and the v2 resolver never emitted them — so a `BillingGate` requiring one already rendered only its fallback. Removing them turns that silent no-op into a compile error. Answer those questions from the catalog entry instead: | Previous action | Ask instead | | - | - | | `switch_interval` | `plan.billingCycles.length > 1` | | `update_units` | `plan.pricingModel === "unit"` | | `contact_sales` | `plan.category === "enterprise"` | `checkout`, `portal`, `cancel`, and `reactivate` are unchanged. #### `cycleBadges` merges instead of replacing `` in React used to replace the root's badge map wholesale, so setting one interval's badge silently dropped the rest. It now merges per interval, falling back to the root's badge for any interval the prop omits — matching Svelte, which already behaved this way. To keep the old "replace everything" behaviour, pass a badge for every interval you render. #### `orders.list` returns unpaid orders `orders.list` previously filtered to `status === "paid"`. It now returns every one-time order, including `pending`, `refunded`, and `partially_refunded` ones, so the caller decides what counts as owned. `snapshot.access` and `ownedProductIds` still apply the paid filter for you. If you treated everything `orders.list` returned as granting access, filter on status explicitly: ```ts theme={null} const owned = orders.filter((order) => order.status === "paid"); ``` #### App-owned plans and i18n `freePlans.activate` and `onBeforeFreePlanActivation` were removed: | Previous API | New API | | - | - | | `freePlans.activate({ freePlanId })` | `plans.activate({ planId })` | | `onBeforeFreePlanActivation({ freePlanId })` | `onBeforePlanActivation({ planId })` | | `api.freePlans.activate` in provider config | `api.plans.activate` in provider config | Use the new plan-based API for free, trial, or other app-owned catalog plans. Convex-Creem writes `snapshot.appPlanAssignments` for the current app-owned plan; host apps only need a custom `activePlanId` projection when they intentionally want to override the component-managed assignment. Price interval suffixes now come from `labels.priceInterval`, so override those labels instead of formatting `/mo` or `/yr` in application code. #### App-plan eligibility helpers `isAppPlanEligible` and `shouldShowPlan` now take an eligibility context object as their third argument. Pass `activePlanId`, `activeOrScheduledPlanIds`, and `catalogPlans` explicitly so once-per-entity and scoped trial rules evaluate against the same billing state as the widgets. | Previous helper call | Current helper call | | - | - | | `shouldShowPlan(plan, activations, activePlanId)` | `shouldShowPlan(plan, activations, { activePlanId })` | | `isAppPlanEligible(plan, activations, planId)` | `isAppPlanEligible(plan, activations, { activePlanId: planId })` | For scoped trials, include `activeOrScheduledPlanIds` and `catalogPlans`: ```ts theme={null} shouldShowPlan(trialPlan, activations, { activePlanId, activeOrScheduledPlanIds, catalogPlans, }); ``` #### Billing Snapshot Contract `creem.getBillingSnapshot(...)` and the generated `creem.api({ resolve }).snapshot` query return the canonical `BillingSnapshot` shape with explicit arrays for subscriptions, one-time orders, and app-owned plan assignments, plus a derived `access` projection. | Previous flat field | Current source | | - | - | | `activePlanId` | Derive from `snapshot.access` or the relevant row in `snapshot.subscriptions` / `snapshot.appPlanAssignments` | | `subscriptionProductId` | `snapshot.subscriptions[n].productId` | | `subscriptionState` | `snapshot.subscriptions[n].status` | | `recurringCycle` | `snapshot.subscriptions[n].recurringCycle` | | `availableActions` | `snapshot.availableBillingActions` | | `payment` | Use payment/order-specific queries or `snapshot.orders` for paid orders | | `ownedProductIds` | Derive from paid rows in `snapshot.orders` | | primary subscription fields | Derive from the relevant `snapshot.subscriptions` row | The generated `uiModel` used by connected widgets exposes the same canonical snapshot as `uiModel.snapshot`. #### Product credit grants `Product.Item` no longer accepts checkout metadata for credit grants. Put purchase-to-credit mappings in the server-owned billing catalog with `creditGrant` so webhook fulfillment derives the amount from trusted app code. | Previous API | New API | | - | - | | `` | Catalog entry with `creditGrant: { amount: "100" }` | | Client-supplied metadata deciding the credits granted after checkout | Server-side `billingCatalog` passed to `new Creem(...)` | | App code manually deciding whether refunds should reverse granted credits | `creditGrant.refundBehavior` on the catalog entry | By default, catalog-granted credits are reversed only on full refunds. Configure `refundBehavior` per product when your app needs proportional (`"prorate"`), eager (`"debit"`), or manual (`"none"`) refund handling. *** ## Retiring a previous billing provider Moving from another billing integration (Stripe, LemonSqueezy, a custom setup)? The component's setup is additive, but removing the old system safely needs a manual inventory: 1. **Old webhook endpoints**, both in your app and in the old provider's dashboard (`/api/stripe/webhook`, `/webhooks/lemonsqueezy`, and so on). Keep them only while another live flow depends on them. 2. **Client env vars**: old product, price, plan, and publishable-key variables in the `VITE_*`, `NEXT_PUBLIC_*`, and `PUBLIC_*` namespaces. 3. **Server env vars**: old API keys, webhook secrets, portal config, and price IDs. These hide in several places at once, including local `.env*` files, hosting provider settings, CI secrets, and the old dashboard. 4. **Background jobs**: scheduled syncs or functions still reading old billing env vars or processing old webhook events. Switch traffic only after the Creem webhook is verifiably receiving events, and don't delete old secrets before rollback and data-retention requirements are clear. The [Integration Guide](/code/sdks/convex/integration) includes this checklist in an agent-executable form. # One-Time Products & Credits Source: https://docs.creem.io/code/sdks/convex/one-time-and-credits Sell owned products, consumables, and credit packs with the Creem Convex component, including refund-safe credit grants. One-time products, consumables, and credit packs. > [accordion] Where this code goes, and what it assumes > > Examples on this page are fragments. They render inside the provider you mounted > in the [Quickstart](/code/sdks/convex/quickstart): > > ```svelte theme={null} > > > > ``` > > If something below does not work, one of these is usually missing. Each links > straight to the step that sets it up. > > * [Component registered](/code/sdks/convex/quickstart#register-component) — `app.use(creem)` in `convex/convex.config.ts` > * [Secrets set](/code/sdks/convex/quickstart#set-secrets) — `CREEM_API_KEY` and `CREEM_WEBHOOK_SECRET` in Convex env > * [Billing API exported](/code/sdks/convex/quickstart#export-billing-api) — `convex/billing.ts` calling `creem.api({ resolve })` > * [Webhook registered](/code/sdks/convex/quickstart#register-webhook) — `creem.registerRoutes(http)` in `convex/http.ts` > * [Products created](/code/sdks/convex/quickstart#create-products) — one Creem product per plan and billing cycle > * [Products synced](/code/sdks/convex/quickstart#sync-products) — `npx convex run billing:syncBillingProducts` > * [Styles imported](/code/sdks/convex/quickstart#import-styles) — `@creem_io/convex/styles` after the Tailwind import > * [Catalog defined](/code/sdks/convex/quickstart#define-plans) — `billingCatalog` mapping plan IDs to product IDs > * [Provider mounted](/code/sdks/convex/quickstart#render-pricing-page) — `` around your billing UI ## Single owned product A product purchased once. The card shows "Owned" afterwards and suppresses repeat checkout: ```tsx title="Pricing page" theme={null} ``` ## Repeating products (consumables) `type="recurring"` allows repeat purchases and never shows an "Owned" badge. Use it for credit packs and other consumables: ```tsx title="Pricing page" theme={null} ``` ## Credit grants Credit fulfillment happens in the webhook, on the server. The purchase-to-credit mapping therefore has to live in a server-owned catalog, not in client code. Pass it to the `Creem` constructor in `convex/billing.ts`: ```ts title="convex/billing.ts" theme={null} const serverBillingCatalog = defineBillingCatalog({ version: "server", plans: [ { planId: "ai-credits-100", category: "paid", billingType: "onetime", creemProductIds: { custom: process.env.CREEM_ONETIME_CREDITS! }, creditGrant: { amount: "100", accountName: "credits", unitLabel: "credits", refundBehavior: "revoke_on_full_refund", }, }, ], } as const); export const creem = new Creem(components.creem, { billingCatalog: serverBillingCatalog, }); ``` Set the trusted product ID in Convex env (never read it from a browser-exposed variable for fulfillment): ```bash theme={null} npx convex env set CREEM_ONETIME_CREDITS prod_... ``` When a `checkout.completed` webhook arrives for that product, the component grants the credits. ### Refund behavior `creditGrant.refundBehavior` answers one question. What happens to granted credits when the product is refunded? | Value | Full refund | Partial refund | Use when | | - | - | - | - | | `"revoke_on_full_refund"` (default) | Revokes all | Revokes nothing | A purchase is only undone when fully refunded | | `"prorate"` | Revokes all | Revokes proportional share | The product is clearly divisible (credit packs) | | `"debit"` | Revokes all | Revokes all | Any refund should invalidate the whole grant | | `"none"` | Revokes none | Revokes none | Your app handles refund reversals manually | ## Displaying and spending credits `Credits.Root` renders a default balance card, or you can compose the slots yourself. Spending credits belongs in your own Convex action. The widget only displays and refreshes the balance: ```ts title="convex/billing.ts" theme={null} // App-owned spend action export const generateImage = action({ args: { requestId: v.string() }, returns: v.object({ creditsConsumed: v.string() }), handler: async (ctx, args) => { const identity = await resolve(ctx); if (!identity) throw new ConvexError("Not authenticated"); await creem.credits.debitForEntity(ctx, { entityId: identity.entityId, amount: "10", reference: "generate_image", // A stable key per logical operation. idempotencyKey: `generate_image_${args.requestId}`, }); return { creditsConsumed: "10" }; }, }); ``` > [tab] React > > ```tsx title="src/CreditsPanel.tsx" theme={null} > > {(credits) => ( > <> > > > > > > )} > > ``` > [tab] Svelte > > ```svelte title="src/routes/+page.svelte" theme={null} > > {#snippet children(credits)} > > > > > {/snippet} > > ``` ![A Credit Balance card showing 490 credits with a refresh icon and a Generate image button costing 10 credits](https://mintcdn.com/creem/IA-lLh1OWoZ0Tbxw/images/convex/credits-balance-light.webp?fit=max\&auto=format\&n=IA-lLh1OWoZ0Tbxw\&q=85\&s=527760bb98e7c26d5a478c721e42a2f8) The widget needs only `credits.getBalance` in your connected API: ```ts theme={null} const connectedApi: ConnectedBillingApi = { // Other widget capabilities... credits: { getBalance: api.billing.creditsGetBalance }, }; ``` > [!WARNING] > > Keep the spend amount, reference, and idempotency policy in the app-owned backend action. UI code > can be manipulated; the action is the enforcement point. ## Mutually exclusive products & upgrade paths When one-time products supersede each other (Basic license → Premium license), declare `transition` rules on the root. Once the user owns a lower tier, only valid upgrade paths render: ```tsx title="Pricing page" theme={null} ``` ![Two product cards side by side: Basic at \$400 marked Owned with no buy button, and Premium at \$700 offering an Upgrade button](https://mintcdn.com/creem/IA-lLh1OWoZ0Tbxw/images/convex/product-upgrade-path-light.webp?fit=max\&auto=format\&n=IA-lLh1OWoZ0Tbxw\&q=85\&s=6ae4f3c0bb5bdbd3b502efe51967a747) Two transition kinds: * **`via_product`** checks out a dedicated upgrade product, so the customer pays only the difference. * **`direct`** checks out the target product at full price. > [!NOTE] > > **Handled in your frontend today.** Transition rules are declared on `Product.Root` and applied by > the widget. One effect worth knowing: a checkout started outside the widget sells the target > product at full price, since the grouping lives in your app rather than in Creem. Prefer this > handled by Creem directly? Vote for [grouping non-subscription > products](https://creem.featurebase.app/p/group-non-subscription-products-and-expose-via-creem-api). ## What to keep in mind * `type="one-time"` is ownable, `type="recurring"` is repeatable. Choose per product. Both can live in the same `Product.Root`. * Subscription checkouts also create Creem orders, but the billing snapshot only exposes one-time orders as owned access. See [Concepts](/code/sdks/convex/concepts#the-billing-state-model). * Full `Product.Root` / `Product.Item` prop tables live in the [Reference](/code/sdks/convex/reference#component-reference). # Quickstart Source: https://docs.creem.io/code/sdks/convex/quickstart Set up Creem billing in your Convex app: backend sync, webhook, and a working subscription pricing page. `@creem_io/convex` connects your Convex backend to Creem. Webhooks keep billing state synced into your Convex database. Pre-built React and Svelte widgets handle checkout, plan switching, and cancellation. This page gets you to a working two-plan pricing page. **Before you start**, you need an existing [Convex](https://docs.convex.dev/quickstarts) project with `npx convex dev` running, and [auth configured](https://docs.convex.dev/auth) so `ctx.auth.getUserIdentity()` returns your signed-in user. Without auth, the pricing page renders - but only in its public, logged-out state, and checkout stays unavailable. > [!NOTE] > > **Integrating with an AI agent, or migrating from another billing provider?** Point it at the > [Integration Guide](/code/sdks/convex/integration). That page holds the whole setup sequence in > order, with validation steps. Agents can fetch it as raw markdown: > > ```text theme={null} > https://docs.creem.io/code/sdks/convex/integration.md > ``` ## Backend **1. Install** ```bash theme={null} npm install @creem_io/convex convex creem ``` **2. Register the component** ```ts title="convex/convex.config.ts" theme={null} import { defineApp } from "convex/server"; import creem from "@creem_io/convex/convex.config"; const app = defineApp(); app.use(creem); export default app; ``` **3. Set secrets** ```bash theme={null} npx convex env set CREEM_API_KEY npx convex env set CREEM_WEBHOOK_SECRET npx convex env set CREEM_SERVER test ``` Both keys live in the [Developers section](https://creem.io/dashboard/developers) of your dashboard. Toggle [Test Mode](/getting-started/test-mode#activating-test-mode) to get test keys. Set `CREEM_SERVER=prod` (or omit it) when you go live. **4. Export the billing API** The `resolve` callback maps your authenticated session to a billing entity. Replace it with your real auth logic: ```ts title="convex/billing.ts" theme={null} import { Creem, type ApiResolver } from "@creem_io/convex"; import { components } from "./_generated/api"; import { internalAction } from "./_generated/server"; export const creem = new Creem(components.creem); // Return `null` for an unauthenticated caller. That is what keeps public // pricing pages working. Anything thrown here counts as a real failure. const resolve: ApiResolver = async (ctx) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) return null; return { userId: identity.subject, email: identity.email!, entityId: identity.subject, // for org billing, return the org ID }; }; const { uiModel, checkouts, subscriptions, customers } = creem.api({ resolve }); export { uiModel }; export const checkoutsCreate = checkouts.create; export const subscriptionsUpdate = subscriptions.update; export const subscriptionsCancel = subscriptions.cancel; export const subscriptionsResume = subscriptions.resume; export const customersPortalUrl = customers.portalUrl; export const syncBillingProducts = internalAction({ args: {}, handler: async (ctx) => { await creem.syncProducts(ctx); }, }); ``` > [!TIP] > > Keep these export names. `connectCreemApi` on the frontend maps them onto the widget API for you. **5. Register the webhook** ```ts title="convex/http.ts" theme={null} import { httpRouter } from "convex/server"; import { creem } from "./billing"; const http = httpRouter(); creem.registerRoutes(http); export default http; ``` In your Creem dashboard, set the webhook endpoint to your **Convex site URL** plus `/creem/events`: ```text theme={null} https://.convex.site/creem/events ``` **6. Create two products** This quickstart renders a Basic and a Premium plan, so create one Creem product for each. > [tab] CLI > > [Install the CLI](/ai/for-humans/cli), then sign in with the same test key you > set in step 3: > > ```bash theme={null} > creem login --api-key creem_test_YOUR_KEY > > creem products create \ > --name "Basic" \ > --description "For small teams" \ > --price 1900 \ > --currency USD \ > --billing-type recurring \ > --billing-period every-month > > creem products create \ > --name "Premium" \ > --description "For growing teams" \ > --price 4900 \ > --currency USD \ > --billing-type recurring \ > --billing-period every-month > ``` > > Each command prints the new `prod_...` ID. `creem products list` shows them again later. > [tab] Dashboard > > Create two recurring products in the [Products section](https://creem.io/dashboard/products) > of your dashboard, then copy each product ID from its detail page. Put both IDs in your frontend env file. They are public values that the browser needs in order to start checkout: ```bash title=".env.local" theme={null} VITE_CREEM_SUB_BASIC_MONTHLY=prod_... VITE_CREEM_SUB_PREMIUM_MONTHLY=prod_... ``` > [!NOTE] > > Use whichever public prefix your framework expects: `VITE_*` for Vite, `NEXT_PUBLIC_*` for > Next.js, `PUBLIC_*` for SvelteKit. Your Creem API key is not a public value and stays in Convex > env, as set above. **7. Sync products** Pull the product metadata (names, prices, descriptions) into Convex so the widgets can render it: ```bash theme={null} npx convex run billing:syncBillingProducts ``` Billing state now syncs into Convex automatically. The backend is done. ## Frontend **1. Install UI dependencies** The widgets are built on [Ark UI](https://ark-ui.com) headless primitives. Add the adapter for your framework to your existing app: > [tab] React > > ```bash theme={null} > npm install @ark-ui/react > ``` > [tab] Svelte > > ```bash theme={null} > npm install convex-svelte @ark-ui/svelte > ``` **2. Set up Tailwind and import styles** The widgets require **Tailwind CSS v4**. If your project doesn't have it yet, follow the [Tailwind framework guide](https://tailwindcss.com/docs/installation/framework-guides). The steps differ per framework. Then add the component styles to your CSS entry point, after the Tailwind import: ```css theme={null} @import "tailwindcss"; @import "@creem_io/convex/styles"; ``` **3. Define your plans** Map stable plan IDs to your Creem product IDs: > [tab] React > > ```ts title="src/billingCatalog.ts" theme={null} > import { defineBillingCatalog } from "@creem_io/convex/react"; > > export const billingCatalog = defineBillingCatalog({ > version: "1", > plans: [ > { > planId: "basic", > category: "paid", > billingType: "recurring", > creemProductIds: { > "every-month": import.meta.env.VITE_CREEM_SUB_BASIC_MONTHLY, > }, > }, > { > planId: "premium", > category: "paid", > billingType: "recurring", > recommended: true, > creemProductIds: { > "every-month": import.meta.env.VITE_CREEM_SUB_PREMIUM_MONTHLY, > }, > }, > ], > } as const); > ``` > [tab] Svelte > > ```ts title="src/billingCatalog.ts" theme={null} > import { defineBillingCatalog } from "@creem_io/convex/svelte"; > > export const billingCatalog = defineBillingCatalog({ > version: "1", > plans: [ > { > planId: "basic", > category: "paid", > billingType: "recurring", > creemProductIds: { > "every-month": import.meta.env.VITE_CREEM_SUB_BASIC_MONTHLY, > }, > }, > { > planId: "premium", > category: "paid", > billingType: "recurring", > recommended: true, > creemProductIds: { > "every-month": import.meta.env.VITE_CREEM_SUB_PREMIUM_MONTHLY, > }, > }, > ], > } as const); > ``` `defineBillingCatalog` is the same framework-agnostic function in both entry points. It is re-exported from `/react` and `/svelte` so that browser code never has to import the server entry. Titles, descriptions, and prices come from the synced Creem product data. **4. Render the pricing page** Wrap your billing UI once in `CreemConvexProvider`. The widgets read everything from it: > [tab] React > > ```tsx title="src/PricingPage.tsx" theme={null} > import { > CreemConvexProvider, > Subscription, > BillingPortal, > connectCreemApi, > plansOf, > } from "@creem_io/convex/react"; > import { api } from "../convex/_generated/api"; > import { billingCatalog } from "./billingCatalog"; > > // Maps the exports from convex/billing.ts onto the widget API. > const connectedApi = connectCreemApi(api.billing); > > export function PricingPage() { > return ( > > > > > ); > } > ``` > [tab] Svelte > > ```svelte title="src/routes/+page.svelte" theme={null} > > > > > > > ``` You now have a pricing page with live prices and working checkout. It shows a "Current plan" badge, and handles plan switching, cancel, and resume. Convex keeps all of it in sync. Try it with a [test card](/getting-started/test-mode#testing-payments). ![Two subscription plan cards, Basic at \$50 per month and a recommended Premium at \$100 per month, each with a Subscribe button](https://mintcdn.com/creem/IA-lLh1OWoZ0Tbxw/images/convex/pricing-two-plans-light.webp?fit=max\&auto=format\&n=IA-lLh1OWoZ0Tbxw\&q=85\&s=d55f3b9dd422473f9a55649469eb1a30) ## Next steps > [card] [Subscriptions](/code/sdks/convex/subscriptions) > > Billing cycles, trials, unit-based pricing, and scheduled changes > [card] [One-Time Products & Credits](/code/sdks/convex/one-time-and-credits) > > Owned products, consumables, credit packs, and upgrade paths > [card] [Entitlements & Account UI](/code/sdks/convex/entitlements) > > Feature gating, usage limits, billing history, and payment recovery > [card] [Advanced](/code/sdks/convex/advanced) > > Custom auth/RBAC, entity model, webhook middleware, and migration # Component Reference Source: https://docs.creem.io/code/sdks/convex/reference Full reference for the Creem Convex component: backend namespaces, generated functions, the billing snapshot, and every widget prop. This page is the exhaustive reference. For task-shaped guides start with the [Quickstart](/code/sdks/convex/quickstart) and its siblings. ## Backend API ### Resource namespaces: `creem..*` All methods take explicit arguments. Use them directly in your own Convex functions, or let `creem.api({ resolve })` generate ready-to-export wrappers. **`creem.subscriptions.*`** | Method | Data source | Description | | - | - | - | | `.getCurrent(ctx, { entityId })` | Convex DB | Current active subscription with product join | | `.list(ctx, { entityId })` | Convex DB | Active subscriptions (excludes ended + expired trials) | | `.listAll(ctx, { entityId })` | Convex DB | All subscriptions including ended | | `.update(ctx, { entityId, ...SubscriptionUpdateArgs })` | Creem API / Convex scheduler | Takes the `SubscriptionUpdateArgs` union, discriminated on `kind`: `"plan"` (paid switch), `"units"` (quantity change), or `"app-plan"` (paid → free/trial/custom). Pass `subscriptionId` when several subscriptions are active. `"immediate"` is only valid for `"app-plan"`. | | `.cancelScheduledUpdate(ctx, { entityId, subscriptionId? })` | Convex DB / Creem API | Undo a pending app-side period-end update. If the pending update was a paid-to-free switch, the Creem scheduled cancellation is resumed. | | `.cancel(ctx, { entityId, revokeImmediately? })` | Creem API | Cancel subscription | | `.pause(ctx, { entityId })` | Creem API | Pause an active subscription | | `.resume(ctx, { entityId })` | Creem API | Resume a paused or scheduled-cancel subscription | Set `new Creem(components.creem, { cancelMode: "scheduled" })` to make normal cancel actions end at the paid period boundary and surface `subscription.scheduled_cancel`. Pass `revokeImmediately` on an individual cancel call when you need to override that default. **`creem.checkouts.*`** | Method | Data source | Description | | - | - | - | | `.create(ctx, { entityId, userId, email, productId, successUrl?, fallbackSuccessUrl?, units?, metadata?, theme? })` | Creem API | Create checkout URL with 3-tier `successUrl` resolution and optional `theme` | **`creem.products.*`** | Method | Data source | Description | | - | - | - | | `.list(ctx, options?)` | Convex DB | All synced products (public — no `entityId` needed) | | `.get(ctx, { productId })` | Convex DB | Single product by ID (public) | **`creem.customers.*`** | Method | Data source | Description | | - | - | - | | `.retrieve(ctx, { entityId })` | Convex DB | Customer record by entity | | `.portalUrl(ctx, { entityId })` | Creem API | Customer billing portal URL. Throws a `ConvexError` with `code: "shared-customer"` while other billing entities share the customer | | `.billingEmail(ctx, { entityId })` | Creem API | Email Creem sends invoices and receipts to: `{ status: "ok", email }` or `{ status: "no-customer" }` | | `.updateBillingEmail(ctx, { entityId, email })` | Creem API | Change that email; same result shape, plus `{ status: "shared-customer" }` without calling Creem while other entities share the customer. Reads the customer back from Creem and stores that address on the Convex customer record unless a newer readback is already stored (by Creem's `updated_at`) | | `.isShared(ctx, { entityId })` | Convex DB | Whether another billing entity is or was mapped to the entity's Creem customer, or owns one of its subscriptions or orders (Creem keeps one customer per store and email address) | **`creem.orders.*`** | Method | Data source | Description | | - | - | - | | `.list(ctx, { entityId })` | Convex DB | One-time orders | **`creem.credits.*`** Entity-scoped methods are the preferred backend API. They resolve the default credit account from a trusted billing entity and keep provider account IDs out of client arguments. | Method | Intended use | | - | - | | `.getBalanceForEntity(ctx, { entityId })` | Entity-scoped balance read | | `.listEntriesForEntity(ctx, { entityId, limit?, startingAfter? })` | Entity-scoped credit history | | `.creditForEntity(ctx, { entityId, amount, reference, idempotencyKey })` | Trusted app-owned grant or adjustment | | `.debitForEntity(ctx, { entityId, amount, reference, idempotencyKey })` | Trusted app-owned business operation | | `.createAccount(...)`, `.credit(...)`, `.debit(...)`, `.listEntries(...)` | Raw server-only Customer Credits primitives | Do not export the raw primitives directly as public Convex actions. **Composite helpers (top-level methods)** | Method | Description | | - | - | | `creem.getBillingModel(ctx, { entityId, user? })` | Aggregates the widget model into a single object for connected UI. Graceful when `entityId` is null (returns public catalog only). | | `creem.getBillingSnapshot(ctx, { entityId })` | Billing state with `subscriptions[]`, `orders[]`, `appPlanAssignments[]`, derived `access[]`, `paymentRecoveryState`, and `availableBillingActions`. | ### `creem.api({ resolve })` convenience exports Generates ready-to-export Convex function definitions. Each function calls your `resolve` callback, then delegates to the corresponding namespace method. | Export | Wraps | Type | Description | | - | - | - | - | | `uiModel` | `getBillingModel` | query | Calls `resolve()`, then `getBillingModel`. Returns the catalog-only model when `resolve` yields `null`. | | `snapshot` | `getBillingSnapshot` | query | Calls `resolve()`, then `getBillingSnapshot`. Returns `null` when `resolve` yields `null`. | | `checkouts.create` | `checkouts.create` | action | Auto-resolves auth | | `subscriptions.update` | `subscriptions.update` | mutation | Auto-resolves auth and verifies explicit subscription ownership | | `subscriptions.cancel` | `subscriptions.cancel` | mutation | Auto-resolves auth and verifies explicit subscription ownership | | `subscriptions.resume` | `subscriptions.resume` | mutation | Auto-resolves auth and verifies explicit subscription ownership | | `subscriptions.pause` | `subscriptions.pause` | mutation | Auto-resolves auth and verifies explicit subscription ownership | | `subscriptions.list` | `subscriptions.list` | query | Auto-resolves auth | | `subscriptions.listAll` | `subscriptions.listAll` | query | Auto-resolves auth | | `products.list` | `products.list` | query | Public, no auth needed | | `products.get` | `products.get` | query | Public, no auth needed | | `customers.retrieve` | `customers.retrieve` | query | Auto-resolves auth | | `customers.portalUrl` | `customers.portalUrl` | action | Auto-resolves auth | | `customers.billingEmail` | `customers.billingEmail` | action | Auto-resolves auth; args `{ expectedEntityId }`. Returns `{ status: "entity-changed" }` when the resolved entity differs | | `customers.updateBillingEmail` | `customers.updateBillingEmail` | action | Auto-resolves auth; args `{ expectedEntityId, email }`. Same `"entity-changed"` guard; nothing is changed then | | `transactions.search` | `transactions.search` | action | Derives the customer from the resolved entity and returns paginated history | | `plans.activate` | `appPlans.activate` | mutation | Enforces catalog eligibility before activation | | `orders.list` | `orders.list` | query | Auto-resolves auth | | `credits.getBalance` | `credits.getBalanceForEntity` | action | Reads the resolved entity's default credit balance | | `credits.listEntries` | `credits.listEntriesForEntity` | action | Lists the entity's default credit entries as `{ entries[], hasMore }` | `creem.api()` does not generate public credit-account creation, credit, or debit actions. Those operations must stay behind app-owned backend functions. Every generated function declares a real Convex `returns` validator, so Convex clients infer the concrete result type instead of `any`. The matching TypeScript types are derived from those validators with `Infer<>`, which is why `ConnectedBillingApi` can pin each reference's return type and reject a mis-wired export at compile time. `snapshot` and `creem.getBillingSnapshot(...)` return the backend billing snapshot: ```ts theme={null} { entityId: "org_123", catalogVersion: "2026-05", subscriptions: [ { planId: "private", productId: "prod_20GpOqRYWpSpU1pv1KCPet", subscriptionId: "sub_123", status: "active", recurringCycle: "every-year", kind: "base", units: 3, cancelAtPeriodEnd: false, currentPeriodEnd: "2026-06-18T00:00:00.000Z", }, ], orders: [ { planId: "lifetime-export", orderId: "ord_123", productId: "prod_7kP3mAqR9xT2vB6nLwY8Cs", status: "paid", }, ], appPlanAssignments: [ { entityId: "org_123", planId: "free", status: "scheduled", startsAt: "2026-06-18T00:00:00.000Z", source: "paid_to_app_plan", subscriptionId: "sub_123", createdAt: "2026-05-18T00:00:00.000Z", updatedAt: "2026-05-18T00:00:00.000Z", }, ], access: [ { source: "creem_subscription", kind: "subscription", planId: "private", productId: "prod_20GpOqRYWpSpU1pv1KCPet", subscriptionId: "sub_123", status: "active", recurringCycle: "every-year", }, { source: "creem_order", kind: "one_time", planId: "lifetime-export", productId: "prod_7kP3mAqR9xT2vB6nLwY8Cs", orderId: "ord_123", status: "paid", }, ], paymentRecoveryState: "none", availableBillingActions: ["portal", "cancel"], resolvedAt: "2026-05-18T00:00:00.000Z", } ``` Mental model: * `subscriptions` mirrors Creem recurring subscriptions and supports multiple simultaneous rows, such as a base subscription plus add-ons. * `orders` mirrors Creem orders. Subscription checkouts also create orders, but the snapshot only exposes one-time orders as owned one-time access. * `appPlanAssignments` stores Convex-Creem-owned current or scheduled app-owned plans such as free plans, no-card trials, and custom internal plans. * `access` is a derived read model that combines active subscriptions, paid one-time orders, and active app-plan assignments. It is not a separate table and should not be treated as the source of truth. ### Infrastructure | Method | Description | | - | - | | `creem.syncProducts(ctx)` | Pull products from Creem API into Convex DB | | `creem.registerRoutes(http, { path?, events? })` | Register webhook HTTP routes | ### Direct API access with `creem.sdk.*` The resource namespaces above cover all **billing features that stay in sync** with Convex via webhooks. Some Creem API resources have no webhook support, so the component cannot mirror them in Convex DB. For these, use `creem.sdk.*` directly inside your own Convex actions. It is the same Creem SDK client, already configured with your API key: | Resource | Synced to Convex? | Access | | - | - | - | | Subscriptions | Yes (webhook) | `creem.subscriptions.*` | | Checkouts | Yes (webhook) | `creem.checkouts.*` | | Products | Yes (webhook + sync) | `creem.products.*` | | Customers | Yes (webhook) | `creem.customers.*` | | Orders | Yes (webhook) | `creem.orders.*` | | **Licenses** | No webhook | `creem.sdk.licenses.*` | | **Discounts** | No webhook | `creem.sdk.discounts.*` | | **Transactions** | No webhook | `creem.sdk.transactions.*` | ```ts theme={null} import { action } from "./_generated/server"; import { v } from "convex/values"; // Example: create a discount (not synced, since Creem has no webhook for discounts) export const createDiscount = action({ args: { code: v.string(), percentage: v.number() }, handler: async (ctx, args) => { return await creem.sdk.discounts.create({ name: args.code, code: args.code, type: "percentage", percentage: args.percentage, duration: "forever", appliesTo: [], }); }, }); ``` *** ## Component Reference All components share **identical props** across Svelte and React. * **Import:** `@creem_io/convex/svelte` or `@creem_io/convex/react` * **CSS class prop:** `class` in Svelte, `className` in React * **Children:** Svelte `Snippet` / React `ReactNode` * **Svelte** components use Svelte 5 runes and snippet rendering (`{@render ...}`) See the [Svelte example](https://github.com/armitage-labs/creem/tree/main/packages/integrations/convex/example-svelte) and [React example](https://github.com/armitage-labs/creem/tree/main/packages/integrations/convex/example-react) for complete integrations. The components below read the provider and talk to Convex directly. Everything under [Billing state components](#billing-state-components), plus `` below, takes plain props instead. ### `` Required context boundary for connected widgets. Render it around any `Subscription`, `Product`, `BillingPortal`, `BillingHistory`, or `Credits` widgets. | Prop | Type | Default | Description | | - | - | - | - | | `api` | `ConnectedBillingApi` | — | **Required.** Connected Convex function references. Build it with `connectCreemApi(api.billing)`. | | `catalog` | `PlanCatalog` | — | App-owned billing catalog used by subscription widgets and plan helpers | | `defaultCycle` | `RecurringCycle` | — | Default billing cycle for subscription widgets | | `permissions` | `BillingPermissions` | enabled | Provider-level UI permission flags. Enforce real authorization server-side | | `onBeforeCheckout` | `(intent: CheckoutIntent) => Promise \| boolean` | — | Provider-level checkout guard. Return `false` to abort | | `onBeforePlanChange` | `(intent: PlanChangeIntent) => Promise \| boolean` | — | Provider-level paid plan switch/unit update guard. Return `false` to abort | | `onBeforePlanActivation` | `(intent: { planId: string }) => Promise \| boolean` | — | Provider-level app-owned plan activation guard. Return `false` to abort | | `i18n` | `BillingI18n` | default | Locale, label, date, and currency formatter overrides | | `children` | `Snippet` / `ReactNode` | — | Connected billing UI | Connected widgets no longer accept direct `api={...}` props. Pass the API to `CreemConvexProvider` once. `createCreemReact` / `createCreemSvelte` return a spreadable binding: ``. ### `` The subscription namespace. `Subscription.Root` owns billing state and actions; everything else registers a plan or renders a slot inside it. It is a plain namespace object, so render `` or ``, never a bare ``. #### `` Container for subscription plan cards. Handles billing cycle toggle, checkout, plan switching, cancellation, and unit management. | Prop | Type | Default | Description | | - | - | - | - | | `catalog` | `PlanCatalog` | provider catalog | Local catalog override | | `plans` | `readonly string[]` | — | Catalog plan IDs rendered by the default pricing layout | | `groups` | `SubscriptionGroupRegistration[]` | — | Grouped plan definitions for audience selectors, e.g. Individual vs Teams | | `defaultGroup` | `string` | first group | Initial uncontrolled group value | | `group` | `string` | — | Controlled group value | | `onGroupChange` | `(group: string) => void` | — | Called when the active group changes | | `groupSelector` | `"auto" \| "hidden" \| "external"` | `"auto"` | Group selector placement | | `defaultCycle` | `RecurringCycle` | provider default → `"every-month"` | Initial uncontrolled billing cycle | | `cycle` | `RecurringCycle` | — | Controlled billing cycle | | `onCycleChange` | `(cycle: RecurringCycle) => void` | — | Called when the active billing cycle changes | | `intervalSelector` | `"auto" \| "hidden" \| "external"` | `"auto"` | Interval selector placement. `"auto"` renders it for you in both default and composed layouts; use `"external"` to place `Subscription.IntervalSelector` yourself | | `cycleBadges` | `Partial>` | — | Optional badges next to billing interval labels, e.g. `{ "every-year": "-20%" }` | | `permissions` | `BillingPermissions` | provider permissions | Local UI permission overrides | | `class`/`className` | `string` | `""` | Wrapper CSS class | | `successUrl` | `string` | product's `defaultSuccessUrl` → current page | Override redirect after checkout. When omitted, uses the product's `defaultSuccessUrl` from Creem; if that is also unset, falls back to the current page. | | `units` | `number` | — | Auto-derived unit count for unit-based plans | | `showUnitPicker` | `boolean` | `false` | Show quantity picker on unit-based cards | | `columns` | `"auto" \| 1 \| 2 \| 3 \| 4` | `"auto"` | Preferred pricing card columns. `"auto"` derives the layout from visible plan count and plan type. | | `updateBehavior` | `UpdateBehavior \| ((intent: UpdateBehaviorIntent) => UpdateBehavior)` | `"proration-charge-immediately"` | Paid subscription update behavior for paid-to-paid plan switches and unit changes. | | `appPlanUpdateBehavior` | `AppPlanUpdateBehavior \| ((intent: AppPlanUpdateBehaviorIntent) => AppPlanUpdateBehavior)` | `"period-end"` | Cancellation behavior for paid-to-app-owned plan switches. | | `unstyled` | `boolean` | `false` | Remove built-in visual classes from compound subscription pieces so custom children own their styling. | | `onBeforeCheckout` | `(intent: CheckoutIntent) => Promise \| boolean` | provider guard | Local checkout guard. Return `false` to abort | | `onBeforePlanChange` | `(intent: PlanChangeIntent) => Promise \| boolean` | provider guard | Local plan switch/unit update guard. Return `false` to abort | | `onBeforePlanActivation` | `(intent: { planId: string }) => Promise \| boolean` | provider guard | Local app-owned plan activation guard. Return `false` to abort | | `labels` | `BillingLabelOverrides` | provider labels | Override subscription labels locally for this root | | `i18n` | `BillingI18n` | provider i18n | Override locale, labels, or formatters locally for this root | | `children` | `Snippet` / `ReactNode` | default cards | Compound subscription markup. When omitted, default pricing cards render | Use `unstyled` when composing your own pricing cards with `Subscription.Grid`, `Subscription.ItemTitle`, `Subscription.ItemPrice`, `Subscription.ItemDescription`, `Subscription.ItemBadge`, `Subscription.ItemCTA`, `Subscription.ItemPriceCaption`, `Subscription.UnitPicker`, `Subscription.Cancel`, `Subscription.GroupSelector`, or `Subscription.IntervalSelector`. The default generated pricing cards remain the fast styled path. Styled compound defaults use the package's `creem-base:` Tailwind variant, which places library defaults in the base cascade layer. Consumer `class`/`className` utilities like `font-bold`, `text-xl`, or `bg-emerald-600` therefore override the built-in defaults without `tailwind-merge`. **`UpdateBehavior`** controls paid subscription updates: * `"proration-charge-immediately"` prorates and charges the difference now. This is the default. * `"proration-charge"` prorates and charges on the next invoice. * `"proration-none"` skips proration; the change takes effect on the next billing cycle. * `"period-end"` keeps the current subscription active until `currentPeriodEnd`, then applies the target plan or unit count from a scheduled Convex job. The first three values map directly to Creem's paid subscription update behavior. `updateBehavior` intentionally does not include `"immediate"` because Creem paid-to-paid switches cannot be immediate cancellation. **`AppPlanUpdateBehavior`** controls paid-to-app-owned target switches: * `"period-end"` schedules Creem cancellation for the billing period boundary, then activates the app-owned target plan at that time. This is the default. * `"immediate"` calls Creem cancellation with `mode: "immediate"` and assigns the app-owned plan straight away. Paid-to-app-owned is a cancellation flow because the target entitlement is fulfilled by your app rather than Creem. Use `appPlanUpdateBehavior`, not `updateBehavior`, when you want to choose between period-end and immediate cancellation. Until Creem supports native scheduled subscription updates, the Creem customer portal will still show the current subscription as active and will not know about pending app-side paid-to-free assignment. Use a resolver function when upgrades and downgrades should behave differently: ```tsx theme={null} { if (intent.fromPrice != null && intent.toPrice != null && intent.toPrice < intent.fromPrice) { return "period-end"; } return "proration-charge"; }} appPlanUpdateBehavior="period-end" /> ``` #### `` Registers a plan inside ``. Without children it registers only, and the root renders the default pricing card. With children it becomes the card wrapper and provides the item context that every `Subscription.Item*` slot reads. Slots placed outside an item throw. | Prop | Type | Default | Description | | - | - | - | - | | `type` | `"free" \| "single" \| "unit-based" \| "enterprise"` | inferred from catalog | Plan type. Optional — the catalog entry supplies category and billing type when omitted. | | `planId` | `string` | first product ID or `type` | Unique plan identifier | | `groupId` | `string` | — | Optional pricing audience/group such as `"individual"` or `"teams"` | | `groupTitle` | `string` | formatted `groupId` | Optional label for the root group selector | | `title` | `string` | from Creem product data | Plan display title | | `description` | `string` | from Creem product data | Plan subtitle (rendered as Markdown) | | `contactUrl` | `string` | — | "Contact sales" link. **Required when `type="enterprise"`**. | | `recommended` | `boolean` | `false` | Highlight as recommended plan | | `productIds` | `Partial>` | — | Creem product IDs keyed by billing cycle. Migration escape hatch when no catalog is provided. | | `class`/`className` | `string` | `""` | Card CSS class. Applied to the card wrapper in composition mode. | | `children` | `Snippet` / `ReactNode` | — | Composed card markup. Required for slot components — every slot reads this item's context. | **Supported billing cycles:** `every-month`, `every-three-months`, `every-six-months`, `every-year`. #### `` Layout wrapper for custom composed subscription cards. | Prop | Type | Default | Description | | - | - | - | - | | `class`/`className` | `string` | `""` | Grid CSS class | | `children` | `Snippet` / `ReactNode` | — | Subscription items | #### `` Conditional group wrapper for custom composed subscription sections. | Prop | Type | Default | Description | | - | - | - | - | | `value` | `string` | — | Group ID this block renders for | | `label` | `string` | — | Group label, retained for symmetry | | `children` | `Snippet` / `ReactNode` | — | Rendered when this group is active | #### `` Group selector for `groupSelector="external"` composition. | Prop | Type | Default | Description | | - | - | - | - | | `items` | `{ value: string; label: string }[]` | root groups | Selector items | | `value` | `string \| null` | root active group | Controlled selected group | | `onValueChange` | `(value: string) => void` | root group setter | Group change handler | | `class`/`className` | `string` | `""` | Wrapper CSS class | #### `` Billing-cycle selector for `intervalSelector="external"` composition. | Prop | Type | Default | Description | | - | - | - | - | | `cycles` | `RecurringCycle[]` | root active cycles | Available billing cycles | | `value` | `RecurringCycle` | root selected cycle | Controlled selected cycle | | `onValueChange` | `(cycle: RecurringCycle) => void` | root cycle setter | Cycle change handler | | `cycleBadges` | `Partial>` | root badges | Optional badges next to interval labels | | `class`/`className` | `string` | `""` | Wrapper CSS class | #### `` Secondary price text for inherited unit quantities, such as `$30/mo × 3 units`. Pair it with `` when a custom card should show the total bill as the primary price and the unit calculation as supporting text. #### ``, ``, and `` Text slots for custom subscription cards. Each resolves its value from the current `Subscription.Item` context. | Prop | Type | Default | Description | | - | - | - | - | | `class`/`className` | `string` | `""` | Text CSS class | `Subscription.ItemPriceCaption` accepts the same `class`/`className` prop. #### `` Composable quantity control for unit-based plans. Use it inside a custom `` when your card owns the markup. For inactive unit plans it updates the checkout quantity; for the active unit plan it renders the change/update flow when subscription unit updates are available. Pass `detailed` to also show the current subscribed quantity above the change button. It returns `null` on switch-plan cards so the current subscribed quantity is not mistaken for a target quantity. In `unstyled` mode, pass `class`/`className` plus slot classes such as `rowClass`, `labelClass`, `actionsClass`, `secondaryClass`, `primaryClass`, and `numberInputClass` in Svelte. React uses the same names with `Name` suffixes, for example `rowClassName` and `primaryClassName`. | Prop | Type | Default | Description | | - | - | - | - | | `class`/`className` | `string` | `""` | Wrapper CSS class | | `rowClass`/`rowClassName` | `string` | `""` | Label/input row class | | `labelClass`/`labelClassName` | `string` | `""` | Unit label class | | `actionsClass`/`actionsClassName` | `string` | `""` | Edit action row class | | `secondaryClass`/`secondaryClassName` | `string` | `""` | Secondary button class | | `primaryClass`/`primaryClassName` | `string` | `""` | Primary update button class | | `numberInputClass`/`numberInputClassName` | `string` | `""` | Number input class | | `label` | `string` | i18n | Unit label override | | `changeLabel` | `string` | i18n | Change button label override | | `updateLabel` | `string` | i18n | Update button label override | | `cancelLabel` | `string` | i18n | Cancel button label override | | `detailed` | `boolean` | `false` | Show current subscribed quantity before editing | #### `` Composable subscription action button. | Prop | Type | Default | Description | | - | - | - | - | | `class`/`className` | `string` | `""` | Button CSS class | | `activeLabel` | `string` | i18n | Current-plan label override | | `checkoutLabel` | `string` | i18n | Checkout label override | | `switchLabel` | `string` | i18n | Switch-plan label override | #### `` Composable badge for current/recommended/custom plan labels. | Prop | Type | Default | Description | | - | - | - | - | | `label` | `string` | current/recommended | Badge label override | | `class`/`className` | `string` | `""` | Badge CSS class | | `children` | `Snippet` / `ReactNode` | — | Custom badge content | #### `` Composable cancel button for the active subscription card. It opens the same root-owned confirmation dialog as the default pricing card, and renders nothing when the card is not active or cancellation is unavailable. | Prop | Type | Default | Description | | - | - | - | - | | `class`/`className` | `string` | `""` | Button CSS class | | `label` | `string` | i18n | Cancel button label override | ### `` The one-time and repeating product namespace. `Product.Root` owns ownership tracking, upgrade transitions, and checkout; `Product.Item` registers a product inside it. #### `` Container for one-time or repeating product cards. Handles ownership tracking, upgrade transitions, and checkout. | Prop | Type | Default | Description | | - | - | - | - | | `permissions` | `BillingPermissions` | provider permissions | Local UI permission overrides | | `transition` | `Transition[]` | `[]` | Upgrade path rules between products | | `class`/`className` | `string` | `""` | Wrapper CSS class | | `layout` | `"default" \| "single"` | `"default"` | Card layout mode | | `styleVariant` | `"legacy" \| "pricing"` | `"legacy"` | Visual style variant | | `showImages` | `boolean` | `false` | Show product images on cards | | `pricingCtaVariant` | `"filled" \| "faded"` | `"faded"` | Call-to-action button style | | `successUrl` | `string` | product's `defaultSuccessUrl` → current page | Override redirect after checkout. When omitted, uses the product's `defaultSuccessUrl` from Creem; if that is also unset, falls back to the current page. | | `onBeforeCheckout` | `(intent: CheckoutIntent) => Promise \| boolean` | — | Gate checkout (auth, terms, etc.). Return `false` to abort. | | `children` | `Snippet` / `ReactNode` | — | `` children | **Transition types:** ```ts theme={null} type Transition = | { from: string; to: string; kind: "direct" } | { from: string; to: string; kind: "via_product"; viaProductId: string }; ``` #### `` Registers a product inside ``. | Prop | Type | Default | Description | | - | - | - | - | | `productId` | `string` | — | **Required.** Creem product ID | | `type` | `"one-time" \| "recurring"` | — | **Required.** One-time shows "Owned" badge after purchase | | `title` | `string` | from Creem product data | Card display title | | `description` | `string` | from Creem product data | Card subtitle (rendered as Markdown) | ### `` Button that opens the Creem customer billing portal. Auto-hides when the billing entity has no Creem customer record, or when `canAccessPortal` is `false`. | Prop | Type | Default | Description | | - | - | - | - | | `permissions` | `BillingPermissions` | provider permissions | Control portal access (e.g. `{ canAccessPortal: false }`) | | `class`/`className` | `string` | `""` | Button CSS class | | `children` | `Snippet` / `ReactNode` | `"Manage billing"` | Custom button label | ### `` Form that shows and changes the email address Creem sends invoices and receipts to. Auto-hides when the billing entity has no Creem customer record, when `canManageBillingEmail` is `false`, or when `customers.billingEmail` and `customers.updateBillingEmail` are not both in the connected API. Save stays disabled until the input holds a valid address that differs from the current one. A failed load shows a "Try again" button. Labels live under `billingEmail` in the i18n labels. The widget sends the entity it displays (`uiModel.snapshot.entityId`) as `expectedEntityId`. When the resolver has moved to another entity in the meantime, the actions answer `"entity-changed"` without touching Creem, and the widget reloads instead of saving one organization's address into another. When other billing entities share the entity's Creem customer, a save is refused with `"shared-customer"` and the form shows the `sharedCustomer` label instead of changing an address the other entities use. `` is the same component as ``. Without children it renders the default layout; with children it renders a `
` around your layout and provides the state to the parts below. | Prop | Type | Default | Description | | - | - | - | - | | `permissions` | `BillingPermissions` | provider permissions | Hide the form (e.g. `{ canManageBillingEmail: false }`) | | `unstyled` | `boolean` | `false` | Drop the default classes of the root and every part | | `class`/`className` | `string` | `""` | Added to the form's default classes | | `children` | parts / `ReactNode` / `Snippet<[context]>` | default layout | Custom layout; React also accepts `(context) => ReactNode` | Other props are forwarded to the ``. **Parts.** Each part must be rendered inside `BillingEmail.Root` and throws otherwise. `class`/`className` is added to the part's default classes (which sit in a lower CSS layer, so your utilities win); other props are forwarded to the element, except the ones the root wires. | Part | Element | Wiring | | - | - | - | | `BillingEmail.Title` | `

` | Names the form through `aria-labelledby` | | `BillingEmail.Description` | `

` | Referenced by the input's `aria-describedby` | | `BillingEmail.Label` | `

  • **Upload your logo** (used on checkout and email receipts)
  • **Select your default checkout theme** (light or dark)
  • **Pick your accent color** (used for buttons, upsells, and field borders)
  • **Set your accent hover color** (for button hover states)
  • **Choose your text color** (for dynamic buttons and component text)
**4. Save and Preview** Save your changes. You can preview your checkout with the new branding instantly. ![Creem branding settings UI with logo upload and color pickers](https://nucn5fajkcc6sgrd.public.blob.vercel-storage.com/Screenshot%202025-05-07%20at%2022.55.01-7k1fgfuPbZHiOKxelfiAjYJNXZHEXB.png) Branding settings UI ## Test Mode vs Live Mode You can safely experiment with different branding options in [Test Mode](/getting-started/test-mode). These changes won't affect your live checkout. When you're ready, switch to live mode and apply your final branding for real customers. ## Programmatic Theme Selection You can override the default checkout theme by appending `?theme=light` or `?theme=dark` to your checkout URL before redirecting your customers. > [!TIP] > > Example: > > `https://www.creem.io/payment/prod_3pcofZ4pTXtuvdDb1j2MMp?theme=dark` > [card] [All Payment Link Parameters](/features/checkout/checkout-link#3-customize-with-url-parameters) > > See the full list of URL parameters you can use with payment links, including discount codes and metadata. ## Best Practices * Use a high-contrast logo with a transparent background for best results * Choose accessible color combinations for text and buttons * Preview your checkout and email receipts in both light and dark themes * Test your branding in test mode before going live **Need help?** Reach out to our support team for guidance on branding best practices or troubleshooting. # Checkout Link Source: https://docs.creem.io/features/checkout/checkout-link Learn how to receive payments without any code ## Prerequisites To get the most out of this guide, you'll need to: * **Create an account on Creem.io** * **Have your API key ready** ## 1. Create a product Go over to the [products tab](https://creem.io/dashboard/products) and create a product. You can add a name, description, and price to your product. Optionally you can also add a picture to your product that will be shown to users. > [accordion] Product page > > ![](https://nucn5fajkcc6sgrd.public.blob.vercel-storage.com/add-product-B0Khh16pSFp3DpwsuBrrExvlwovhMq.png) > [accordion] Adding product details > > ![](https://nucn5fajkcc6sgrd.public.blob.vercel-storage.com/Screenshot%202024-10-03%20at%2015.51.45-arQ1KogX03W1cGCmTgMBSJFd8d8QYR.png) ## 2. Copy the payment link from the product After successfully creating your product, you can copy the payment link by clicking on the product Share button. Simply send this link to your users and they will be able to pay you instantly. ## 3. Customize with URL parameters Payment links support query parameters that let you customize the checkout experience without any code. Append them to your payment link URL: ``` https://creem.io/payment/prod_xxxxx?discount_code=LAUNCH50&theme=dark ``` ### Available parameters | Parameter | Example | Description | | - | - | - | | `discount_code` | `?discount_code=LAUNCH50` | Pre-applies a discount code to the checkout. The discount is validated and applied server-side when the checkout session is created. | | `theme` | `?theme=dark` | Sets the checkout theme to `light` or `dark`, overriding your store's default branding theme. | | `metadata[key]` | `?metadata[source]=twitter&metadata[campaign]=launch` | Passes custom metadata key-value pairs to the checkout session. Metadata is included in webhook events and can be retrieved via the API. Use bracket notation for each key. | > [!TIP] > > You can combine multiple parameters: `?discount_code=SAVE20&theme=dark&metadata[source]=email` > [!NOTE] > > Parameters like `discount_code` and `metadata` are processed server-side and won't appear in the final checkout URL. The `theme` parameter and any other unrecognized parameters are forwarded to the checkout page as query strings. ### More use cases If you are not planning to do a no-code integration, we strongly encourage you to check out our other guides. Create checkout-sessions and prices dynamically, use webhooks to receive updates on your application automatically, and much more. Check out our guides to get the most out of Creem. > [card] [Checkout API](/features/checkout/checkout-api) > > Learn how to create and manage checkout sessions programmatically using the > Creem API. > [card] [Webhooks and Events](/code/webhooks) > > Set up webhooks to receive updates on your application automatically. # Checkout Localization Source: https://docs.creem.io/features/checkout/checkout-localization Provide a native language checkout experience with automatic language detection and support for 42 languages worldwide. Creem automatically localizes your checkout interface to match your customer's language, helping you reach a global audience and increase conversion rates through familiar, native-language interactions. > [!NOTE] > > Localization applies only to the checkout interface elements (form labels, > buttons, validation messages, payment UI). Your product names, descriptions, > and other store content remain as you've entered them. ## Supported Languages Creem supports 42 languages and regional variants, ensuring comprehensive global coverage: ### European Languages Bulgarian, Croatian, Czech, Danish, Dutch, English, Estonian, Finnish, French, German, Greek, Hungarian, Italian, Latvian, Lithuanian, Maltese, Norwegian (Bokmål), Polish, Portuguese, Romanian, Russian, Slovak, Slovenian, Spanish, Swedish ### Regional Variants * **English:** English (US), English (UK) * **Spanish:** Spanish (Spain), Spanish (Latin America) * **French:** French (France), French (Canada) * **Portuguese:** Portuguese (Portugal), Portuguese (Brazil) * **Chinese:** Simplified Chinese, Traditional Chinese (Hong Kong), Traditional Chinese (Taiwan) ### Asian Languages Chinese (Simplified and Traditional), Filipino, Indonesian, Japanese, Korean, Malay, Thai, Turkish, Vietnamese ## How It Works **Automatic Detection:** Creem detects the customer's browser language on first visit. If supported, the checkout displays in that language; otherwise, it defaults to English. **Manual Override:** Customers can change languages using the language switcher in the checkout interface. Their preference is saved and persists across sessions. **What's Localized:** * Form labels and placeholders * Validation and error messages * Button text and calls-to-action * Payment interface elements * Order summary sections ## Fallback Behavior * **Unsupported languages:** Defaults to English * **Missing translations:** English text shown for incomplete translations * **Partial browser support:** Closest supported language variant is selected ## Testing Test different languages in [Test Mode](/getting-started/test-mode) by changing your browser's language preference or using the language switcher in the checkout interface. ## Frequently Asked Questions > [accordion] Can I customize or disable certain languages? > > All 42 supported languages are automatically available to ensure the widest > reach. Localization cannot be customized or disabled. > [accordion] Are product names and descriptions localized? > > No, only the checkout interface is localized. Your product names, > descriptions, and other store content remain as you enter them. # Embedded Checkout Source: https://docs.creem.io/features/checkout/embedded-checkout Embed Creem checkout directly in your site — as a modal overlay or inline — without redirecting customers away. Embedded checkout runs the entire Creem payment flow **inside your own site** instead of sending customers to a hosted page. Drop in a small script, open checkout as a modal or inline iframe, and get a callback when payment completes. ![Creem embedded checkout as a modal overlay on a merchant's site](https://nucn5fajkcc6sgrd.public.blob.vercel-storage.com/embed-checkout-4sSl5sCtTb30kDoLuhCZHtZaW1qPp4.png) Creem embedded checkout shown as a modal overlay on a merchant's site ## How it works 1. Create a **checkout session** on your server with your secret API key (see [Checkout API](/features/checkout/checkout-api)) and read its `checkoutUrl`. 2. Load the Creem embed script on your page. 3. Open the checkout as an overlay or inline, and handle `onComplete`. > [!TIP] > > You create the session server-side (secret key) and pass the resulting URL to the browser — the URL is safe to expose, and completion is always confirmed server-side via webhook. ## 1. Create a checkout session (server-side) Every embed needs a **checkout URL**, created on your server with your secret API key so the price and product can't be tampered with. Use the [Checkout API](/features/checkout/checkout-api) or one of its SDKs and read `checkoutUrl` (the raw REST API returns it as `checkout_url`): ```ts theme={null} // Server-side only — keep CREEM_API_KEY secret import { createCreem } from 'creem_io'; const creem = createCreem({ apiKey: process.env.CREEM_API_KEY! }); const checkout = await creem.checkouts.create({ productId: 'prod_YOUR_PRODUCT_ID', successUrl: 'https://yoursite.com/success', // optional }); // `checkoutUrl` is typed as optional in the SDK — assert (or guard) it: const checkoutUrl = checkout.checkoutUrl!; // Send `checkoutUrl` to the browser, then embed it (below). ``` Then embed that URL with **a framework SDK**, the **script loader**, or a **raw iframe** — pick one. ## 2. Choose an embed path Use exactly **one** of the three paths below — framework SDKs, the script loader, or a raw iframe. ### Framework SDKs First-class packages for **React (≥18), Vue (≥3), and Svelte (≥4)** with typed props and lifecycle events. They share a framework-agnostic core, [`@creem_io/embed`](https://www.npmjs.com/package/@creem_io/embed), which you can also use directly in vanilla JS. > [tab] React > > ```bash npm theme={null} > npm install @creem_io/react > ``` > > ```bash yarn theme={null} > yarn add @creem_io/react > ``` > > ```bash pnpm theme={null} > pnpm add @creem_io/react > ``` > > ```bash bun theme={null} > bun add @creem_io/react > ``` > > ```tsx theme={null} > import { CreemCheckout, CreemCheckoutInline } from '@creem_io/react'; > > // Overlay — wrap any clickable element > console.log('paid', d)}> > > > > // Inline — mount in place > checkoutUrl={checkoutUrl} > onComplete={onComplete} > style={{ width: 460, height: 820 }} > /> > ``` > > Also available: the `useCreemCheckout()` hook and the `CreemEmbedCheckout.create()` promise API. [Full reference →](https://www.npmjs.com/package/@creem_io/react) > [tab] Vue > > ```bash npm theme={null} > npm install @creem_io/vue > ``` > > ```bash yarn theme={null} > yarn add @creem_io/vue > ``` > > ```bash pnpm theme={null} > pnpm add @creem_io/vue > ``` > > ```bash bun theme={null} > bun add @creem_io/vue > ``` > > ```vue theme={null} > > > > ``` > > Also available: the `useCreemCheckout()` composable and `CreemEmbedCheckout.create()`. [Full reference →](https://www.npmjs.com/package/@creem_io/vue) > [tab] Svelte > > ```bash npm theme={null} > npm install @creem_io/svelte > ``` > > ```bash yarn theme={null} > yarn add @creem_io/svelte > ``` > > ```bash pnpm theme={null} > pnpm add @creem_io/svelte > ``` > > ```bash bun theme={null} > bun add @creem_io/svelte > ``` > > ```svelte theme={null} > > > > > > > > > > ``` > > Low-level: the `{@attach}` attachments (Svelte 5.29+) or `use:` actions (Svelte 4). [Full reference →](https://www.npmjs.com/package/@creem_io/svelte) Every SDK takes the same options as the loader below (`theme`, `locale`) and emits the same `ready` + `completed` events. On completion the embed behaves exactly like the hosted checkout's return page: * **Product has a Return URL** → a short confirmation screen, then the top window navigates there (\~3s). * **No Return URL** → a "View order" button; the embed stays open until the customer closes it. To keep customers fully inline, call `close()` inside `onComplete` — it dismisses the embed **and cancels the pending redirect**. Cancelling the redirect from `close()` requires `@creem_io/embed` ≥ 0.3.3 (or `@creem_io/react` / `/vue` / `/svelte` ≥ 0.2.3); on older versions `close()` dismisses the modal but the redirect still fires. ![Embedded checkout success screen: 'Thank you for your payment' with a 'Returning to Merchant in 2s' countdown button](https://nucn5fajkcc6sgrd.public.blob.vercel-storage.com/embed-completion-return-url.png) Product has a Return URL — a confirmation screen with a 'Returning to Merchant' countdown, then the redirect. ![Embedded checkout success screen: 'Thank you for your payment' with a 'View Order' button](https://nucn5fajkcc6sgrd.public.blob.vercel-storage.com/embed-completion-view-order.png) No Return URL — a 'View order' button; the embed stays open until the customer closes it (or you call close() in onComplete). #### Open on click (dynamic sessions) The components above need the `checkoutUrl` at render time. For a **pricing grid** — many products, where you don't want to pre-create a session for each one on page load — create the session **on demand** and open it imperatively with the `useCreemCheckout()` hook: ```tsx theme={null} import { useCreemCheckout } from '@creem_io/react'; function BuyButton({ productId }: { productId: string }) { const openCheckout = useCreemCheckout(); async function buy() { // Create the session on YOUR server (keeps the secret key off the client), // then open the returned URL — no need to pre-create sessions on load. const res = await fetch('/api/checkout', { method: 'POST', body: JSON.stringify({ productId }), }); const { checkoutUrl } = await res.json(); openCheckout({ checkoutUrl, onComplete: (detail) => console.log('paid', detail) }); } return ; } ``` Vue exposes the same `useCreemCheckout()` composable. In vanilla JS (or any framework), use the promise-based `CreemEmbedCheckout.create({ checkoutUrl })`, which resolves once the checkout has rendered. ### Script loader For non-framework apps, or when you want a global `Creem` object. No build step — drop in the loader script and open checkout from any framework or plain HTML. #### Overlay **1. Add the script** ```html theme={null} ``` **2. Open checkout on click** ```html theme={null} ``` The overlay shows the confirmation screen on success; call `Creem.close()` from `onComplete` to dismiss it — this also **cancels the pending redirect** to the Return URL, keeping the customer on your page. #### Inline Mount checkout inside a container on your page: ```html theme={null}
``` > [!WARNING] > > **`onComplete` is UX-only.** It fires in the browser and can be spoofed — use it to close the modal or show a success state. Grant entitlements / fulfil orders from your **[webhook handler](/code/webhooks)** (verified server-side), never from `onComplete`. #### Declarative data attributes Any element with `data-creem-checkout` opens the overlay on click — no JS wiring, but it still relies on the loader script above: ```html theme={null} Buy now ``` Optionally set the theme and language with `data-creem-theme` and `data-creem-locale`: ```html theme={null} Buy now ``` ### Raw iframe The lowest-level option — no loader, no SDK. Use it when you only need inline display and will handle the lifecycle yourself, or don't need callbacks: ```html theme={null} ``` > [!WARNING] > > The `allow="payment *; publickey-credentials-get *"` attribute is required — without it, digital wallets, passkeys, and 3-D Secure challenges can't run inside the iframe. (The framework SDKs and the script loader set this for you.) ## Presentation — theme & language Works with the framework SDKs and the script loader. `openCheckout` and `mount` accept two presentation options, appended to the checkout URL for you: ```js theme={null} Creem.openCheckout({ checkoutUrl: 'CHECKOUT_URL', theme: 'dark', // 'light' | 'dark' locale: 'pt-BR', // BCP47 tag — forces the checkout language }); ``` By default the checkout follows the customer's **browser language**. Pass `locale` to force a specific one (e.g. to match your own site's language). Unsupported locales fall back to English. See the [supported languages](/features/checkout/checkout-api) for the full list. ## Affiliate attribution If you run the Creem [Affiliate Program](/features/affiliate-program), embedded checkout still credits referred sales to the right affiliate — and the SDKs and script loader handle it for you. Here's what happens, and the one edge case worth knowing. **How it works** * An affiliate link (`creem.io/affiliate?code=…`) sends the visitor to your site and appends a `creem_ref` token to the landing URL. * On the **hosted** checkout, attribution rides a first-party cookie on Creem's domain — nothing to do. * Inside the **embed**, the checkout runs in a cross-site iframe, so the browser doesn't send that cookie there — in any browser. Attribution instead rides the token: the SDK/loader reads `creem_ref` from your page, **persists it in your site's own first-party storage**, and forwards it into the checkout iframe, so it works uniformly everywhere. No code needed for the common case. > [!NOTE] > > `creem_ref` is an **opaque, signed token** — it identifies the click, not the affiliate. Don't try to parse an affiliate code out of it, and you don't need to read or forward it yourself: the SDKs and loader do it automatically. (It mirrors `client_reference_id` in Stripe-based tools like Rewardful and Tolt.) **Edge case: separate landing and checkout pages** The token arrives on whatever page the affiliate link points to. The SDK captures it automatically when it runs on that page. But if a visitor lands on `/?creem_ref=…`, then **navigates** to another page (say `/pricing`) before opening checkout, and your app drops the query string on that navigation, the token is no longer on the URL. If it wasn't captured before that navigation, attribution is lost — in every browser, since the embed relies on the token, not the cookie. To cover this, call `captureAffiliateRef()` once early in your app (e.g. a root layout) so the token is captured on the landing page and stored for later: ```tsx theme={null} // Root layout / top-level component — runs on every page 'use client'; import { useEffect } from 'react'; import { captureAffiliateRef } from '@creem_io/react'; // also in /vue, /svelte, /embed export function AffiliateRefCapture() { useEffect(() => { captureAffiliateRef(); }, []); return null; } ``` > [!TIP] > > The **script loader** (`creem.io/embed.js`) captures the token automatically on every page it loads on — so if you include the ` > ``` > > This script is essential for Affonso to function. When a user visits your website through an affiliate link, it automatically creates a referral with the status "Visited link" and stores a referral cookie on their device. > > The script creates a global window\.Affonso object that you'll use in the next step to track successful signups. > [accordion] 3.2 Track User Signups. > > ```html theme={null} > // After successful registration > window.Affonso.signup(userEmail); > ``` > > When this function is called, Affonso system will: > > Create a new referral with status "LEAD" if a valid referral ID cookie exists > Make the referral visible in both your and your affiliate's statistics > > > [!NOTE] > > > > Note: If your platform allows payments without user registration (e.g., direct checkout), you can skip this step and proceed to the next one for payment tracking. > > > [!NOTE] > > > > Best Practice: Call this function for all signups, regardless of the traffic source. The system will only create referrals when a valid referral ID cookie is present. Place the code: > > > > After successful registration for immediate tracking > > After email verification if you use double opt-in (DOI) > [!TIP] > > For more advanced tracking documentation, or further examples in several > languages, visit [Affonso](https://affonso.io) documentation. ## Best Practices * Always test the integration in a development environment first * Implement proper error handling for affiliate tracking * Monitor webhook deliveries and set up retry mechanisms * Regularly verify commission calculations # Evendeals Source: https://docs.creem.io/integrations/evendeals Add purchase parity pricing to your Creem products and boost international conversions. ## Overview [Evendeals](https://www.evendeals.com) is a purchase parity pricing platform that helps you adjust prices based on your customers' location. Combined with Creem's payment processing and tax compliance, you get a complete global sales stack. A single price doesn't work for a global audience. \$49/mo might be reasonable in the US, but it could represent days of work in other countries. Parity pricing consistently drives **20-30% more international sales** by showing location-based discounts to visitors from lower-income regions. > [accordion] What you'll learn > > How to integrate Evendeals' purchase parity pricing with Creem's payment processing to automatically offer regional discounts and capture revenue from visitors who would otherwise bounce. > [card] Requirements > > * A Creem account > * An Evendeals account ([sign up free](https://www.evendeals.com/signin)) > * Your Creem API keys ## How It Works Evendeals detects your visitor's country, shows a discount banner with a region-appropriate price, and automatically creates and manages discount codes in Creem. When a visitor applies the code at checkout, they pay the adjusted price through Creem's standard checkout flow. **Key features:** * **Automatic discount sync** — Discount codes are created and managed in Creem automatically. No manual coupon work. * **Code rotation** — Codes rotate by time or view count. Leaked coupons expire automatically. * **VPN detection** — Block discount abuse from users masking their real location. ## Integration Steps Five steps, about 10 minutes. ### 1. Create a Creem API key In your [Creem dashboard](https://www.creem.io/dashboard/developers), create an API key with the right permissions. Use **Full access**, or enable Products, Subscriptions, and Transactions read + Discounts read/write. ### 2. Create a webhook in Creem Create a webhook in [Creem Webhooks](https://www.creem.io/dashboard/developers/webhooks), paste the URL from Evendeals, and select all events. Copy the signing secret for the next step. ### 3. Connect in Evendeals Paste your API key and webhook secret in the Evendeals connect dialog. The connection validates instantly. ### 4. Set regional discounts Choose percentage or fixed-amount discounts per country group. Evendeals creates the discount codes in Creem automatically. ### 5. Add the script to your site Add one line of code to your website. Visitors from lower-income countries will see a discount banner and can apply the code at Creem checkout. > [!NOTE] > > For detailed step-by-step instructions with screenshots, visit the [Evendeals Creem integration guide](https://www.evendeals.com/integrations/creem). ## Best Practices * Start with conservative discounts (15-25%) and adjust based on conversion data * Test the integration in Creem's test mode before going live * Monitor which regions are driving the most conversions * Review discount redemption rates regularly to optimize pricing tiers ## Resources > [card] [Evendeals Integration Guide](https://www.evendeals.com/integrations/creem) > > Detailed setup instructions with screenshots on the Evendeals site. > [card] [Evendeals Website](https://www.evendeals.com) > > Learn more about purchase parity pricing and sign up. # Framer Source: https://docs.creem.io/integrations/framer Add Creem checkout buttons and pricing tables to your Framer site with a no-code plugin, then style everything on the canvas. ## Overview The [Creem plugin for Framer](https://www.framer.com/community/marketplace/plugins/creem/) lets you add **checkout buttons** and **pricing tables** to any Framer site without writing code. Connect your Creem account, pick your products, and insert a component. The plugin drops a live, fully styleable element straight onto your canvas. Creem acts as your Merchant of Record, so VAT, GST, and sales tax across 190+ countries are calculated, collected, and remitted for you. That makes this pairing a fast way to start selling from a Framer landing page, template, or marketing site. > [accordion] What you'll learn > > How to install the Creem plugin from the Framer Marketplace, connect your account, insert a checkout button and a pricing table, customize both directly on the canvas, and switch from test mode to live. > [card] Requirements > > * A [Creem](https://creem.io/) account > * A Framer project (with edit access) ## Install the plugin You can install Creem from the [Framer Marketplace](https://www.framer.com/community/marketplace/plugins/creem/), or use it directly inside your Framer project with the following steps: **1. Open the Plugins menu** In your Framer project, open **Canvas** → **Plugins** → **Browse all**. ![Opening the Plugins menu in Framer](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/open-plugin-framer.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=98910108ef683ec316b8f1d8a3e7388f) Open the Plugins menu from the Framer canvas **2. Install Creem** Search for **Creem** and click the plugin to automatically install it. Once installed, open the plugin to get started. ![Select the Creem plugin from the suggested options](https://mintcdn.com/creem/EJ0hrD4kPhWGVVVR/images/framer/select-creem-plugin.png?fit=max\&auto=format\&n=EJ0hrD4kPhWGVVVR\&q=85\&s=4254a1263b1d4f2db42ae067b9ace605) Select the Creem plugin from the suggested options ## Connect your Creem account When you open the plugin for the first time, you can enter your **Live** Creem Store API Key, **Test** Creem Store API Key, or both, so you can browse either catalog and switch between them at any time. ![Connect your Creem account in the Framer plugin](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/connect-account.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=485d1f5bc35a085844f9b22e58a600c3) Name your store and paste a Live and/or Test API keys **1. Copy your API keys** In the [Creem dashboard](https://www.creem.io/dashboard/developers), go to **Developers** → **API Keys** and copy your keys. Live and test keys are separate (test keys are prefixed with `creem_test_`). **2. Name your store** Enter a **Store name** so you can tell your stores apart later. **3. Paste your keys** Add at least one key. Paste your live key into **Live API Key** and your test key into **Test API Key**. You can add the other environment later. The plugin routes each key to the right environment by its prefix, so a key pasted into the wrong field is flagged. **4. Connect** Click **Connect**. The plugin validates the key, loads your products, and drops you into the component picker. > [!NOTE] > > Your API keys are stored locally in the plugin and used only to read your product list. They are > never embedded in the components you insert onto the canvas. ## Manage stores and switch environments Once connected, the header shows a **store switcher** with the active store's name and a **Live** or **Test** badge. Open it to switch stores, switch environments, or manage your keys. ![Store and environment switcher in the Framer plugin](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/test-mode.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=1afa5d36499848adbc9dada7e61dce1b) The store switcher lets you switch stores, toggle Live and Test, and add or manage stores From the switcher you can: * **Switch environment**: choose **Live** or **Test** for the active store. If that store has no key for the environment yet, you're prompted to paste one inline. Product lists refresh automatically when you switch. * **Switch store**: select any other store to browse its products. * **Add a new store**: connect another Creem account or workspace. * **Rename** or **Remove** a store (you can't remove your only store). * **Sign out**: remove all stores and return to the connect screen. > [!NOTE] > > When the active environment is **Test**, the whole plugin gets a peach frame and a **Test mode > on** bar at the bottom, the same unmistakable signal as the Creem dashboard. See [Test mode and > going live](#test-mode-and-going-live). ## Choose a component After connecting, choose the component to be added to your canvas. Pick a **Checkout Button** for a single product, or a **Pricing Table** to list pricing plans on your page. ![Choosing between a Checkout Button and a Pricing Table](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/choose-component.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=1b5d05564b611654df86158cfdccdaad) Pick a checkout button or a pricing table ## Insert a Checkout Button A checkout button helps you sell a single product. It can either open checkout in a new tab or open it in a modal on the same page (the embed version). **1. Select a product** Search your products and select one. Picking a product advances you straight to configuration. ![Selecting a product for the checkout button](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/checkout-button-select-product.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=c34c6cad8b425537a6f92893de799c85) Select the product the button will sell **2. Configure the button** Choose how checkout opens, set the button text, and preview the result. ![Configuring the checkout button](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/checkout-button-configure.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=8e7eaf6f4b260db6f6bc77664964798d) Configure checkout type and button text, with a live preview **3. Insert Button** Click **Insert Button**. The button appears on your canvas, ready to style. See [Customize on the canvas](#customize-on-the-canvas) for every option. ## Insert a pricing table A pricing table lists several products side by side. You can mix one-time and subscription products in the same table. **1. Select products** Search and select the products to include. Each product becomes its own tier. ![Selecting products for the pricing table](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/pricing-table-select-products.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=0bbf730f4b8ac4f3d295f9bec5e38678) Select the products to include as tiers **2. Pick a layout** Choose a **Grid**, **Horizontal**, or **Vertical** layout. For a grid, set the number of **Columns** (1 to 5). A live preview reflects your choices. ![Choosing the pricing table layout and columns](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/pricing-table-configure.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=a39e730a909c125d9e2f9659b01611eb) Choose the layout and column count **3. Set the heading** Add a **Heading** and **Subheading** for the table. Leave both empty to hide the header entirely. ![Setting the pricing table heading and subheading](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/pricing-table-heading.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=2f8d0579fc813d19fb0e672e2e4e36fc) Add a heading and subheading **4. Edit and order the tiers** Reorder tiers with the up/down arrows, and expand any tier to edit it. ![Reordering pricing table tiers](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/pricing-table-tiers.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=492022cd3920e7d21196bb7bf333a065) Reorder tiers and expand one to edit Each tier has a **Tier Name**, a **Description**, a **CTA Text**, and a **Feature this tier** toggle. The description takes the same Markdown you use for product descriptions in the Creem dashboard: `- item` for a bulleted feature list, plus headings, links, bold or italic text, etc... ![Editing a pricing table tier](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/pricing-table-tier-config.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=cabe50ed44be75adc2b300a05a9e6447) Edit a tier's name, Markdown description, CTA, and featured state > [!TIP] > > Turn on **Feature this tier** to highlight a plan. The featured card gets a stronger border and shadow so it stands out. You can restyle featured cards on the canvas under **Featured Tier**. **5. Insert Pricing Table** Click **Insert Pricing Table**. The table appears on your canvas, ready to style. ## Product types and billing intervals The plugin supports every Creem product type and shows the correct price label for each. | Type | Description | Price label | | - | - | - | | **One-time** | A single purchase, no recurring billing | No suffix | | **Subscription** | Recurring billing on a set schedule | `/day`, `/month`, `/3 months`, `/6 months`, `/year` | When a pricing table contains **two or more subscription intervals** (for example a Monthly and a Yearly plan), the component automatically shows a billing-interval toggle so visitors can switch between them. One-time products always stay visible. Tables with a single interval show no toggle. ![Pricing table with a monthly/yearly interval toggle](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/pricing-table-interval-toggle.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=44401b6cec94280c8c387543816c2ee6) A pricing table automatically shows an interval toggle when it has multiple subscription intervals > [!NOTE] > > Interval tabs are labeled Daily, Monthly, Quarterly, Semi-annual, and Yearly. You can restyle the > toggle (Pill or Segmented, plus colors) on the canvas under **Billing Toggle**. ## Customize on the canvas The plugin inserts each component with sensible defaults, then hands the rest to Framer. Colors, spacing, fonts, button styles, and copy all live in Framer's property panel on the right, so you never reopen the plugin to restyle. Select the component on the canvas and the panel groups its controls by the part of the component they affect. Every change previews live, and the values you set travel with the component when you publish. ### Checkout button controls The button is one group of controls. The plugin fills in the product and a starting style (**CreemCheckoutButton**) at insert time, and everything below is yours to brand. ![Checkout button property controls in the Framer panel](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/checkout-button-on-canvas-panel.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=b788346cd6c84931d31a215ff0fe41ea) The checkout button and its property panel in Framer | Control | What it controls, and when to reach for it | | - | - | | **Variant** | The button's visual style. Seven presets ship: Default (solid fill), Outline, Ghost (text only), Gradient, Shadow, Shimmer (animated sheen), and Icon Slide (an arrow that slides across on hover). All of them use the colors you set below, so choose the shape first and brand it after. | | **Type** | Whether checkout opens as an Embed (a modal over the current page) or in a New Tab. Embed keeps buyers on your site, while New Tab is the safer choice when the button sits inside a restrictive embed or you want a full checkout window. | | **Product ID** | The Creem product this button charges for. The plugin sets it at insert time, so you normally leave it untouched. Edit it only to repoint the button at a different product without re-inserting. | | **Button Text** | The label on the button, such as "Buy now" or "Get the template". Keep it short and action-led. | | **Background** and **Text Color** | The fill and label colors. Defaults are Creem peach on white. Set both to match your brand or the section the button sits in. | | **Radius**, **Font Size**, **Padding X**, **Padding Y** | The button's shape and size. Radius rounds the corners (0 is square), Padding X and Y set the space around the label (its width and height), and Font Size scales the text. | | **Full Width** | Stretches the button to fill its container. Turn it on for full-width calls to action in narrow columns or on mobile. | | **Discount Code** | A Creem discount code applied automatically when checkout opens, so buyers never type it. Handy for launch or campaign buttons that should always carry the offer. | | **Success URL** | Where the buyer lands after paying. Point it at a thank-you or onboarding page to continue the flow, or leave it empty to use the product's default redirect. | > [!NOTE] > > Success URLs are optional. When set, they must be valid HTTPS URLs; unsupported or malformed > redirect targets are blocked before checkout opens. ### Pricing table controls The pricing table splits its controls into groups (in the **CreemPricingTable** style), one per area of the table, matching the rows in the panel. ![Pricing table property controls in the Framer panel](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/pricing-table-on-canvas-panel.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=6f1fe6c6ec876d594f7bd3a3fdf58e78) The pricing table's property panel in Framer For an easier editing flow, make sure **Table** shape is as per your requirements, then style the **Card**, then set apart the **Featured Tier** and its buttons. > [accordion] Table > > Sets the table's overall shape. **Layout** switches between a Grid, a Horizontal scroll row, and > a Vertical stack. For a grid, **Grid Columns** caps how many cards sit per row, while **Min Card > Width** and **Grid Gap** decide when cards wrap on smaller screens. **Max Width** stops the > table stretching too wide on large monitors, and **Page Background** paints the area behind the > cards. Start here to get the structure right before styling anything else. > [accordion] Header > > The title and subtitle above the cards, pre-filled from the heading you set when inserting. > Toggle the header off to drop it entirely, or set the **Title** and **Description** text, > **Alignment** (left, center, right), font sizes, and colors to match your page's typography. > [accordion] Pricing Tiers > > The list of plans, one entry per card. Each tier holds its **Name**, **Price**, **Currency**, > and billing (a **One-time** purchase or a recurring **Billing Period**), the **Product ID** it > charges, the **Button Text** and **Button Variant**, optional per-tier button colors, a Markdown > **Description**, and a **Featured** flag. This is where you edit plan copy, correct a price or > its interval label, reorder cards, or add and remove tiers after inserting. > [accordion] Billing Toggle > > The Monthly/Yearly switch that appears automatically when the table holds two or more > subscription intervals (see [Product types and billing > intervals](#product-types-and-billing-intervals)). Choose its **Style** (Pill or Segmented) and > its colors, or hide it when you want a single interval on show. > [accordion] Card > > The look every card shares: **Background**, **Border**, and **Divider** colors and widths, > corner **Radius**, inner **Padding** and **Gap**, the text colors for headings, muted body copy, > and links, and the **Title**, **Description**, and **Price** font sizes. Set your neutral card > style here, and the featured card inherits it and overrides only its highlighted parts. > [accordion] Featured Tier > > The extra styling for whichever tier you marked **Featured**, covering its button colors and a > heavier border. Use it to make your recommended plan stand out from the standard cards without > restyling every card. > [accordion] Standard Buttons > > The default call-to-action style for non-featured tiers: button colors (fill, text, border), > **Height**, **Radius**, and **Font Size**. Featured tiers use the **Featured Tier** colors > instead, so set the everyday button look here and the highlight there. ## Embed vs. New Tab checkout Both components let you choose how checkout opens. | Option | What happens | | - | - | | **Embed** | Opens checkout in a modal overlay on the same page | | **New Tab** | Opens checkout in a new browser tab | > [!NOTE] > > Both options use Creem-hosted checkout at runtime. Test components open the test checkout URL and > Live components open the production checkout URL. If Creem or the visitor's network is temporarily > unavailable, checkout cannot open or complete until connectivity is restored. ![Creem embed checkout modal](https://mintcdn.com/creem/39cpBjt8v8o0etJ5/images/framer/embed-modal.png?fit=max\&auto=format\&n=39cpBjt8v8o0etJ5\&q=85\&s=111209405e5dcde6b63647c5d6bd9c90) Embed opens checkout in a modal over your page > [!NOTE] > > Checkout opens on your published site, not on the Framer canvas. Publish or preview your site to > test the full flow. ## Test mode and going live Test mode lets you build and preview without real charges. Switch a store to **Test** in the [store switcher](#manage-stores-and-switch-environments) to browse your test catalog. A peach frame and a **Test mode on** bar make it obvious you're in test. The environment is captured on each component **at insert time**. A component inserted while you're in Test opens test checkout, and one inserted in Live opens live checkout. > [!WARNING] > > Switching a store's environment does **not** retroactively change components you already inserted. > When you're ready to go live, switch the store to **Live** in the switcher and **re-insert** your > buttons and tables so they point at your live products. **Unconfigured products are blocked, not broken.** If a button or tier's **Product ID** is still the placeholder (`prod_abc123`) or left empty, most often after adding a tier by hand in the property panel instead of through the plugin, its checkout is blocked and the visitor sees an "isn't available yet" message rather than a broken checkout. Fix it by setting a real **Product ID** on that tier or button (copy the ID from your product in the Creem dashboard), or re-insert the component through the plugin to pull in a valid product. ## Troubleshooting > [accordion] The Insert button is disabled > > Inserting writes a code file and drops a component onto the canvas, which both need edit access. > Ask the project owner for edit permission on the Framer project. > [accordion] "Still compiling" when inserting > > Framer is still building the component's code file. Wait a moment and click Insert again. > [accordion] A tier shows "isn't available yet" > > That tier or button's **Product ID** is still the placeholder (`prod_abc123`) or empty, usually > from adding a tier directly in the property panel. Set a valid **Product ID** on it (copy the ID > from your product in the Creem dashboard), or re-insert the component through the plugin to > select a product from your list. > [accordion] A product is missing from the list > > The plugin lists active products. Make sure the product is active in your Creem dashboard, then > use the refresh button in the plugin to re-sync. ## Resources > [card] [Creem plugin on the Framer Marketplace](https://www.framer.com/community/marketplace/plugins/creem/) > > Install the plugin and view its listing. > [card] [Sell Framer templates with remix links](/guides/sell-framer-templates-instant-remix-links) > > Deliver a private remix link automatically after purchase. > [card] [Creem webhooks guide](/code/webhooks) > > React to payments with verified webhook events. > [card] [Creem quickstart](/getting-started/quickstart) > > Get your first API key and create a product. # LinkJolt Affiliate Program Integration Source: https://docs.creem.io/integrations/linkjolt Connect LinkJolt affiliate tracking to your Creem store with one restricted API key. LinkJolt adds its own webhook, credits sales and renewals to affiliates, and creates affiliate discount codes in your store. > [!NOTE] > > Creem also has a [built-in affiliate program](/features/affiliate-program) that runs inside your > Creem dashboard. This guide covers connecting a third-party affiliate platform instead, or > alongside it. ## Overview [LinkJolt](https://www.linkjolt.io/integrations/creem-affiliate-tracking?utm_source=creem\&utm_medium=docs) is affiliate tracking and management software with a Creem connection. An affiliate shares a link or a discount code, LinkJolt records the click, and when that visitor buys through your Creem checkout, the sale arrives on a signed webhook and is credited to the affiliate. You connect with one API key. LinkJolt uses it to add its own webhook to your Creem store and read the signing secret, so you don't copy a URL or paste a secret. Sales, subscription renewals, trials, refunds and chargebacks all arrive through that webhook. LinkJolt also uses the key to create a Creem discount code for each affiliate. > [card] What you'll need > > * A Creem account (production or Test Mode, LinkJolt follows the key you connect with) > * A LinkJolt account > ([sign up](https://www.linkjolt.io/auth/sign-up?utm_source=creem\&utm_medium=docs)) > * A Creem API key with the `webhooks:read`, `webhooks:write`, `discounts:read`, `discounts:write` > and `products:read` scopes ## Video walkthrough A six-minute walkthrough: connecting a Creem store with one API key, giving an affiliate a Creem discount code, and following one sale from the affiliate's link to the commission. [How to Set Up an Affiliate Program for Your Creem SaaS](https://www.youtube.com/embed/QEEFepZWNd4) ## How It Works Creem hosts checkout on its own domain, so the affiliate referral needs a way to travel from your site into the sale. It travels as one metadata field, `linkjolt_ref`, and on Creem payment links the LinkJolt tracking script adds it for you. * A visitor clicks an affiliate's link and lands on your site. The LinkJolt tracking script stores the referral in their browser for 30 days and exposes it as `window.linkjolt.referral`. * They go to checkout with the referral attached as `linkjolt_ref` metadata. The script adds it to every Creem payment link and product link on your page. If your server creates the checkout, you add it there. * Creem processes the payment and sends a signed webhook to LinkJolt. * LinkJolt matches the referral, or the discount code used at checkout, to the affiliate, calculates the commission, and records it as pending until you approve it. Sales never come through the API. They arrive on the signed webhook, and the API key only manages the webhook and the discount codes. > [!NOTE] > > LinkJolt reads `linkjolt_ref` from checkout metadata. Creem's [built-in affiliate > feature](/features/affiliate-program) uses its own `creem_ref` URL token, which never ends up in > your metadata, so you can run both side by side. ## Integration Steps You connect Creem's Test Mode first, check a purchase end to end, then connect your live store. **1. Create a campaign in LinkJolt** In LinkJolt, create a campaign. It holds your commission terms: * **Commission**: a percentage of each sale, or a fixed amount. * **Renewals**: whether subscription renewals pay commission too, and for how many months or payments. * **Approval**: whether affiliates who apply are approved automatically, or wait for you. Then invite affiliates from LinkJolt, or share your program's join page so they can apply. **2. Create a restricted API key in Creem** In your Creem dashboard, switch on **Test Mode**, go to **Developers > API Keys** and create a key. Switch **Full access** off and grant only the scopes LinkJolt uses: | Scope | Used for | | - | - | | `webhooks:read` and `webhooks:write` | Adding the LinkJolt webhook to your store and reading its signing secret | | `discounts:read` and `discounts:write` | Creating a discount code for each affiliate | | `products:read` | Listing your active products, so each new code applies to them | With these scopes the key can't change your products, customers or orders. A Test Mode key starts with `creem_test_`. LinkJolt records sales from Test Mode as test sales and never pays them out. You create the live key the same way in the last step. **3. Connect Creem in LinkJolt** In LinkJolt, open **Integrations** and choose the **Creem** tab. Paste the key into **Creem API key** and click **Set it up**. LinkJolt then: * adds a webhook named **LinkJolt** to your Creem store, subscribed to every event * reads the webhook back from Creem to confirm it was saved * reads the webhook's signing secret * stores the key encrypted, to create discount codes and to check the webhook once a day The new webhook is in Creem under **Developers > Webhooks**. Leave its events as they are. > [!TIP] > > If you'd rather not give LinkJolt an API key, choose **Set it up by hand instead** on the Creem > tab. Add the webhook in Creem yourself with every event selected, and paste its signing secret > into LinkJolt. Tracking works the same, but LinkJolt can't create discount codes or run the daily > check. **4. Add the LinkJolt tracking script to your site** The Creem tab asks how your customers pay: payment links on your site, a checkout your own code creates, or discount codes only. For the first two, add the tracking script to the `` of your marketing site. It records affiliate clicks and stores the referral for the next step. ```html Tracking script theme={null} ``` The Creem tab shows the script with your ID filled in, plus a version for React. If you only use discount codes, there's nothing to install, so skip to the last step. **5. Pass the referral into checkout** This step connects a click to a sale. Without it, sales arrive with no referral and no affiliate is credited. **Payment links**: nothing to add. The tracking script appends `metadata[linkjolt_ref]` to every link on the page that points at a Creem payment link or product page (`creem.io/payment/`, `creem.io/product/` and their `/test/` forms), including links added after the page loads. Creem copies the parameter into the checkout's metadata. **Checkout API or SDK**: read the referral in the browser with `window.linkjolt.referral`, send it with your checkout request, and set it as `metadata.linkjolt_ref` where your server creates the checkout. ```json Checkout API theme={null} { "product_id": "prod_your_product", "success_url": "https://yoursite.com/success", "metadata": { "linkjolt_ref": "REFERRAL_FROM_YOUR_FRONTEND" } } ``` ```ts TypeScript SDK theme={null} const checkout = await creem.checkouts.create({ productId: "prod_your_product", successUrl: "https://yoursite.com/success", metadata: { linkjolt_ref: referral }, // the value of window.linkjolt.referral }); // send the customer to checkout.checkoutUrl ``` ```js Links you build in JavaScript theme={null} const url = new URL("https://www.creem.io/payment/prod_your_product"); const referral = window.linkjolt?.referral; if (referral) url.searchParams.set("metadata[linkjolt_ref]", referral); window.location.href = url.toString(); ``` **Links you build in JavaScript**: the script rewrites links on the page, not a URL your code opens (for example with `window.open` or `location.href`). Add the parameter yourself, as in the third tab. > [!TIP] > > Creem copies checkout metadata onto the subscription, and every `subscription.paid` event carries > it. Renewals keep crediting the same affiliate without anything extra. **6. Verify with a test purchase, then go live** Run this once in Test Mode before you rely on it. 1. **Visit your site through an affiliate link.** Take any affiliate's link from LinkJolt, or a test affiliate's, and open your site with it. 2. **Check the link carries the referral.** Hover a Creem payment link on the page. Its address now includes `linkjolt_ref`. If you use the Checkout API, log the value you send instead. 3. **Buy with a test card.** Complete the checkout with card `4111 1111 1111 1111`, any future expiry and any CVC ([test cards](/getting-started/test-mode)). In LinkJolt, the sale appears under **Test sales** on the **Commissions** page, credited to that affiliate. 4. **Refund the purchase in Creem.** LinkJolt reverses the commission. 5. **Resend the webhook.** In Creem, resend the `checkout.completed` delivery. LinkJolt keys every payment by its Creem transaction, so it still shows one sale and one commission. To go live, switch Test Mode off in Creem, create a live API key with the same scopes, and paste it into the same field on LinkJolt's Creem tab. LinkJolt adds its webhook to your live store. Your Test Mode connection stays, and test sales stay separate from your live commissions. ## Affiliate discount codes A discount code credits an affiliate without a link, for affiliates who promote by voice or video. Once your live store is connected with an API key: * **One code at a time**: on the **Coupons** tab of LinkJolt's **Campaigns** page, create a coupon, pick the affiliate, choose **Creem discount**, and enter the code and the discount. LinkJolt creates it as a discount in your Creem store, with the percentage or amount and the duration you chose. * **A code for every affiliate**: switch on **A coupon code for every affiliate** in a campaign's settings, and every approved affiliate gets their own code, named after them. A sale that uses the code is credited to that affiliate. LinkJolt creates each code for the products active in your store at that moment, so a product you add later needs new codes. Discounts you create in Creem yourself work too. Register each one on the same Coupons tab by its `dis_` ID. ## What Gets Tracked | Event | What happens | | - | - | | One-time sale | Commission recorded from `checkout.completed`, pending until you approve it | | First subscription payment | Recorded once, whether `checkout.completed` or `subscription.paid` arrives first | | Subscription renewal | Commission from each `subscription.paid`, at your recurring rate, up to the cap you set | | Trial start | Recorded as a trial, with no commission until the first real payment | | Refund | Commission reduced in proportion for a partial refund, removed for a full one | | Chargeback | Commission reversed in full | | Discount code | A sale using an affiliate's code credits them, even without a link | | Test Mode purchase | Recorded as a test sale, separate from your live commissions, and never paid out | Commission is calculated on what the customer paid, or on the price before tax if you switch on **Commission on the price before tax** in LinkJolt's settings. Every payment is keyed by its Creem transaction, so webhook retries and manual resends don't count twice. ## Refunds and chargebacks Creem's `refund.created` event carries `refund_amount`, the amount of that refund. LinkJolt reverses the commission in proportion to what has been refunded, and a full refund or a chargeback removes it. A redelivered or out-of-order event doesn't reverse anything twice, and a payout still queued for the sale is reduced or cancelled to match. Every commission stays pending until you approve it, so a refund that arrives first adjusts it before anything is paid. If you've already paid the commission, LinkJolt records the refund but doesn't take money back from the affiliate. Settle that with them directly. ## Good to Know * **The daily check.** Once a day LinkJolt reads its webhook with your key. If the webhook was switched off, changed or deleted, or the key revoked, the Creem tab says what's wrong and LinkJolt emails you once. LinkJolt never changes the webhook by itself: if you switched it off, it stays off until you click **Turn it back on** on the Creem tab. * **Short links and storefronts.** The script adds the referral to full payment links and product links on your own site. It can't reach a Creem short link (`l.creem.io`) or a [storefront](/features/storefronts) page, so link to the payment link itself where affiliates send traffic, or give those affiliates a discount code. * **Custom domains.** With a [custom domain](/features/custom-domains), new payment links point at your subdomain (for example `pay.yourbrand.com`) instead of `creem.io`. Add `&creem_domain=pay.yourbrand.com` to the tracking script's URL and the script adds the referral to links on that domain too. If you connected with an API key, LinkJolt finds the domain in your products and the Creem tab shows the script with it filled in. * **One Creem store per LinkJolt brand.** LinkJolt refuses a store that's already connected to another brand until you disconnect it there. * **Disconnecting.** Click **Disconnect Creem** on the Creem tab. LinkJolt removes its webhook from your store and keeps the discount codes it created, since they live in Creem. > [card] [LinkJolt for Creem](https://www.linkjolt.io/integrations/creem-affiliate-tracking?utm_source=creem\&utm_medium=docs) > > LinkJolt's own page for the Creem integration. # Referly Affiliate Program Integration Source: https://docs.creem.io/integrations/referly Run your affiliate program on Creem with Referly. One webhook tracks sales, renewals, refunds and coupon codes, and Referly handles your affiliates end to end. > [!NOTE] > > Creem also has a [built-in affiliate program](/features/affiliate-program) that runs inside your > Creem dashboard. This guide covers connecting a third-party affiliate platform instead, or > alongside it. ![The Referly and Creem logos connected by sync arrows](https://mintcdn.com/creem/JSGX57Jb9ZsGUaVq/images/referly/hero.png?fit=max\&auto=format\&n=JSGX57Jb9ZsGUaVq\&q=85\&s=104b6bd7f76aea2897bb033a6f4400a3) ## Overview [Referly](https://referly.so/creem) is affiliate tracking and management software with a native Creem connection. An affiliate shares a link or a discount code, Referly records the click, and when that visitor buys through your Creem checkout the sale arrives on a signed webhook and is credited to the right affiliate. Setup is one webhook in Creem, two values pasted into Referly, and one metadata field carried through your checkout. Sales, subscription renewals, trials, refunds and chargebacks all arrive through that single webhook. ## What you can do with Referly > [card] Launch an affiliate program > > A branded portal where affiliates sign up and find their links, codes and earnings. > [card] Track referrals and sales > > Clicks, sign-ups, one-time sales, subscription renewals, refunds and chargebacks. > [card] Product-based commissions > > Different rates per Creem product, or rule-based plans. > [card] Affiliate promo codes > > A Creem discount code per affiliate, credited without a link. Automatic generation needs the > Business plan or above. > [card] Affiliate self-service > > Affiliates create and rename their own codes, synced to your Creem store. > [card] Flexible payouts > > Bank transfer, PayPal or Wise, or discount codes and Creem customer credits instead of cash. > [card] What you'll need > > * A Creem account (production or test mode, Referly follows the key you connect with) > * A Referly account ([start here](https://referly.so/creem)) > * A Creem API key, plus the signing secret of the webhook you create in step 3 ## How It Works Creem hosts checkout on its own domain, so the affiliate referral needs a way to travel from your site into the sale. That is the one piece you wire up yourself, and it is a single metadata field. * A visitor clicks an affiliate link and lands on your site. The Referly tracking script stores the referral in their browser and exposes it as `window.affiliateId`. * They go to checkout, and you attach that referral to the Creem checkout as `referly_ref` metadata. For payment links, a drop-in snippet from Referly does this for you. * Creem processes the payment and sends a signed webhook to Referly. * Referly matches the referral (or the discount code used at checkout) to the affiliate, calculates the commission, and records it. Your API key powers the optional extras: listing your Creem products for product-based commission rules, creating discount codes for coupon attribution, and crediting affiliates who are paid in Creem customer credits. Sales never come through the API; they arrive on the signed webhook. > [!NOTE] > > Referly reads `referly_ref` from checkout metadata. Creem's [built-in affiliate > feature](/features/affiliate-program) uses its own `creem_ref` URL token, which never ends up in > your metadata, so you can run both side by side. ## Integration Steps Eight steps, about twenty minutes including the test purchase. **1. Create your affiliate program in Referly** Sign up at [referly.so](https://referly.so/creem) and create an affiliate program for your Creem store. The setup wizard walks you through the parts that matter: * **Reward and trigger**: a cash commission (percentage or flat amount), earned when a customer makes a payment. Product-specific rates can be added later, once Creem is connected and Referly can list your products. * **Commission frequency**: choose **Recurring** if you want subscription renewals to pay commission. **First payment only** pays once per customer and ignores renewals. * **Payout hold**: how long commissions are held before payout. This is also your refund window. A refund inside the hold reverses the commission automatically; after the hold, the commission has been released for payout and is not reversed. * **Affiliate portal**: the page your affiliates sign up on and where they find their links and codes. ![Referly's program setup wizard on the commission step, with Customer Makes a Payment and Recurring selected and the commission amount filled in](https://mintcdn.com/creem/JSGX57Jb9ZsGUaVq/images/referly/create-program.png?fit=max\&auto=format\&n=JSGX57Jb9ZsGUaVq\&q=85\&s=79a25c8803d2980e23013b4abf99f061) The commission step of the program wizard: reward type, trigger, frequency and amount. **2. Open the Creem connect dialog in Referly** In your Referly dashboard, open **Settings > Integrations** and choose **Creem**. The dialog shows your program's unique webhook URL. Copy it and keep this dialog open; you will come back to it in step 5. ![Referly's Creem connect dialog with the webhook URL, an API key field and a webhook signing secret field](https://mintcdn.com/creem/JSGX57Jb9ZsGUaVq/images/referly/connect-dialog.png?fit=max\&auto=format\&n=JSGX57Jb9ZsGUaVq\&q=85\&s=2bfc797be13f43c76f3ef2efdd3794e5) The Creem dialog shows your webhook URL and the two fields you'll fill in shortly. **3. Add the webhook in Creem** In your Creem dashboard, go to **Settings > Webhooks** and click **Add Webhook**, then: 1. Give it a name you will recognize later, for example "Referly". 2. Paste the webhook URL from step 2 as the endpoint URL. 3. Check that **every event type** is selected. They are selected by default, so the counter should match the full list; leave it that way. 4. Click **Create webhook**. 5. Open the webhook you just created and copy its **signing secret**; you will paste it into Referly in step 5. ![Creem's New webhook form with the Referly webhook URL pasted and every event type selected](https://mintcdn.com/creem/JSGX57Jb9ZsGUaVq/images/referly/webhook-events.png?fit=max\&auto=format\&n=JSGX57Jb9ZsGUaVq\&q=85\&s=aac16ac86cdd918285f2bd281ec1ea02) All event types are selected by default. Check the counter matches the full list, then click Create webhook. > [!WARNING] > > Keep every event type selected. Referly ignores the events it does not need, but a webhook saved > with only some events is accepted without complaint and then silently drops sales or refunds. If > tracking ever goes quiet, check this first. **4. Create a restricted API key** In Creem, go to **Settings > API Keys** and create a key. Switch **Full access** off and grant only the permissions Referly uses: | Permission | Needed for | | - | - | | **Products: Read** | Always. Validates the connection and lists your products for product-based commission rules. | | **Discounts: Read and Write** | Only if Referly should create and sync affiliate discount codes. | | **Customers: Read** | Only if you reward affiliates with Creem customer credits (Referly looks the affiliate's customer record up by email). | | **Customer Credits: Read and Write** | Only if you reward affiliates with Creem customer credits (Referly creates and tops up their credits account). | Nothing else is required. Referly never writes customers, products or orders. Use a production key for live tracking. A `creem_test_` key connects the same way and tracks Creem Test Mode purchases instead, which is how you run the test purchase in step 8. ![Creem's New API key dialog with Full access switched off and read permission on Products, read and write on Discounts, read on Customers and read and write on Customer Credits](https://mintcdn.com/creem/JSGX57Jb9ZsGUaVq/images/referly/api-key-permissions.png?fit=max\&auto=format\&n=JSGX57Jb9ZsGUaVq\&q=85\&s=eeacbd9472bbf6a69fe91c49fd2ef401) Full access switched off, with only the permissions Referly uses granted. **5. Connect in Referly** Back in the Referly dialog from step 2: * Paste the **API key** from step 4 * Paste the **webhook signing secret** from step 3, including its prefix * Click **Connect** Referly validates the key against Creem before saving, so you find out straight away if something is off. A test key shows a **Test mode** badge so there is no guessing which environment you are in. ![Referly's Creem dialog in the connected state showing a green Connected badge and an amber Test mode badge](https://mintcdn.com/creem/JSGX57Jb9ZsGUaVq/images/referly/connected.png?fit=max\&auto=format\&n=JSGX57Jb9ZsGUaVq\&q=85\&s=4f6a4ce6f5934645411f4d5dc3a98aeb) Connected, with the Test mode badge when a creem_test\_ key is used. **6. Add the Referly tracking script to your site** Copy your program's tracking script from the Referly dashboard (**Settings > Tracking methods**, or step 2 of the integration wizard) into the `` of your marketing site. It records affiliate clicks, stores the referral for your program's cookie window, and exposes it as `window.affiliateId` for the next step. ```html Tracking script theme={null} ``` Replace `YOUR_PROGRAM_ID` with the id shown in your dashboard; the copy button in Referly fills it in for you. ![Referly's tracking script step with the copyable script snippet](https://mintcdn.com/creem/JSGX57Jb9ZsGUaVq/images/referly/tracking-script.png?fit=max\&auto=format\&n=JSGX57Jb9ZsGUaVq\&q=85\&s=53bd7af77662cee7a09b1f90cf613af6) The tracking script step in Referly, with the copyable snippet. **7. Pass the referral into checkout** This is the step that connects a click to a sale. Without it, link-attributed sales arrive with no referral attached (discount-code sales still match through the code itself). Pick whichever matches how you sell: ```json Checkout API theme={null} { "product_id": "prod_your_product", "success_url": "https://yoursite.com/success", "metadata": { "referly_ref": "REFERLY_ID_FROM_YOUR_FRONTEND" } } ``` ```html Payment links theme={null} ``` ```js Links you build in JavaScript theme={null} const url = new URL("https://www.creem.io/payment/prod_your_product"); if (window.affiliateId) { url.searchParams.set("metadata[referly_ref]", window.affiliateId); } window.location.href = url.toString(); ``` **Checkout API**: read the referral in the browser with `window.affiliateId` and send it along with the rest of your checkout request; your server puts it in `metadata.referly_ref`. **Payment links**: the snippet appends `metadata[referly_ref]` to every `` element on the page whose `href` points at `creem.io/payment/` or `creem.io/test/payment/`. It handles links that appear after page load (it watches the DOM, so client-side rendering, modals and pricing toggles are covered), updates a link again if the referral changes from the raw ref to the click id, and decorates a link once more on click as a last resort. **Links you build in JavaScript**: the snippet only sees anchor elements. If a button opens Creem from code (for example `window.open` or `location.href`), append the parameter yourself as in the third tab, or use the Checkout API. > [!TIP] > > Creem carries checkout metadata onto the subscription, so renewals keep crediting the same > affiliate without you doing anything extra. **8. Verify with a test purchase** Run this once in Test Mode before going live. It takes about five minutes. 1. **Visit your site through an affiliate link.** Take any affiliate's link from your Referly portal (or your own test affiliate's) and open your site with it. The click appears on that affiliate in Referly. 2. **Check the link carries the referral.** Hover a Creem payment link on the page: its address now ends in `metadata[referly_ref]=...`. Checkout API integrations should log the `referly_ref` value they send instead. 3. **Buy with a test card.** Complete the checkout with card `4111 1111 1111 1111`, any future expiry and any CVC. In Referly, the buyer appears as a referral and the order appears as a sale with the commission calculated for that affiliate. 4. **Refund the order in Creem** (Orders, open the order, Refund). Referly marks the sale refunded and reverses the commission. This works because the sale is still inside your payout hold; a refund after the hold is not reversed automatically. 5. **Resend the webhook.** In Creem, open the webhook's deliveries and resend the `checkout.completed` event. Referly de-duplicates by Creem order id, so nothing changes: still one sale, no second commission. 6. **Test a coupon-only sale** if you use affiliate codes. Give an affiliate a Creem discount code in Referly, open a fresh private window without any affiliate link, and check out using the code. The sale is credited to that affiliate through the code alone. To switch to live mode: 1. In Creem, switch out of Test Mode and repeat step 3 for the live environment: the same webhook URL, every event type selected, **Create webhook**, then copy the live webhook's signing secret. 2. Create a live API key with the same restricted permissions as step 4. 3. In Referly, click **Disconnect** in the Creem dialog, then connect again with the live key and the live signing secret. The Test mode badge disappears. Test-mode sales stay in Referly as history; live sales arrive on the same webhook URL from here on. ## What Gets Tracked Once you are connected, these all happen on their own: | Event | What happens | | - | - | | One-time sale | Commission credited when the checkout completes | | Subscription renewal | Commission per billing period, at the amount actually charged, when the commission plan pays on a recurring basis | | Trial start | Referral recorded, but no commission until the first real payment | | Refund | Inside the payout hold: the sale is marked refunded and the full commission is reversed. After the hold: nothing changes | | Chargeback | Treated like a refund, with the same payout-hold rule | | Coupon code | A sale using an affiliate's Creem discount code credits that affiliate. Automatic per-affiliate codes need the Business plan or above | Commissions are calculated on the pre-tax sale amount, and every sale, refund and dispute is de-duplicated by its Creem order id, so webhook retries and manual resends never count twice. ## Refunds and chargebacks A refund or chargeback reverses the commission only while the sale is inside your payout hold (the hold you set in step 1). During the hold, the sale is marked refunded and the affiliate's commission is taken back in full. Partial refunds reverse the entire commission, not a proportional share. After the hold, the commission has already been released for payout. Referly acknowledges the refund webhook but changes nothing: the sale stays as it was, the commission is not reversed, and the dashboard's manual mark-as-refunded action is blocked for the same reason. Settle it with the affiliate directly. If refunds are common in your business, set a payout hold that covers your refund policy. ## Good to Know * **Check the event selection first.** A webhook saved with only some events ticked fails quietly. * **Coupon attribution works without the snippet.** If an affiliate's discount code is used at checkout, the sale is credited through the code even when no `referly_ref` metadata is present. * **One Creem key per Referly program.** A key already connected to another Referly program is rejected. * **Re-created the webhook? Update the signing secret.** Deleting and re-creating the endpoint in Creem gives you a new secret; paste the new one into Referly's connect dialog, or deliveries fail their signature check. > [card] [Referly documentation](https://www.referly.so/docs?utm_source=creem\&utm_medium=docs\&utm_campaign=creem-integration\&ref=creem) > > Guides to commission plans, coupon rules, payouts and the affiliate portal in Referly's own docs. # Refgrow Affiliate Program Integration Source: https://docs.creem.io/integrations/refgrow Connect Refgrow to your Creem store with one restricted API key. Refgrow adds its own webhook, credits sales and subscription renewals to partners, and reverses commissions on refunds and chargebacks. > [!NOTE] > > Creem also has a [built-in affiliate program](/features/affiliate-program) that runs inside your > Creem dashboard. This guide covers connecting a third-party affiliate platform instead, or > alongside it. ## Overview [Refgrow](https://refgrow.com/?utm_source=creem\&utm_medium=docs) is affiliate and referral software for SaaS. A partner shares a link or a discount code, and when that visitor buys through your Creem checkout, Refgrow credits the sale to the partner. You connect with one API key. Refgrow uses it to add its own webhook to your Creem store and read the signing secret, so you don't copy a URL or paste a secret. Sales, subscription renewals, refunds and chargebacks all arrive through that webhook. > [card] What you'll need > > * A Creem account (production or Test Mode) > * A Refgrow account ([sign up](https://refgrow.com/register?utm_source=creem\&utm_medium=docs)) > * A Creem API key with the `webhooks:read` and `webhooks:write` scopes ## How It Works Creem hosts checkout on its own domain, so the partner's referral needs a way to travel from your site into the sale. It travels as one metadata field, `referral_code`, and on Creem payment links the Refgrow script adds it for you. * A visitor clicks a partner's link and lands on your site. The Refgrow script stores the partner's code in their browser for 30 days (you can change this in Refgrow). * They go to checkout with the code attached as `metadata[referral_code]`. The script adds it to every Creem payment link on your page, including links that appear after the page loads. If your server creates the checkout, you add it there. * Creem processes the payment and sends a signed webhook to Refgrow. * Refgrow matches the code, or the discount code used at checkout, to the partner and records the commission. Creem copies checkout metadata onto the subscription, so once the code is on the first payment, every renewal is credited to the same partner. > [!NOTE] > > Refgrow reads `referral_code` from checkout metadata. Creem's [built-in affiliate > feature](/features/affiliate-program) uses its own `creem_ref` URL token, which never ends up in > your metadata, so you can run both side by side. ## Integration Steps **1. Create your program in Refgrow** In Refgrow, create a project for your product and set your commission terms: * **Commission**: a percentage of each sale or a fixed amount, with different rates per product or per partner if you need them. * **Renewals**: whether subscription renewals pay commission too, and for how long. * **Hold period**: how many days a commission waits before it can be paid out. Set it longer than your refund window. Then invite partners, or share your program's sign-up page so they can join. **2. Create a restricted API key in Creem** In your Creem dashboard, go to **Developers > API Keys** and create a key. Switch **Full access** off and grant only the scopes Refgrow uses: | Scope | Used for | | - | - | | `webhooks:read` and `webhooks:write` | Adding the Refgrow webhook to your store, reading its signing secret, and removing it when you disconnect | Renewal amounts come in each `subscription.paid` event, so Refgrow needs no other scope. With these scopes the key can't change your products, customers or orders. **3. Connect Creem in Refgrow** In Refgrow, open **Integration**, choose **Creem**, paste the key and click **Connect**. Refgrow then adds a webhook named **Refgrow (project ID)** to your Creem store, subscribed to: * `checkout.completed` * `subscription.paid` * `refund.created` * `dispute.created` * `subscription.canceled` Refgrow keeps the webhook's signing secret and checks it on every event. Nothing else in your store changes, and connecting again later reuses the same webhook. > [!NOTE] > > Prefer to create the webhook yourself? Point it at > `https://refgrow.com/webhook/creem/YOUR_PROJECT_ID` with the five events above, then choose > **Paste its signing secret instead** on Refgrow's Integration page. **4. Add the Refgrow script to your site** Add the script to the pages that link to Creem. For a referred visitor it adds the partner's code to every `creem.io` payment link: ```html theme={null} Buy ``` If your payment links use a [custom domain](/features/custom-domains), add the class `refgrow-creem-link` to those links so the script picks them up too. The script adds the code when a link is clicked, not to a URL your code opens with `window.open` or `window.location`. Add `metadata[referral_code]` to those URLs yourself, with the value of `window.Refgrow.getReferralCode()`. **5. Pass the code from your server (optional)** If your server creates checkout sessions, read the code in the browser and send it with your checkout request: ```ts Browser theme={null} const referralCode = window.Refgrow?.getReferralCode?.() ?? null; await fetch("/api/checkout", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ referralCode }), }); ``` ```ts Server (TypeScript SDK) theme={null} const { referralCode } = await request.json(); const checkout = await creem.checkouts.create({ productId: "prod_xxxxx", ...(referralCode && { metadata: { referral_code: referralCode } }), }); // send the customer to checkout.checkoutUrl ``` **6. Report signups (optional)** If people create an account on your site before they pay, report the signup while the partner's code is still in their browser: ```js theme={null} // after a successful signup, with the email they signed up with Refgrow(0, "signup", "user@example.com"); ``` Refgrow records the signup under the partner. A later Creem payment with the same email is credited to that partner even if the checkout carries no metadata, for example when the buyer pays from your app a week later on another device. **7. Test, then go live** Create a key in Creem's **Test Mode** (it starts with `creem_test_`) and connect it to a separate Refgrow project, so test sales stay out of your real program. Open your site with `?ref=PARTNER_CODE`, click a payment link and pay with a [test card](/getting-started/test-mode). The sale appears under the partner, and Refgrow's **Integration** page lists every webhook it received and what it did with it. Then refund the payment in Creem and check that the commission is reversed. Use a real test payment rather than **Send test event** in Creem. Test events carry no metadata, so they can't be credited to a partner. When it works, create a live key the same way and connect it to your real Refgrow project. ## Partner discount codes A discount code credits a partner without a link, for partners who promote by voice or video. Create the discount in your Creem store, then give the same code to the partner in Refgrow. A sale that uses the code is credited to that partner, with or without metadata. ## What Gets Tracked | Event | What happens | | - | - | | One-time sale | Commission recorded from `checkout.completed` | | First subscription payment | Commission recorded once, whichever of `checkout.completed` and `subscription.paid` arrives first | | Subscription renewal | Commission from each `subscription.paid`, on its `last_transaction`, for the same partner | | Refund | Commission reduced in proportion for a partial refund, removed for a full one | | Chargeback | Commission reversed in full when the dispute opens | | Cancellation | Commission already earned is kept | | Discount code | A sale using a partner's code credits them, even without a link | Percentage commissions use what the customer paid after discounts, minus the tax Creem collected. Every payment is keyed by its Creem transaction, so webhook retries and manual resends don't count twice. ## Good to Know * **Short links and storefronts.** The script also adds the code to `l.creem.io` short links and [storefront](/features/storefronts) pages, but Creem drops it before checkout. On your site, link to the payment link itself. * **Partners who link to Creem directly.** A partner link that skips your site never loads the script, so no code is attached. Give those partners a discount code. * **Won disputes.** Creem sends no event when you win a dispute, so Refgrow doesn't restore a commission it reversed on `dispute.created`. To pay the partner anyway, open the partner's menu under **Affiliates** in Refgrow and choose **Add a sale manually**. * **Signature failures.** Each Creem webhook has its own signing secret. If you re-create Refgrow's webhook by hand, or add a second webhook pointing at Refgrow, deliveries signed with the other secret fail. Keep one webhook for Refgrow, then connect again or paste that webhook's secret. * **Disconnecting.** Click **Disconnect** next to Creem on Refgrow's **Integration** page. Refgrow removes its webhook from your store, and does the same when you delete the Refgrow project. If Creem can't be reached at that moment, Refgrow names the webhook for you to delete. * **Webhook log.** Refgrow's **Integration** page shows each Creem event it received and what it did with it, which is the quickest way to see why a sale was or wasn't credited. > [card] [Refgrow's Creem guide](https://refgrow.com/docs/creem?utm_source=creem\&utm_medium=docs) > > Refgrow's own setup guide for the Creem integration, with troubleshooting. # Rekomi Affiliate Program Integration Source: https://docs.creem.io/integrations/rekomi Set up an affiliate program on your Creem store. One webhook connects the two, and Rekomi tracks every sale, then pays your affiliates in 150+ countries. > [!NOTE] > > Creem also has a [built-in affiliate program](/features/affiliate-program) that runs inside your > Creem dashboard. This guide covers connecting a third-party affiliate platform instead, or > alongside it. ## Overview [Rekomi](https://rekomi.com) is affiliate tracking and management software that plugs straight into Creem. Someone shares an affiliate link, Rekomi records the click, and when that visitor buys, the sale arrives from Creem and the right affiliate is credited automatically. Rekomi works out the commission and pays your affiliates for you, in 150+ countries. Setup is small on purpose. You add one webhook in Creem, paste two values into Rekomi, and pass one extra field through your checkout. There is no relay service to build and nothing to host. From then on, sales, subscription renewals, refunds, and chargebacks all arrive through that single webhook. > [accordion] What you'll learn > > How to connect your Creem store to Rekomi, how to carry the affiliate referral through Creem checkout, and how to confirm that commissions and clawbacks are tracking correctly. > [card] What you'll need > > * A Creem account in production mode > * A Rekomi account ([start a free trial](https://app.rekomi.com/sign-up)) > * A Creem API key with the `products:read` scope ## How It Works Creem hosts checkout on its own domain, so the affiliate referral needs a way to travel from your site into the sale. That is the one piece you wire up yourself, and it is a single metadata field. Here is the whole flow: * A visitor clicks an affiliate link and lands on your site, and the Rekomi script stores the referral in their browser. * They go to checkout, and you attach that referral to the Creem checkout as `rekomi_ref` metadata. * Creem processes the payment and sends a signed webhook to Rekomi. * Rekomi matches the referral to the affiliate, calculates the commission, and records it. Your API key is only used to validate the connection and run a periodic read-only health check. Sales never come through the API, they arrive on the signed webhook, which is why a `products:read` key is all you need to hand over. > [!NOTE] > > Rekomi reads `rekomi_ref` from checkout metadata. Creem's [built-in affiliate > feature](/features/affiliate-program) uses its own `creem_ref` URL token, which never ends up in > your metadata, so you can run both side by side. ## Integration Steps Five steps, about ten minutes. ### 1. Open the Creem setup page in Rekomi > [accordion] Get your webhook URL > > In Rekomi, open **Setup > Connect payment processor** and choose Creem. The page gives you a webhook URL that is unique to your workspace, plus the two fields you will fill in shortly. > > Keep this tab open, you will come back to it in step 3. ![Rekomi showing the per-workspace Creem webhook URL to copy, with a reminder to select all events](https://mintcdn.com/creem/q5G_lnYAqoN3ondA/images/rekomi/webhook-url.png?fit=max\&auto=format\&n=q5G_lnYAqoN3ondA\&q=85\&s=e8ae937ba4c34cabc465d47827a35ceb) Step 1 in Rekomi: copy your workspace's webhook URL. ### 2. Add the webhook in Creem > [accordion] Create the endpoint > > In your Creem dashboard, go to **Developers > Webhooks** and click **Add Webhook**, then: > > * Give it a name you will recognize later, for example "Rekomi" > * Paste the webhook URL from step 1 > * Select **all events** ![Creem's Create Webhook form with the name and URL fields and all 13 event types selected](https://mintcdn.com/creem/q5G_lnYAqoN3ondA/images/rekomi/webhook-events.png?fit=max\&auto=format\&n=q5G_lnYAqoN3ondA\&q=85\&s=48dd48bf917200284a3bd67c06458105) Step 2 in Creem: use Select All so the counter reads 13 of 13 events selected. > [!WARNING] > > Please select every event type. The quickest way is the **Select All** button, which should leave > the counter reading 13 of 13. Rekomi quietly ignores the events it does not need, but a partial > selection is accepted without complaint and then drops sales, with no error shown anywhere. If > tracking ever goes quiet, this is the first thing to check. ### 3. Create an API key and connect > [accordion] Create the key > > In Creem, go to **Developers > API Keys** and create a key with the `products:read` scope. > > Use a production key. If you paste a `creem_test_` key into a production connection, Rekomi tells you > so before anything is saved. ![Creem's Create API Key dialog showing the resource permission matrix with read and write columns](https://mintcdn.com/creem/q5G_lnYAqoN3ondA/images/rekomi/api-key-scopes.png?fit=max\&auto=format\&n=q5G_lnYAqoN3ondA\&q=85\&s=0521b22c7d11a81dd16bfc55bac5c6a9) Step 3 in Creem: tick READ on Products. Nothing else is needed. > [accordion] Paste both values into Rekomi > > Back on the Rekomi setup page: > > * Paste the **webhook signing secret** from Creem's webhook page, including its prefix > * Paste the **API key** > * Click **Connect Creem** > > Rekomi checks the key against Creem before accepting it, so you find out straight away if something > is off. ![The Rekomi connect form with fields for the Creem webhook signing secret and API key](https://mintcdn.com/creem/q5G_lnYAqoN3ondA/images/rekomi/connect-form.png?fit=max\&auto=format\&n=q5G_lnYAqoN3ondA\&q=85\&s=821c13154c2c75fdde32b6ff69604771) Step 3 in Rekomi: paste the signing secret and API key, then connect. ### 4. Add the Rekomi script to your site > [accordion] Install the tracking script > > Drop this into the `` of your marketing site so affiliate clicks get captured: > > ```html theme={null} > > ``` > > Your program ID is in Rekomi under **Setup > Install**. The script remembers the referral and exposes > `window.Rekomi.getReferral()`, which you will use in the last step. ### 5. Pass the referral into checkout > [accordion] Attach rekomi_ref to the sale > > This is the step that connects a click to a sale, so it is worth getting right. Without it, sales > arrive with no referral attached and no commission is credited. > > Pick whichever matches how you sell: > > ```json Checkout API theme={null} > { > "product_id": "prod_your_product", > "metadata": { "rekomi_ref": "REFERRAL_FROM_YOUR_FRONTEND" } > } > ``` > > ```js Payment links theme={null} > const ref = window.Rekomi?.getReferral?.(); > const url = new URL("https://www.creem.io/payment/prod_your_product"); > if (ref) url.searchParams.set("metadata[rekomi_ref]", ref); > // use url.toString() as the href on your Buy button > ``` > > If you create checkout sessions on your server, read the referral in the browser with > `window.Rekomi.getReferral()` and send it along with the rest of your checkout request. > [!TIP] > > Creem carries checkout metadata onto the subscription, so renewals keep crediting the same > affiliate without you doing anything extra. ## What Gets Tracked Once you are connected, these all happen on their own: | Event | What happens | | - | - | | One-time sale | Commission credited when the checkout completes | | Subscription renewal | Recurring commission at the amount actually charged | | Trial start | Recorded, but no commission until the first real payment | | Refund | Commission clawed back proportionally, never past the original amount | | Chargeback | Disputed amount clawed back, without double counting a matching refund | Commissions are calculated on the pre-tax sale amount, in both of Creem's tax modes. As Merchant of Record, Creem collects the tax, and your affiliates earn on the sale rather than on the tax. With `tax_mode: exclusive` the tax sits on top of your price, and with `tax_mode: inclusive` your price already contains it. Rekomi works out the net from what the customer paid less the tax line, so an inclusive-priced product never pays commission on its own VAT. Everything is de-duplicated by the underlying order, transaction, refund, and dispute ID, so redeliveries and manual resends never count twice. ## Good to Know * **Check the event selection first.** A webhook saved with only some events ticked is the most common problem, and it fails quietly. It is worth a look before anything else. * **Try a real purchase.** Click an affiliate link, buy something, confirm the conversion shows up in Rekomi within a minute, then refund it and watch the commission come back off. * **Watch the event state, not just the key check.** Rekomi's key only has `products:read`, so Rekomi can confirm the key works but cannot see whether your endpoint still exists. The setup page handles this for you: it stays amber until a real delivery lands, and says so again if events go quiet. * **Re-created the webhook? Update the signing secret.** Deleting and re-creating the endpoint in Creem gives you a new secret. Until you paste it in, deliveries fail their signature check even though the API key still looks fine. * **After an outage, resend from Creem.** Creem retries with increasing delays for several hours. Past that, resend the delivery from your Creem dashboard, and Rekomi will record it without duplicating anything. > [card] [Full setup guide](https://rekomi.com/docs/brands/install/creem) > > Troubleshooting, security details, and the complete Creem reference in Rekomi's own docs. # Strapi Source: https://docs.creem.io/integrations/strapi Manage Creem products and checkout directly from your Strapi 5 admin panel. ## Overview [Strapi](https://strapi.io/) is a leading open-source headless CMS for structuring content and building flexible APIs. The [`@creem_io/strapi`](https://www.npmjs.com/package/@creem_io/strapi) plugin brings Creem's billing capabilities directly into your Strapi 5 admin panel, so you can create products, configure checkout, and receive verified webhooks without leaving your CMS. Creem acts as the legal seller of record. VAT, GST, and sales tax across 190+ countries are calculated, collected, and remitted for you, making this pairing especially useful when your Strapi project is the operational hub for a product you sell globally. > [accordion] What you'll learn > > How to install and configure the Creem plugin for Strapi 5, manage products from the Strapi admin, wire up a front-end checkout through Strapi's content API, and receive verified Creem webhook events. > [card] Requirements > > * A [Creem account](https://creem.io/) with at least one API key > * A Strapi 5 project (or create one during this guide) > * Node.js v22 or later ## Create a Strapi project Open your terminal and scaffold a new Strapi project with their CLI: ```bash theme={null} npx create-strapi@latest my-strapi-app ``` When prompted, configure the CLI options (such as database setup) according to your preferences. Once that is done, move into the project directory and start the app in development mode by executing the following command: ```bash theme={null} cd my-strapi-app npm run develop ``` The Strapi admin panel will be available at `http://localhost:1337/admin`. Complete the initial registration so you can sign in after installing the plugin. ## Install the Strapi plugin To install the plugin, run the following command: ```bash theme={null} npm i @creem_io/strapi ``` Then, restart Strapi instance after installation: ```bash theme={null} npm run develop ``` After restarting, you should see the Creem plugin appear in the left sidebar. ![Strapi admin home with Creem plugin in the sidebar](https://mintcdn.com/creem/_0_83JTNl3wb3znh/images/strapi/strapi-admin-home.png?fit=max\&auto=format\&n=_0_83JTNl3wb3znh\&q=85\&s=c40dc44a966f5fcd0d7922d073086847) Strapi admin home with the Creem plugin visible in the left sidebar ## Configure environment variables ### API Keys Get at least one API key from the [Creem dashboard](https://creem.io/dashboard) under **Developers**. Test and production keys are separate; test keys are typically prefixed with `creem_test_`. | Variable | When you need it | | - | - | | `STRAPI_CREEM_TEST_API_KEY` | Test Mode (`https://test-api.creem.io/v1`) | | `STRAPI_CREEM_API_KEY` | Production (`https://api.creem.io/v1`) | ### Webhook Secret (optional) | Variable | Purpose | | - | - | | `STRAPI_CREEM_WEBHOOK_SECRET` | Signing secret from **Developers → Webhook** so Strapi can verify the `creem-signature` header | Once obtained, add these variables to your Strapi project's `.env`: ```bash theme={null} # API Keys STRAPI_CREEM_TEST_API_KEY="creem_test_..." STRAPI_CREEM_API_KEY="creem_..." # Webhook Secret STRAPI_CREEM_WEBHOOK_SECRET="..." ``` Restart your Strapi project for changes to take effect: ```bash theme={null} npm run develop ``` ## Access the plugin Open the admin panel again and then open **Strapi 5 Plugin for Creem** in the left sidebar. ![Creem plugin products page, empty initial state](https://mintcdn.com/creem/_0_83JTNl3wb3znh/images/strapi/strapi-creem-products-empty.png?fit=max\&auto=format\&n=_0_83JTNl3wb3znh\&q=85\&s=a15ae22cd50be6060b093a5d108a3fa3) The Creem products page on first open, before any products are created When you first open the Creem panel, it fetches and displays all products from [the Creem API](https://docs.creem.io/api-reference/endpoint/search-products). You can then manage these products directly within your Strapi instance. ## Manage products Click **+ New Product** to open the create form. ![Create product modal in the Strapi Creem plugin](https://mintcdn.com/creem/_0_83JTNl3wb3znh/images/strapi/strapi-creem-create-product.png?fit=max\&auto=format\&n=_0_83JTNl3wb3znh\&q=85\&s=ec3c1ed7af7bfd8b4d84a48d2437273d) The create product form with options for payment type, price, currency, and optional features Supported options include: * **One-time** and **subscription** products (including free products with price `0`) * **Billing interval** for subscriptions (daily, monthly, every 3 months, every 6 months, yearly) * **Currency** selection (USD or EUR) * The list view excludes archived products > [!NOTE] > > **Edit** and **archive** open the [Creem dashboard](https://www.creem.io/dashboard) directly. The Creem API does not support those operations through this plugin yet. ## Front-end checkout The Strapi plugin exposes a checkout route through Strapi's [Content API](https://docs.strapi.io/cms/api/content-api). ``` POST /api/@creem_io/strapi/checkout ``` ![Checkout integration modal with embed snippet and JavaScript](https://mintcdn.com/creem/_0_83JTNl3wb3znh/images/strapi/strapi-creem-checkout-integration.png?fit=max\&auto=format\&n=_0_83JTNl3wb3znh\&q=85\&s=c6c6f0bac40d53219f7b0237edd0fae2) The checkout integration modal showing the ready-to-use embed snippet and script Your front end talks to **Strapi**, not directly to Creem, so API keys never reach the browser. The server creates a Creem checkout session and returns `{ "url": "..." }` for redirect. **Example request body:** ```json theme={null} { "productId": "prod_abc123", "customer_email": "customer@example.com", "success_url": "https://your-site.com/success", "metadata": { "order_id": "ORDER_123" } } ``` The plugin also generates a ready-to-use **embed snippet** per product. Copy it from the product's embed dialog and drop it into your site with no extra dependencies. ## Configure environment and webhook forwarding To configure the environment and webhook forwarding settings in Strapi, open the Strapi admin sidebar and click on **Settings**. ![Settings entry in the Strapi admin sidebar](https://mintcdn.com/creem/_0_83JTNl3wb3znh/images/strapi/strapi-settings-navigation.png?fit=max\&auto=format\&n=_0_83JTNl3wb3znh\&q=85\&s=5d8d9b78377a1fcca1f4ef3d56a625a6) Open Settings from the Strapi admin sidebar Click on **Configuration** within the Creem section to open the configuration panel for the plugin. ![Creem Configuration under Settings in the Strapi admin](https://mintcdn.com/creem/_0_83JTNl3wb3znh/images/strapi/strapi-creem-settings-menu.png?fit=max\&auto=format\&n=_0_83JTNl3wb3znh\&q=85\&s=213cc004b5421d88a716fd435115b655) The Creem section under Settings where you click Configuration to open the plugin settings On this page, you'll be able to set the environment, default checkout success URL, and webhook forwarding options. ![Creem plugin Configuration page](https://mintcdn.com/creem/_0_83JTNl3wb3znh/images/strapi/strapi-creem-configuration.png?fit=max\&auto=format\&n=_0_83JTNl3wb3znh\&q=85\&s=3dfff25d1e2760ab42a4bd8019497102) Plugin configuration page for setting the environment, checkout success URL, and webhook forwarding | Setting | Description | | - | - | | **Environment** | Choose **Test mode** or **Production**. Only environments with a matching `.env` key are selectable. | | **Checkout success URL** | Default redirect after checkout. Per-request `success_url` is used when this is empty. Must be HTTPS in production. | | **Webhook forward URL** | After HMAC-SHA256 verification, the plugin POSTs the parsed event JSON to this URL. Useful for provisioning access, updating user records, or triggering email automation. | ## Register the webhook in Creem 1. In the [Creem dashboard](https://creem.io/dashboard), go to **Developers → Webhook**. 2. Add your public HTTPS endpoint: **Production / staging:** ``` https://your-deployed-strapi-instance.com/api/@creem_io/strapi/webhook ``` **Local development** (Creem cannot reach `localhost` directly, so expose your local Strapi with a tunnel first): ```bash theme={null} ngrok http 1337 ``` Then use the tunnel URL: ``` https://abcd.ngrok.io/api/@creem_io/strapi/webhook ``` 3. Copy the signing secret and set `STRAPI_CREEM_WEBHOOK_SECRET` in your Strapi `.env`. 4. Restart Strapi. The plugin responds with **HTTP 200** on successful verification. If a **Webhook Forward URL** is configured, the verified payload is forwarded there automatically. ![Forwarded Creem webhook event received at a webhook forward URL](https://mintcdn.com/creem/_0_83JTNl3wb3znh/images/strapi/strapi-creem-webhook-forward-example.png?fit=max\&auto=format\&n=_0_83JTNl3wb3znh\&q=85\&s=1e77ce2d97aab62831b39d3d437d3a41) A forwarded Creem webhook event received at the configured forward URL See the [Creem webhooks guide](/code/webhooks) for all supported events (`checkout.completed`, `subscription.active`, `subscription.paid`, `subscription.canceled`, `refund.created`, and more). ## Resources > [card] [@creem_io/strapi on npm](https://www.npmjs.com/package/@creem_io/strapi) > > Install the plugin and view release history. > [card] [Creem webhooks guide](/code/webhooks) > > Signature verification, event types, and payload examples. > [card] [Strapi Content API](https://docs.strapi.io/cms/api/content-api) > > Strapi's REST content API reference. > [card] [Creem quickstart](/getting-started/quickstart) > > Get your first API key and create a test product. # Account Reviews Source: https://docs.creem.io/merchant-of-record/account-reviews/account-reviews Learn how account reviews work on Creem and what you need to get approved. Before you can accept live payments through Creem, your store needs to pass an account review. This page gives you the core checklist. If you need next-step guidance after a rejection, use the [Re-Review Guide](/merchant-of-record/account-reviews/re-review-guide). If you're building an AI image or video product, also read [AI Wrapper Compliance](/merchant-of-record/account-reviews/ai-wrapper-compliance). > [!TIP] > > The fastest approvals happen when your product is already live on its own domain, your legal pages are visible, and your support email matches what appears on your website. ## Approval checklist | Requirement | Details | | - | - | | **Product is live** | Your product is ready for production. Still building? Use [Test Mode](/getting-started/test-mode) first. | | **Own custom domain** | Your website runs on your own custom domain. Shared URLs such as social media profiles, marketplace or checkout pages, and free hosting subdomains are not accepted. | | **No false information** | No fake reviews, testimonials, or inflated user/customer counts on your website. | | **Privacy Policy & Terms of Service** | Both legal pages must be present and accessible on your website. | | **Product clearly visible** | We must be able to understand what you're selling from your website or landing page. | | **No trademark conflicts** | Your product name must not infringe existing trademarks or create customer confusion. | | **Pricing is visible** | Pricing must be clearly displayed and easy for users to find. | | **Acceptable use** | No high-risk, shady, or illegitimate use cases. | | **Customer support email** | A reachable support email must be set up and shown on your website and receipts. | | **Moderation API** | AI image/video generation products must integrate the [CREEM Moderation API](/features/moderation). | | **Not on prohibited list** | Your product must not fall under our [prohibited product list](#prohibited-products). | ### Why a custom domain is required Customers and payment partners rely on your website to know who they are buying from. A custom domain shows that your business is established, stays under your control, and belongs to you. That is why every Creem store needs a website on its own custom domain before it can accept live payments. **Accepted:** a domain you own, such as `yourbrand.com`, or a subdomain of it, such as `app.yourbrand.com`. **Not accepted:** * Free hosting subdomains, such as `yourapp.vercel.app`, `yourapp.netlify.app`, `yourname.github.io`, `yourapp.pages.dev`, Notion or Google Sites pages * Social media profiles and channels, such as Instagram, Facebook, YouTube, TikTok, X or Telegram * Design and file share links, such as Canva links or Google Drive folders * Marketplace and checkout pages, such as Gumroad, Payhip or Whop pages, or a Creem checkout link * Code repositories, such as a GitHub repo ## Review process ### How long does the review take? Account reviews are typically completed within **1-2 working days**. During peak periods, it may take up to 3 working days. You'll receive an email notification once the review is complete, if changes are requested, or if the account is rejected. ### What happens after the review? * **Approved** - Your store can start accepting live payments. * **Changes requested** - Fix the flagged issues, then use the **Request re-review** button on the **Balance → Payout Account** page. * **Rejected** — We aren't able to support this business on Creem. This is a final decision for this store, and there's no **Request re-review** button for it. See [If your account was rejected](/merchant-of-record/account-reviews/rejected-accounts). ### Where do I start the review? Go to **Balance → Payout Account** and click **Set up Payout Account** to submit your details. ![Creem Balance page showing Payout Account tab with test mode notice](https://mintcdn.com/creem/fm2TYBwopS74uc7h/images/payout-account-test-mode.png?fit=max\&auto=format\&n=fm2TYBwopS74uc7h\&q=85\&s=ee2b358e55cd68173e429fdaa05e69d0) Navigate to Balance → Payout Account to start the review process. Payout accounts are only available in live mode. ### What information is needed? * Your full individual name and/or your business entity name * Your store or product name * Your website URL, on your own custom domain * A description of your business and how you operate * A description of the products you intend to sell through Creem * Your country of tax residence > [!NOTE] > > As part of onboarding and ongoing compliance monitoring, CREEM may perform a limited test purchase > to verify the customer experience and product functionality. To make this process frictionless, we > may create and apply a one-time 100% discount code. You may see a zero-value test order and > limited product usage associated with the review. Testing is limited to verification purposes and > kept to the minimum reasonably necessary. ### Common reasons for requests for changes 1. **Support email mismatch** - The email in your Business Details doesn't match what's on your website. 2. **Website not accessible** - Your site is down, password-protected, or returning errors during review. 3. **No custom domain** - Your website URL is not on your own custom domain. 4. **Missing legal pages** - Your website needs a Privacy Policy and Terms of Service. 5. **False information** - Fake reviews, testimonials, or inflated user counts on your website. 6. **Product not ready** - If your product isn't live yet, use [Test Mode](/getting-started/test-mode) until it's ready. 7. **AI compliance issues** - AI image/video products are missing moderation, AUP, or clear product disclosures. > [card] [Re-Review Guide](/merchant-of-record/account-reviews/re-review-guide) > > What to fix and how to request another review. > [card] [AI Wrapper Compliance](/merchant-of-record/account-reviews/ai-wrapper-compliance) > > Extra rules for AI image and video generation products. > [card] [Gen AI Requirements](/merchant-of-record/account-reviews/gen-ai-requirements) > > Why Gen AI products must integrate Customer Credits and the Moderation API. > [card] [Gen AI Technical Integration Guide](/merchant-of-record/account-reviews/gen-ai-technical-integration-guide) > > Step by step setup of the credit wallet and moderated debits. ## Why do we review accounts? We review accounts to ensure stores are legitimate and in compliance with our terms. This helps prevent fraud, misuse, malicious activity, and high-risk accounts. ## Product guidelines ### Acceptable products > [accordion] Examples of products we support > > We allow digital goods that can be fulfilled through Creem. Examples include: > > * Software & SaaS > * eBooks > * PDFs > * Design assets > * Photos > * Audio > * Video ### Prohibited products > [!WARNING] > > If you attempt to sell prohibited products or violate our terms, your account may be placed in review or suspended. > [accordion] Full list of prohibited products > > * Physical goods of any kind, including, but not limited to, illegal or age-restricted products such as drugs, alcohol, tobacco, vaping products, or weapons, as well as pharmacy, pharmaceutical, and nutraceutical products > * Weapon-related digital goods, including, but not limited to, 3D-printable firearm or weapon files, firearm, suppressor, or weapon blueprints, and explosives or weapons manufacturing guides > * Trading and investment tools and services that enable or facilitate trade execution or automation, including, but not limited to, trading bots, expert advisors (EAs), automated strategies, and copy trading or mirror trading services > * IPTV services, including, but not limited to, IPTV subscriptions, IPTV reseller panels and credits, M3U playlists and playlist stores, M3U and IPTV player apps (with or without preloaded content), Xtream Codes logins, restreaming services, sports or pay-per-view streaming passes, and preloaded devices or apps (such as Firestick setups or Kodi builds) that give access to third-party channels or content > * Online traffic and engagement services, including, but not limited to, followers, likes, views, comments, subscribers, fake or incentivized reviews, bot traffic, and PBN or paid backlinks > * Account and subscription resale, including, but not limited to, shared or resold seats for streaming, music, or AI subscriptions, aged or verified social media accounts, and bulk email or platform accounts > * Donations or charity giving where no product exists or where the price is greater than the product value > * Counterfeit or unauthorized products and content for which you do not hold the required licenses, intellectual property rights, or resale rights, including, but not limited to, PLR or MRR products, cracked or pirated software, grey-market or resold license keys, leaked or ripped courses, and modded versions of paid apps > * Face-swap, deepfake, and face-manipulation tools of any kind, including, but not limited to, nudify or undress apps > * Sexually-oriented or pornographic content and AI companion or relationship chatbots of any kind, including AI-generated content, NSFW chatbots, and romantic AI characters > * Telecommunications and connectivity products such as eSIMs, SIM cards, mobile data plans, calling plans, VoIP services, wireless carriers, internet service providers, VPN services, or residential and mobile proxy networks > * Spyware or parental control apps, including, but not limited to, phone trackers, location trackers, keyloggers, and SMS, call, or messaging app monitoring tools > * Third-party content downloaders and rippers that violate platform Terms of Service, including, but not limited to, YouTube, TikTok, Instagram, or Spotify downloaders, streaming service rippers, and DRM removal tools > * Remote digital file-sharing services and cyberlockers > * Dating sites > * Gambling and games of chance, including, but not limited to, casinos, betting, sweepstakes, lotteries, fantasy sports, prediction markets, skill-based games with cash prizes, and matched betting > * Regulated services such as lending, telemarketing, debt relief, or banking/financing services > * Gift cards and stored value that can be spent outside your own product, including, but not limited to, gift cards for other brands or retailers, open-loop prepaid cards, balances that can be transferred or redeemed for cash, and mobile credit top-ups. Credits, points, or prepaid balances that can only be spent within your own product, such as those built with [Customer Credits](/features/customer-credits/introduction), are allowed > * Fake or fraudulent documents, including, but not limited to, generators or templates for IDs, passports, receipts, invoices, bank statements, pay stubs, or doctor's notes > * Hacking, fraud, and platform-abuse tools, including, but not limited to, malware, DDoS stressers or booters, OTP or 2FA bypass tools, carding or "method" guides, captcha-solving services, and antidetect or multi-account browsers > * Personal data products, including, but not limited to, the sale of scraped or purchased email, phone, or lead lists or contact databases, and people-search or background-check services. B2B lead generation and data enrichment software is a restricted product (see below) > * Get-rich-quick and make-money-online schemes, including, but not limited to, products that promise guaranteed income, earnings, or returns > * Metaphysical, fortune-telling, and spiritual outcome services > * Timeshares > * Homework/essay mills > * Multi-level marketing, pyramid, or IBO schemes > * NFT & crypto asset products > * In-game items, currencies, accounts, boosting services, and virtual goods tied to third-party games, including automation or account-management software that violates the game publisher's Terms of Service > * Products that operate marketplaces or facilitate third-party merchant-funded customer payouts, including cashback, rebates, referral payouts, rewards, or similar payments from merchants to customers > * Any other products that our providers and partners deem too risky ### Restricted products > [accordion] Products subject to strict due diligence > > * Services of any kind, including, but not limited to marketing, design, web development, consulting, and similar work > * Job boards > * Advertising in newsletters, on websites, or in social media posts > * API resellers > * B2B lead generation and data enrichment software > * Generative AI products, including, but not limited to text-to-image and text-to-video generation tools > * Trading and investment communities, signal groups, courses, and educational products that do not enable trade execution or automation. Communities and signal groups must publish a clear, documented methodology (such as entry and exit rules, risk management, and markets traded) and a timestamped record of past signals that cannot be edited after the fact, such as a public channel history or a third-party verified track record. Meeting these requirements makes a product eligible for review, but approval is not guaranteed > > All restricted products require additional verification, including previous payment processor details, chargeback/refund rate, and reason for moving to Creem. An established and proven track record is required for consideration. If you are unsure whether your content is prohibited, contact Creem support with a description or example before you start selling. ## Customer experience and support Providing excellent customer support is a core requirement for all merchants on Creem. * **A visible support email is mandatory.** This email must be accessible on your public website and within the user dashboard. * **Use a branded support email.** If your product is `MintAI`, your support email should be `support@mintai.com`, not a generic address. * **Users must be able to cancel subscriptions directly from your product.** You can do this via the Cancel Subscription API or by redirecting users to the Creem Customer Portal. * **Respond to customer requests within 3 business days.** If you do not respond within that timeframe, Creem may issue a refund on your behalf. # AI Wrapper Compliance Source: https://docs.creem.io/merchant-of-record/account-reviews/ai-wrapper-compliance Extra review requirements for AI image and video generation products on Creem. AI image and video generation products have extra compliance requirements on top of the standard [Account Reviews](/merchant-of-record/account-reviews/account-reviews) checklist. > [!WARNING] > > Failure to comply with these policies can result in your payment processing being restricted or suspended. ## Branding and naming Your product's brand identity must be distinct from the underlying AI models it uses. ### Not allowed * Using AI model brand names directly in your product name, such as `VEO3Studio` or `GeminiVideo` * Creating branding that implies affiliation with the model creator when there is none ### Required * Use independent branding for your product. Choose a name that is unique and does not directly reference the AI models. Examples of compliant names include `MintAI`, `RenderZen`, or `SlateVidAI`. * If you mention supported models in your app or marketing, make it clear they are integrations, not your brand * SEO-focused domains are fine if they redirect to your properly branded main site ## Transparency and marketing Be explicit about what your product is and what it does. * Clearly explain that your platform is an independent wrapper or interface built on top of third-party AI models * Advertise only the features you actually deliver * If you mention model names in ads or marketing, include a disclaimer that your product is not affiliated with or endorsed by the model creators **Example disclaimer:** `This platform is an independent product and is not affiliated with Google. We provide access to the VEO3 model through our custom interface.` ## Moderation API requirement If your product generates or edits images or videos, every generation must go through the [CREEM Moderation API](/features/moderation). That includes generations without user text, such as fixed templates, gallery re-runs, upload-only edits and upscaling. This requirement applies to AI **image and video** products only. It does not apply to products that only generate audio, music or text. Paid generations must also run on [Customer Credits](/features/customer-credits/introduction), with every credit spend linked to a moderation result. See [Gen AI Requirements](/merchant-of-record/account-reviews/gen-ai-requirements) for why, and the [Gen AI Technical Integration Guide](/merchant-of-record/account-reviews/gen-ai-technical-integration-guide) for the step by step setup. > [card] [Gen AI Requirements](/merchant-of-record/account-reviews/gen-ai-requirements) > > Why Gen AI products must integrate Customer Credits and the Moderation API. > [card] [Gen AI Technical Integration Guide](/merchant-of-record/account-reviews/gen-ai-technical-integration-guide) > > Step by step setup of the credit wallet and moderated debits. > [card] [Moderation API Documentation](/features/moderation) > > Full integration guide, endpoint reference, code examples, and go-live checklist. > [!TIP] > > Every image or video generation needs a moderation result, whether the prompt comes from your user, a template or your own pipeline. ## Content policy requirements Even with the Moderation API integrated, the following are still not allowed on CREEM: * Gallery or showcase content featuring suggestive, borderline, or sexually provocative material * Marketing that uses terms like `uncensored`, `no filter`, `NSFW`, `18+`, or `unfiltered generation` * Face-swap, deepfake, and face-manipulation tools ### Additional required policies Your site must include: * A visible **Acceptable Use Policy** that explicitly prohibits NSFW and harmful content generation * Terms of Service that explicitly prohibit NSFW, explicit, or sexually suggestive content generation * Clear user-facing language about what is and is not allowed > [!WARNING] > > CREEM conducts ongoing compliance monitoring and may test AI generation outputs at any time. Merchants are responsible for the content their product enables users to generate. ## Before you request review or re-review Make sure all of the following are true: 1. Your product is live and accessible 2. Your branding is independent from model brand names 3. Your site includes Terms of Service, Privacy Policy, and Acceptable Use Policy 4. Your Moderation API integration is active in production 5. Your marketing does not promise "uncensored" or prohibited output If you were already flagged, use the [Re-Review Guide](/merchant-of-record/account-reviews/re-review-guide) after making the required changes. # Gen AI Requirements Source: https://docs.creem.io/merchant-of-record/account-reviews/gen-ai-requirements Why AI image and video products on Creem must integrate Customer Credits and the Moderation API. Gen AI is one of the fastest growing categories in the world of AI right now, and one of the riskiest. A model that can generate almost anything can also generate content that breaks Creem's [Terms of Service](https://www.creem.io/terms) and the rules of the payment providers behind every card payment. Creem supports this category with products built for it. If you sell a Gen AI product, your integration must use them before you go live and for as long as you sell on Creem. > [!NOTE] > > These requirements apply to every product or feature that generates or edits images or video, > including generations without user text. See [AI Wrapper > Compliance](/merchant-of-record/account-reviews/ai-wrapper-compliance) for the full scope and the > website requirements. ## Why this integration is required Creem is the merchant of record for every sale on your store. That makes us the seller, and we answer to our payment providers for what your product generates. Promising that you moderate is not enough. Creem needs to show that every paid generation on your product passed a content check. The integration on this page creates that record, and it is what lets Creem accept Gen AI products that most payment platforms turn away. ## What you need to integrate Two Creem products, used together: > [card] [Customer Credits](/features/customer-credits/introduction) > > Each of your users gets a credit wallet. Every purchase adds credits to it, and every generation > spends from it. > [card] [Moderation API](/features/moderation) > > Screens every prompt before it reaches your model. Each credit spend carries the ID of the > moderation result that cleared it. Together they link every payment to the credits it bought, every generation to the credits it spent, and every spend to a screened prompt. That chain lets the Creem compliance team monitor how your product is used, and protects you from issues raised by payment providers or regulators. ## Requirements apply after onboarding too These requirements are not a one time onboarding step. Creem monitors every store in the category daily. > [!WARNING] > > If a Gen AI product stops using the required products, or never integrates them, Creem can > restrict your store or permanently offboard it. In some cases, your payouts and balance can be > frozen. ## You stay responsible for what your product generates Customer Credits and the Moderation API do not replace your own safeguards. You must follow the Creem [Terms of Service](https://www.creem.io/terms) and take every measure needed to stop your product from generating prohibited content, including but not limited to: * Adult, sexual or pornographic content * Deepfakes, face swaps or manipulated images of real people * Any content involving minors * Extreme violence * Terrorism * Illegal activity If your product can generate it, you are responsible for it, whether or not you built the product for that purpose. Check your model setup too: * **Hosted model APIs:** many ship with a safety checker, but it is usually a setting that can be switched off. Some routers do not moderate content at all. * **Self hosted or open weight models:** there are no guardrails unless you add them. See the full [prohibited products list](/merchant-of-record/account-reviews/account-reviews#prohibited-products). ## Requirements can change Customer Credits and the Moderation API are the current requirements for Gen AI products on Creem. The Creem compliance team can change them at any time, by removing a required product or by adding new products, workflows or procedures that your product must integrate for Creem to keep supporting it. This page always shows the current requirements. ## Next steps > [card] [Technical Integration Guide](/merchant-of-record/account-reviews/gen-ai-technical-integration-guide) > > A step by step tutorial for integrating Customer Credits and the Moderation API into your Gen AI > app's generation workflow. > [card] [AI Wrapper Compliance](/merchant-of-record/account-reviews/ai-wrapper-compliance) > > General guidelines for onboarding an AI product on Creem: what is allowed, what is not, and what > your website needs. # Technical Integration Guide Source: https://docs.creem.io/merchant-of-record/account-reviews/gen-ai-technical-integration-guide Step by step: integrate Customer Credits and the Moderation API into your Gen AI app. New to the Gen AI requirements? Start with [Gen AI Requirements](/merchant-of-record/account-reviews/gen-ai-requirements) to see why this integration is required. ## Before you start: your app runs on credits The whole setup is built on one idea: **every user of your app has a credit balance**. Users buy credits, and every generation spends them. This applies whether your users top up through a subscription, a one time credit pack, or a usage based plan. If your app doesn't work with a balance yet (credits, tokens, coins or any other unit), that is the first change to make. Everything in this guide builds on it. With [Customer Credits](/features/customer-credits/introduction), Creem keeps that balance for you in a fully audited ledger. You credit, debit and read each user's balance through the API, without writing ledger code and without storing balances in your own database. * **Purchases credit the balance automatically.** When a user buys a credit pack or a subscription renews, Creem adds the credits as part of the payment. You never apply purchased credits yourself, so you don't have to handle double crediting, retries, or failed webhooks. * **You can still give credits yourself.** Free credits at signup, rewards or promotions are a single API call. * **Every spend is linked to a screened prompt.** Each debit carries the ID of the [Moderation API](/features/moderation) result that cleared the prompt, so every generation can be traced back to a content check. In this guide you learn how to read and write each user's credit wallet, and how to link a Moderation API call to every credit deduction. ## Key concepts The integration connects five objects through their IDs: | Object | ID | What it is | | - | - | - | | **Customer** | `cust_...` | The Creem customer for one of your users. Its `external_id` is your own user ID. | | **Generation wallet** | `cca_...` | The user's credits account named `generation`. It holds the AI generation credits, and spending from it requires moderation. | | **AI generation credits** | Product feature | A feature on your products. Every purchase or renewal of the product adds its credits to the buyer's generation wallet. | | **Moderation result** | `id` | The Moderation API's decision on one prompt: `allow`, `flag` or `deny`. | | **Debit** | `cct_...` | A credit spend from the generation wallet. It carries the moderation result ID that cleared the prompt. | ## How the flow works In practice, the most common flow looks like this: 1. A user signs up on your app. 2. You create a Creem customer for that user, linked to your own user ID. 3. You create a generation wallet for that customer. 4. The user buys credits, through a subscription or a one time credit pack. 5. Creem adds the credits to the user's wallet automatically. 6. The user wants to generate content. 7. You check that the wallet has enough credits for the generation. 8. You screen the user's prompt with the Moderation API. 9. You debit the wallet, with the moderation result ID attached. 10. You generate the content, and reverse the debit if the generation fails. ```mermaid theme={null} sequenceDiagram participant User participant App as Your app participant Creem participant Model as Your model User->>App: Sign up App->>Creem: Create customer (external_id = user ID) App->>Creem: Create generation wallet User->>Creem: Buy credits (checkout) Creem->>Creem: Add credits to the wallet User->>App: Generate with a prompt App->>Creem: Check balance App->>Creem: Screen prompt Creem-->>App: allow + moderation ID App->>Creem: Debit with moderation ID App->>Model: Generate Model-->>App: Result (or failure: reverse the debit) App-->>User: Result ``` The steps below walk through each part of the flow. ## Step 0: Set up the SDK Install the [TypeScript SDK](/code/sdks/typescript), version 1.14.0 or later, and create one client. Your API key decides the environment: keys that start with `creem_test_` use the sandbox, live keys use production. ```bash theme={null} npm install creem ``` ```typescript lib/creem.ts theme={null} import { Creem } from "creem"; const apiKey = process.env.CREEM_API_KEY!; export const creem = new Creem({ apiKey, // creem_test_ keys use the sandbox, live keys use production server: apiKey.startsWith("creem_test_") ? "test" : "prod", }); ``` ## Step 1: Create a Creem customer for each user When a user signs up, or the first time they open your generator, create a Creem customer and set `external_id` to your own user ID. This links the Creem customer, and the wallet you create next, to your user. ```typescript TypeScript theme={null} const customer = await creem.customers.create({ email: user.email, name: user.name, externalId: user.id, // your own user ID }); await db.users.update(user.id, { creemCustomerId: customer.id }); // cust_... ``` ```bash API theme={null} curl -X POST https://api.creem.io/v1/customers \ -H "x-api-key: $CREEM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "email": "jane@example.com", "name": "Jane Doe", "external_id": "user_123" }' ``` ## Step 2: Create the user's generation wallet Create a credits account named `generation` for the customer. This name makes it the AI generation wallet: every purchase of AI generation credits lands in it, and every spend from it requires a moderation result ID. ```typescript TypeScript theme={null} const wallet = await creem.customerCredits.createAccount({ customerId: customer.id, // cust_... name: "generation", // makes this the moderated AI generation wallet unitLabel: "credits", initialBalance: "20", // optional free credits }); await db.users.update(user.id, { creditAccountId: wallet.id }); // cca_... ``` ```bash API theme={null} curl -X POST https://api.creem.io/v1/customer-credits/accounts \ -H "x-api-key: $CREEM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "customer_id": "cust_...", "name": "generation", "unit_label": "credits", "initial_balance": "20" }' ``` > [!TIP] > > This step is optional: the user's first purchase creates the wallet for you. Creating it up front > lets you store the wallet ID right away and give free credits before the first purchase. > [!NOTE] > > Free credits work like paid ones. Spending them still requires a moderation result ID, and Creem > refuses the debit without one. ## Step 3: Sell credits with AI generation credits Add **AI generation credits** to every product that sells credits for generations: credit packs and subscription plans. When a user pays, Creem adds the product's credits to their generation wallet as part of the payment. Subscriptions add them again on every renewal. You don't need the API for this step. You can create the product in the dashboard instead, or use the API if you manage products in code. > [tab] Dashboard > > 1. Create a new product, or open an existing one, in **Products**. > 2. In **Delivery**, click **Add** and choose **New AI generation credits**. > > ![The Delivery Add menu with New AI generation credits](https://mintcdn.com/creem/o2sgGZzWG3BGrOR_/images/gen-ai/add-ai-generation-credits.png?fit=max\&auto=format\&n=o2sgGZzWG3BGrOR_\&q=85\&s=698b89c6734f63f1b0e634055c13070e) > > Add AI generation credits as a delivery on the product. > > 3. Fill in the **Description**, the **Credit amount** each purchase grants, and the **Unit label**. > 4. For subscriptions, choose whether **Unused credits reset each billing period**. When it's off, unused credits carry over to the next period. > 5. Set the pricing (one time for credit packs, subscription for plans) and save the product. > > ![The AI generation credits form with description, credit amount, unit label and the reset toggle](https://mintcdn.com/creem/o2sgGZzWG3BGrOR_/images/gen-ai/ai-generation-credits-form.png?fit=max\&auto=format\&n=o2sgGZzWG3BGrOR_\&q=85\&s=0c0c20dbe5d5d1c1964b44b98936a6b7) > > The AI generation credits delivery on a monthly subscription. > [tab] API > > ```bash theme={null} > curl -X POST https://api.creem.io/v1/products \ > -H "x-api-key: $CREEM_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "name": "500 credits", > "description": "500 image and video credits", > "price": 900, > "currency": "USD", > "billing_type": "onetime", > "features": [ > { > "type": "customerCredits", > "description": "500 credits", > "customer_credits": { > "amount": "500", > "unit_label": "credits", > "requires_moderation": true > } > } > ] > }' > ``` In the API, `requires_moderation: true` is what makes these AI generation credits. For subscription plans, add `"resets_each_period": true` to expire unused credits at each renewal instead of carrying them over. ## Step 4: Let users buy credits Start the checkout with the customer from Step 1, so the credits land in that user's wallet. ```typescript TypeScript theme={null} const checkout = await creem.checkouts.create({ productId: PACK_500_PRODUCT_ID, customer: { id: user.creemCustomerId }, // the customer from Step 1 successUrl: `${APP_URL}/success`, metadata: { referenceId: user.id }, }); return redirect(checkout.checkoutUrl!); ``` ```bash API theme={null} curl -X POST https://api.creem.io/v1/checkouts \ -H "x-api-key: $CREEM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "product_id": "prod_...", "customer": { "id": "cust_..." }, "success_url": "https://yourapp.com/success" }' ``` When the payment succeeds, Creem adds the credits to the wallet. There is no credit call to write and no webhook to handle. > [!WARNING] > > Don't also add credits from a webhook such as `checkout.completed` or `subscription.paid`. Creem > already adds them, so your users would get the credits twice. To refresh the balance in your UI, > listen for the `credits.granted` webhook instead. ## Step 5: Check the balance before generating Before you screen and generate, check that the wallet has enough credits for the generation, so you can show the user a clear message early. ```typescript TypeScript theme={null} const { balance } = await creem.customerCredits.getAccountBalance(user.creditAccountId); if (Number(balance) < cost) { return needCredits(cost); // ask the user to buy more credits } ``` ```bash API theme={null} curl https://api.creem.io/v1/customer-credits/accounts/cca_.../balance \ -H "x-api-key: $CREEM_API_KEY" ``` > [!NOTE] > > This check is for your user experience. The debit in Step 7 is what actually protects the balance: > if the balance is too low at that moment, it fails with `insufficient_balance` and nothing is > taken. ## Step 6: Screen the prompt Screen the prompt before anything else reaches your model: before you queue, debit or generate. Pass an `external_id` that ties the call to your user and the generation. ```typescript TypeScript theme={null} let mod; try { mod = await creem.moderation.screenPrompt( { prompt, externalId: `user_${user.id}:gen_${genId}` }, { timeoutMs: 5000 }, ); } catch { return block("moderation_unavailable"); // fail closed } if (mod.decision !== "allow") { return block(mod.decision); // "deny" and "flag" both stop here } ``` ```bash API theme={null} curl -X POST https://api.creem.io/v1/moderation/prompt \ -H "x-api-key: $CREEM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "prompt": "a watercolor fox in a snowy forest", "external_id": "user_123:gen_456" }' ``` * **Only `allow` goes through.** `deny` is a block. * **Treat `flag` as a block too.** Screen again, or stop. * **Fail closed.** If the call errors or times out, don't generate. * **Screen every generation.** Fixed templates, gallery re-runs and upscaling need a moderation result too, so screen the prompt that drives them. See the [Moderation API](/features/moderation) for the full response and pricing. ## Step 7: Debit the wallet with the moderation ID Debit the generation wallet and attach the moderation result ID from Step 6 as `moderation_id`. Without a valid one, Creem refuses the debit and nothing is taken. ```typescript TypeScript theme={null} import { CustomerCreditsErrorResponseDto } from "creem/models/errors"; let debit; try { debit = await creem.customerCredits.debitAccount(user.creditAccountId, { amount: String(cost), // for example 5 per image, 40 per video reference: `gen:${genId}`, idempotencyKey: `debit_${genId}`, // one key per generation moderationId: mod.id, // required on the generation wallet }); } catch (err) { if (err instanceof CustomerCreditsErrorResponseDto && err.error.code === "insufficient_balance") { return needCredits(cost); // nothing was debited } throw err; // moderation_* errors: screen again or stop. Nothing was debited. } ``` ```bash API theme={null} curl -X POST https://api.creem.io/v1/customer-credits/accounts/cca_.../debit \ -H "x-api-key: $CREEM_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "amount": "5", "reference": "gen:gen_456", "idempotency_key": "debit_gen_456", "moderation_id": "" }' ``` * **One moderation ID pays for one debit.** If one prompt produces four images, debit all four in one call. * **The moderation result must be recent.** It must be an `allow` decision from your store, at most 24 hours old. * **Use one idempotency key per generation**, so a retry or a double click never charges twice. ## Step 8: Generate, then return or reverse Call your model. If it succeeds, return the result. If it fails after you debited, reverse that exact debit so the user keeps their credits. The wallet history shows both the debit and the reversal. ```typescript TypeScript theme={null} try { const result = await model.generate({ prompt, mediaType }); return ok(result); } catch (err) { // the model failed after the debit: give the credits back try { await creem.customerCredits.reverseTransaction(user.creditAccountId, { transactionId: debit.id, // cct_..., reversals are idempotent }); } catch { await flagForReconciliation(genId); // don't claim a refund that didn't happen return failed("Generation failed. We'll refund your credits shortly."); } return failed("Generation failed, your credits were refunded."); } ``` > [!TIP] > > Prefer to debit after a successful generation? That works too, as long as the debit carries the > moderation ID and happens within 24 hours of the screen. If the user retries after a reversal, > screen the prompt again: each moderation ID can be used once. # How to Request a Re-Review Source: https://docs.creem.io/merchant-of-record/account-reviews/re-review-guide Your account review came back with changes requested. Here is exactly what to do next. If your account review comes back with **Changes Requested**, don't start from scratch. Fix the flagged issues, then request a re-review from your dashboard. > [!NOTE] > > Re-reviews are requested from **Balance → Payout Account** using the **Request re-review** button. If you need help or the feedback is unclear, contact [Creem support](https://creem.io/contact) and include your Store ID. ## Step 1 - Review the feedback Read the review feedback carefully and make a checklist of every issue you need to fix before requesting another review. The most common requests, and how to fix them: | Re-review reason | What to do | | - | - | | **Missing or inaccessible legal pages** | Add a Privacy Policy and Terms of Service to your website. Both must load without authentication. | | **Support email mismatch** | Update your email in **Settings → Business Details** to match what is shown on your website. | | **Moderation API not integrated** | See the [full integration guide](/features/moderation). Your integration must be running in production, not just sandbox. | | **Product not live** | Your product must be accessible and functional - not a placeholder or "coming soon" page. | | **Missing Acceptable Use Policy (AI products)** | Add an AUP to your website that explicitly prohibits NSFW and harmful content generation. | | **No custom domain** | Move your website to your own custom domain, then update the website URL in **Settings → Business Details**. | | **Website inaccessible during review** | Remove any password protection, maintenance mode, or bot wall that blocks the review team. | | **NSFW or "unfiltered" marketing language** | Remove terms like "uncensored," "no filter," "NSFW," or "18+" from your website, marketing pages, and product UI. | > [!NOTE] > > For AI image and video generation products, the most common failure is that the Moderation API is integrated in sandbox mode only, not in production. See [Verify your integration is live](/features/moderation#verify-your-integration-is-live). ## Step 2 - Find your Store ID You will need your Store ID whenever you contact support about a review. Go to **Settings** in your dashboard. Your Store ID starts with `sto_` and is displayed at the top of the page. > [!TIP] > > Save your Store ID somewhere handy. Leading with it makes support much faster. ## Step 3 - Request the re-review Once you've made the required changes: 1. Go to **Balance → Payout Account** 2. Review the **Changes Requested** card 3. Click **Request re-review** ![Balance page showing the Request re-review button](https://mintcdn.com/creem/r2AtyeAVV2JTGpwg/images/request-re-review-button.png?fit=max\&auto=format\&n=r2AtyeAVV2JTGpwg\&q=85\&s=1b1e9bf78972eaf94d91baa627b64e90) After fixing the requested issues, use the Request re-review button in Balance → Payout Account. ## What happens next Re-reviews are typically completed within **1-2 working days**. During peak periods, it may take up to **3 working days**. During the re-review, the team will: * Verify the changes you made are live on your website * For AI products: check that your Moderation API integration is active in production * Confirm no new issues were introduced If more changes are still needed, you'll get another request with specific feedback. ## Common questions > [accordion] I fixed everything but got another change request > > Usually this means one or more changes were incomplete, not visible to the review team, or new issues were introduced. Double-check the exact feedback and make sure every fix is live before requesting another review. > [accordion] My website was working - why did it say inaccessible? > > This is usually caused by maintenance mode, password protection, Cloudflare bot protection, or a regional access block during the review window. Remove those restrictions before requesting a re-review. > [accordion] Can I keep building while I wait? > > Please finalise the requested adjustments before asking for a re-review. But you can carry on testing your CREEM integration while you wait for the review — you just can't take live payments until the account is approved. > [accordion] I wasn't told what to change > > The specific feedback is in the email we sent and in [your dashboard](https://www.creem.io/dashboard/balances/accounts). If it isn't clear, work through all of the items in Step 1 — most accounts that come back have hit more than one, and fixing them all before you resubmit is faster than resubmitting twice. > > If your status is **Rejected** rather than changes requested, this guide doesn't apply — see [If your account was rejected](/merchant-of-record/account-reviews/rejected-accounts). ## Related > [card] [Account Reviews](/merchant-of-record/account-reviews/account-reviews) > > Full checklist and review requirements. > [card] [AI Wrapper Compliance](/merchant-of-record/account-reviews/ai-wrapper-compliance) > > Extra requirements for AI image and video products. > [card] [Gen AI Requirements](/merchant-of-record/account-reviews/gen-ai-requirements) > > Why Gen AI products must integrate Customer Credits and the Moderation API. > [card] [Gen AI Technical Integration Guide](/merchant-of-record/account-reviews/gen-ai-technical-integration-guide) > > Step by step setup of the credit wallet and moderated debits. # If your account was rejected Source: https://docs.creem.io/merchant-of-record/account-reviews/rejected-accounts What a rejection means, how it differs from a request for changes, and where to check your status. Also covers accounts described as failing verification. Most accounts that don't pass review the first time are asked to make changes, not rejected. These are different outcomes with different consequences. Check which one you have before doing anything else. ## Where to check your status Everything about your review sits on your [account page](https://www.creem.io/dashboard/balances/accounts). It shows your current status and the comments explaining what was requested, or why the account was rejected. The verification banner in your dashboard shows which step you're on and where it stands: | Banner status | What it means | | - | - | | **Waiting for Creem review** | We have what we need. Nothing for you to do. | | **Waiting for your input** | Something is needed from you. The account page says what. | | **Rejected** | This step is closed. | ## Which outcome do you have? | Outcome | What it means | | - | - | | **Changes requested** | We found something specific that needs fixing. This is not a rejection. Fix it and request a re-review yourself. See the [Re-Review Guide](/merchant-of-record/account-reviews/re-review-guide). | | **Rejected** | We aren't able to support this business on Creem. Final decision for this store. | > [!NOTE] > > If the **Request re-review** button is available on **Balance → Payout Account**, you have changes requested, not a rejection. ## Identity verification is a separate check Identity and business verification (KYC and KYB) runs separately from the account review. Passing one doesn't decide the other, and the two are easy to confuse. Your verification status appears in the banner as soon as the check completes. Pending means we review within **two working days**. Rejected means the decision is final, with no resubmission for that step. ## If your account was rejected A rejection is a decision about what we're able to support. In almost every case it comes down to one of two things: * **The product falls into a category we can't process for**, under our payment partners' requirements or card scheme rules. * **Risk signals** on the account, the website, or the business behind it. Neither of those changes by resubmitting, by attaching more documentation, or by describing the product differently. We don't re-review a rejected account for the same business. The comments on your account page explain which one applied to you. ## If you want to sell something else Got a genuinely different product? Create a new store for it. It gets reviewed on its own merits, and a previous rejection doesn't rule you out. > [!WARNING] > > This means a different business, not the same one resubmitted. A rejected product under a new store reaches the same decision. ## Before you build Planning a new product and want to know whether we can support it? Check the acceptable, restricted and prohibited product lists in [Account Reviews](/merchant-of-record/account-reviews/account-reviews) before you integrate. Much cheaper to find out then than after. # Payments Source: https://docs.creem.io/merchant-of-record/finance/payment-methods What happens when a payment is processed through Creem ## Benefits Creem democratizes SaaS financial operations by serving as your merchant of record, enabling immediate payment acceptance, handling all the headaches with tax compliance, VAT requirements, and fraud prevention, while supporting global transactions with competitive, transparent pricing. ## Merchant of Record As your merchant of record, Creem eliminates the complexities of managing international sales and compliance. We handle all the intricate details of tax collection, VAT requirements, and regulatory compliance, allowing you to focus on growing your business while we manage the financial backend. Our commitment to transparency means no hidden fees or surprise charges - just clear, competitive rates that help you scale confidently. > [card] [Merchant of Record](/merchant-of-record/what-is) > > Learn what is a Merchant of Record, and how that can help your business In essence, you can focus entirely on growing your business while we meticulously handle every aspect of your financial operations, ensuring seamless transactions across borders. Your business will appreciate our highly competitive rates and straightforward fee structure, making international expansion more accessible than ever. ## Payment Methods CREEM supports the following payment methods to help you reach customers globally. ### Currently Supported Payment Methods | Payment method | Availability | | - | - | | Cards | Global | | Apple Pay | Global | | Google Pay | Global | | Alipay | Global (one-time payments only) | | iDEAL | Netherlands (one-time payments only) | | Alipay HK | Hong Kong | > [!TIP] > > The payment methods displayed on a checkout page vary based on several factors: > > * The type of product (One-Time Payment vs Subscription) > * Your customer's location > * Your customer's billing address > * The price of your product > * The device your customer is using to access the checkout page We automatically optimize the checkout experience to show the most relevant payment methods for each customer, increasing conversion rates and providing a seamless payment experience. > [card] Global Reach > > Accept payments from customers worldwide with localized payment methods. > [card] Optimized Conversion > > We show the right payment methods to the right customers at the right time. ## Learn more about Creem Finance operations Create customers and subscriptions, manage your products, and much more. Check out our guides to get the most out of Creem. > [card] [Payouts](/merchant-of-record/finance/payouts) > > Receive payments without any code or integration. > [card] [Standard Integration](/getting-started/quickstart) > > Create checkout sessions dynamically in your app # Payout Accounts Source: https://docs.creem.io/merchant-of-record/finance/payout-accounts How to set up, change, and manage your payout accounts on Creem. ## Setting Up a Payout Account Before you can receive payouts, you need to add a payout account: 1. Go to **Balance** → **Payout Account** in your dashboard 2. Complete your **KYC/KYB verification** (identity and/or business verification) 3. Add your bank account or crypto wallet details 4. Wait for Creem team approval ![Creem Balance page showing balance summary and payout options](https://mintcdn.com/creem/fm2TYBwopS74uc7h/images/balance-overview.png?fit=max\&auto=format\&n=fm2TYBwopS74uc7h\&q=85\&s=7ceee799ff961c5b2dad4e66861a745e) The Balance page shows your balance summary, recent activity, and quick links to payout management. > [!TIP] > > The full onboarding flow is: **Business Details** → **KYC/KYB Verification** → **Payout Account Setup** → **Account Review by Creem Team** → **Live Payments Enabled**. ## Available Payout Methods | Method | Details | | - | - | | **Bank Transfer** | \$7 or 1% of payout (whichever is higher) | | **Stablecoin (USDC via Polygon)** | 2% of payout volume | | **Alipay** | Available for China-based merchants (up to 50,000 CNY per payout) | For full fee details, see [Payouts](/merchant-of-record/finance/payouts). ## Changing Your Payout Account To change your bank account or payout method: 1. Go to **Balance** → **Payout Account** in your dashboard 2. Add your new bank account or wallet details 3. Set the new account as your **default payout method** ## Setting a Default Payout Account If you have multiple payout accounts connected, make sure to set the correct one as your **default**: 1. Go to **Balance** → **Payout Account** 2. Click on the payout method you want to use 3. Set it as the default Payouts will always be sent to the default account. ## Multiple Stores If you have multiple Creem stores, each store has its own payout account settings. You can use the same bank account across stores, but you'll need to configure it in each store separately. ## Common Issues > [accordion] My payout account is stuck on 'Review by Creem Team' > > After submitting your payout account, our compliance team reviews it within **1-2 working days**. If it's been longer, contact support with your Store ID. > [accordion] I want to switch from bank transfer to crypto (or vice versa) > > Add the new payout method in your dashboard and set it as default. Your next payout will use the new method. > [accordion] Can I receive payouts in a different currency? > > Payouts are processed in the currency of your registered bank account. If it differs from the currency you charge in, a conversion fee from our banking partners will apply automatically. # Payouts Source: https://docs.creem.io/merchant-of-record/finance/payouts How payouts from Creem work. ## Fees and Payout Schedule Get familiar with the fees and payout schedule associated with using Creem. ## Platform Fee When you make a sale using Creem, we take a small fee, known as the "platform fee", to cover the costs of credit card transaction fees, currency conversion fees, taxes (yes, we cover taxes) etc. The net sales will be paid out to your bank account. [Learn more about our pricing](https://www.creem.io/pricing). The platform fee is calculated on the total order value and collected when the order is placed. Here's an example breakdown where someone in France (20% VAT) buys a digital product with a card. | Description | Amount | | - | - | | Product price | \$20.00 | | Tax (20% VAT) | \$4.00 | | Total | \$24.00 | | Platform fee (3.9% + 0.40c) | \$1.33 | | Net profit (total - tax - platform fee) | \$18.67 | ## Additional Product Fees Certain products and features incur additional fees beyond the standard platform fee. These fees are applied before any commission calculations and affect your final payout amount. ### Splits Payment Functionality When using Creem's splits payment feature, an additional **2% fee** is applied to the transaction amount before any commission is distributed to the participating parties. **Example:** * Transaction amount: \$100.00 * Splits fee (2%): \$2.00 * Amount available for splits: \$98.00 * Commission distribution is then calculated on the \$98.00 ### Affiliate Marketing Platform When a transaction is processed through Creem's Affiliate Marketing platform, an additional **2% fee** is applied to the transaction amount. This fee covers the infrastructure and tracking capabilities that power the affiliate system. **Example:** * Transaction amount: \$100.00 * Affiliate platform fee (2%): \$2.00 * Amount after affiliate fee: \$98.00 * Affiliate commission is then calculated on the \$98.00 ### Abandoned Cart Recovery For transactions recovered through abandoned cart functionality, an additional **5% fee** is applied to the recovered transaction amount. **Example:** * Recovered transaction: \$50.00 * Recovery fee (5%): \$2.50 * Net amount after recovery fee: \$47.50 * Platform fee is then calculated on the \$47.50 These additional fees help cover the specialized infrastructure and processing costs associated with these advanced features. ## Payout Fees Creem charges 7 USD/EUR or 1% of the payout amount, whichever is higher, to cover bank transfer costs. Conversion rates are automatically applied by our banking partners if your registered bank account uses a different currency than the one you charge customers in. In that case, a small conversion fee from our Partners will be applied, which is outside of our control. ### Stablecoin Payouts (USDC via Polygon) Creem also supports payouts in USDC using the Polygon Network. This allows you to receive your funds quickly and securely in stablecoins, directly to your compatible wallet address. * Supported stablecoin: **USDC** * Network: **Polygon** * Fee: **2% of the payout volume** To use this option, ensure your wallet supports USDC on Polygon. When registering a payout account, select the stablecoin payout method and provide your wallet address. The payout will be processed in the next available payout window, subject to the 2% fee. ## Payout Schedule Payouts are always executed twice per month: * On the 1st day of the month * On the 15th day of the month To be eligible for a payout, you need to achieve a minimum balance of 50 USD or 50 EUR. Once you reach this threshold, the "withdraw" button will be enabled for you on your balance page. When you click on the withdraw button, your store will be automatically added to our payout schedule queue, and your payout will be executed on the next available window (1st or 15th of the month). After the payout is processed, you will see a new payout item on the payout activity tab of your balance page, with a reverse invoice available for download for tax purposes. If the payout day falls on a weekend or a public holiday, delays might occur due to our banking partners, and the payout will be executed on the next business day. ### Cancelling a payout request Selected the wrong payout account, or prefer to leave your funds in your balance for now? You can cancel a scheduled payout request from the **Balances** page before its scheduled payout day, as long as processing has not started. 1. Open **Balances** in your dashboard. 2. Click **Cancel payout** in the banner showing your scheduled payout date and selected account. 3. Review the confirmation and click **Cancel payout** to cancel the request. ![Balances page showing a scheduled payout request and the Cancel payout button](https://mintcdn.com/creem/zu0M9WLqZauy73mY/images/cancel-payout-request.png?fit=max\&auto=format\&n=zu0M9WLqZauy73mY\&q=85\&s=79b7a26754905b235ddedb737fddb0d3) > [!WARNING] > > Cancelling stops the payout request and, for security reasons, skips the current payout cycle. You > cannot undo the cancellation or submit another request for the same cycle, even if you select a > different payout account. You can request a payout again for the next cycle. Your Balances page > will show the next eligible payout date. ## Transfer Limits Creem is actively working to increase the number of banking partners it operates with. At the moment, some countries have transfer limits or bank transfer partner restrictions. For the current country-by-country list, see [Supported Countries](/merchant-of-record/supported-countries). ### China * Individual recipient: Alipay * Business recipient: Local Bank Account Receiving via Alipay: You can receive up to 50,000 CNY per payout and between 300,000—600,000 CNY per year Receiving via Local Bank account: Unlimited ## Important Note on Payout Availability Please note that if you have applied for a payout, we will only be able to execute your available balance on that date. Payments may be held for 7-12 days for risk assessment before they become available for payout. For example, if you are getting your payout executed on the 15th, only funds that were processed via payments before the 8th day of the calendar month will be available for withdrawal on that specific payout. ## What to do if your payout fails If a payout fails and is returned to your balance, the issue is usually one of these: ### Bank account issue We tried to send the payout to your selected payout instrument, but the bank could not process it. Please make sure: * your bank account details are correct * the bank account can receive international payments * your default payout account is the one you want us to use for the next payout If setting up a bank account is difficult in your region, we also support **USDC payouts**. ### Identity mismatch There is a mismatch between your selected payout instrument and the identity you onboarded with, so we cannot release the payout. For your next withdrawal: * if you onboarded as a **business**, the payout account must be a business account and the beneficiary name must match the onboarded business entity * if you onboarded as an **individual**, the payout account must be an individual account and the beneficiary name must match your KYC identity ## Managing Your Payout Account For information on setting up, changing, or managing your payout accounts, see [Payout Accounts](/merchant-of-record/finance/payout-accounts). # Refunds and Chargebacks Source: https://docs.creem.io/merchant-of-record/finance/refunds-and-chargebacks How Creem handles refunds and chargebacks. Creem empowers sellers with the flexibility to establish their own refund policies while maintaining the right to process refunds within 60 days to prevent chargebacks. ## Refunds At Creem, we believe in giving sellers the autonomy to determine refund policies that align with their business objectives and requirements. If you opt to offer refunds, they can be processed at any time through the Creem dashboard. The refunded amount will be deducted from your upcoming payout. **Refund Fees:** Creem does not charge any fees for processing refunds. However, the original transaction processing fees remain charged against your merchant balance in case of a refund, as these are transaction processing costs that Creem itself pays to our providers and partners. However, to protect against chargebacks, Creem reserves the right to issue refunds within 60 days of purchase at our discretion. Even if you maintain a "no refunds" policy, please note that customers retain the ability to initiate chargebacks against their purchases at any time. ## Chargebacks A chargeback (also known as a charge reversal or dispute) occurs when a customer requests their credit card provider to reverse a charge on their statement. These disputes can arise for various reasons, with fraud being a common trigger. As part of our commitment to transparent financial operations, Creem takes responsibility for managing chargebacks against your sales. When a chargeback occurs, we typically process a full refund on your behalf, deducting the refunded amount. **Chargeback Fees:** A fee of 25 USD/EUR is charged for each chargeback. It is important to note that this fee is due to the providers and partners that Creem uses, and that Creem does not profit from such fees. We always do our best to avoid such occurrences. Common reasons for chargebacks include: * **Fraudulent transactions using stolen credit card information, leading to charge cancellation by the credit card provider** * **Customers failing to recognize the charge on their statement and requesting a reversal** * **Customers disputing product delivery and bypassing the refund process by directly contacting their credit card provider** In the event of a chargeback, Creem will provide comprehensive information to the payment provider to advocate on your behalf. However, our involvement is limited by legal constraints, and the final decision rests with the payment provider. To maintain the integrity of our platform and protect all users, Creem may take action, including account suspension, if a store experiences an excessive number of chargebacks. # Supported Countries Source: https://docs.creem.io/merchant-of-record/supported-countries Creem supports merchants and affiliates in almost hundred countries. Find out if your country is supported for payouts and purchases. Creem supports purchases from all countries except those in the [unsupported list](#unsupported-countries-for-purchases) below. We support merchants in **87 countries**. > [!NOTE] > > If you don't see your country listed below, sorry, you won't be able to use Creem at this time. We > are always expanding our region support, and would love to hear from you. ### Payout Methods > [card] Local Bank Transfer > > Available in **all 87 supported countries**. Payout fee: 7 EUR/USD or 1% of the payout amount, > whichever is higher. Some countries have Wise transfer restrictions, listed below. ### Supported Countries (86) | Country | Local Bank | | :- | :-: | | Albania | | | Andorra | | | Argentina | | | Australia | | | Austria | | | Azerbaijan | | | [Bangladesh\*\*](#bank-transfer-partner-restrictions) | | | Belgium | | | Bosnia and Herzegovina | | | Brazil | | | Bulgaria | | | Canada | | | Cayman Islands | | | Chile | | | [China\*](/merchant-of-record/finance/payouts#transfer-limits) | | | [Colombia\*\*](#bank-transfer-partner-restrictions) | | | Costa Rica | | | Croatia | | | Cyprus | | | Czech Republic | | | Denmark | | | Dominican Republic | | | Egypt | | | Estonia | | | Finland | | | France | | | Georgia | | | Germany | | | Gibraltar | | | Greece | | | Guatemala | | | Honduras | | | Hong Kong | | | Hungary | | | Iceland | | | India | | | Indonesia | | | Ireland | | | Israel | | | Italy | | | Japan | | | Kenya | | | Latvia | | | Liechtenstein | | | Lithuania | | | Luxembourg | | | Malaysia | | | Malta | | | Mexico | | | Moldova | | | Monaco | | | Montenegro | | | Morocco | | | [Nepal\*\*](#bank-transfer-partner-restrictions) | | | Netherlands | | | New Zealand | | | Nigeria | | | North Macedonia | | | Norway | | | [Pakistan\*\*](#bank-transfer-partner-restrictions) | | | Peru | | | Philippines | | | Poland | | | Portugal | | | Romania | | | San Marino | | | Serbia | | | Singapore | | | Slovakia | | | Slovenia | | | South Africa | | | South Korea | | | Spain | | | Sri Lanka | | | Sweden | | | Switzerland | | | Taiwan | | | [Tanzania\*\*](#bank-transfer-partner-restrictions) | | | Thailand | | | Turkey | | | [Ukraine\*\*](#bank-transfer-partner-restrictions) | | | United Arab Emirates | | | United Kingdom | | | United States of America | | | Uruguay | | | Vietnam | | | Zambia | | ### Bank Transfer Partner Restrictions Some local bank payouts are subject to additional restrictions from our bank transfer partner. Countries marked with a double asterisk (\*\*) in the table above may have restrictions that affect payouts - for example, only individual (personal) bank accounts being supported, or business transfers not being available. > [!NOTE] > > These restrictions come from our bank transfer partner and may change over time. For the most > up-to-date, country-specific details, please check the partner's [live availability > page](https://wise.com/help/articles/2571942/what-countriesregions-can-i-send-to). ### Unsupported Countries for Purchases > [accordion] Unsupported countries (32 countries) > > We cannot accept payments from customers or Merchants from the following countries: > >
    >
  • Afghanistan
  • >
  • Antarctica
  • >
  • Belarus
  • >
  • Burma (Myanmar)
  • >
  • Burundi
  • >
  • Central African Republic
  • >
  • Chad
  • >
  • Cuba
  • >
  • Crimea (Region of Ukraine)
  • >
  • Democratic Republic of Congo
  • >
  • Republic of Congo
  • >
  • Donetsk (Region of Ukraine)
  • >
  • Eritrea
  • >
  • Haiti
  • >
  • Iran
  • >
  • Iraq
  • >
  • Kherson (Region of Ukraine)
  • >
  • Libya
  • >
  • Luhansk (Region of Ukraine)
  • >
  • Mali
  • >
  • Netherlands Antilles
  • >
  • Nicaragua
  • >
  • North Korea
  • >
  • Russia
  • >
  • Somalia
  • >
  • South Sudan
  • >
  • Sudan
  • >
  • Syria
  • >
  • Venezuela
  • >
  • Yemen
  • >
  • Zaporizhzhia (Region of Ukraine)
  • >
  • Zimbabwe
  • >
# What is a Merchant of Record Source: https://docs.creem.io/merchant-of-record/what-is What is a Merchant of Record (MoR)? Learn how Creem handles global tax compliance, payment processing, and SaaS billing as your MoR partner. A merchant of record (sometimes shortened to “MoR”) is a legal entity that takes on the responsibility of selling goods and services to end customers, handling everything from payments to compliance. ## What is a Merchant of Record? A Merchant of Record (MoR) is the legal entity responsible for selling goods or services to end customers. When customers make a purchase through Creem, they are technically buying from us as the Merchant of Record. This means we handle all aspects of the transaction, including payment processing, sales tax collection, refund management, chargeback handling, etc. ## Is Creem a Merchant of Record? Yes! Creem acts as your Merchant of Record, taking on all the complex financial and legal responsibilities so you can focus on what matters most - building and growing your SaaS business. We handle: * **Payment processing and tax compliance across different markets** * **Management of refunds and chargebacks** * **Sales tax collection and remittance** ## Frequently Asked Questions > [accordion] What is a Merchant of Record? > > A Merchant of Record (MoR) is the legal entity responsible for selling goods or services to end customers. The MoR appears on customer bank statements and invoices, and is responsible for all tax collection, remittance, and regulatory compliance. When you use Creem as your MoR, we handle all of this complexity so you can focus on building your product. > [accordion] How is a MoR different from a payment processor? > > A payment processor (like Stripe) only handles the technical side of moving money. You remain the seller of record and are responsible for tax compliance, refunds, and regulatory issues. A Merchant of Record like Creem takes on the legal responsibility of being the seller, handling VAT/GST collection, tax remittance, compliance, and customer disputes on your behalf. > [accordion] Why do I need a Merchant of Record? > > If you sell to customers globally, you face complex tax requirements in 190+ countries. Each jurisdiction has different VAT/GST rates, registration thresholds, and compliance rules. A MoR handles all of this automatically, letting you sell globally without setting up legal entities or tax registrations in every country. > [accordion] Does Creem handle tax compliance? > > Yes! Creem automatically calculates and collects the correct VAT, GST, or sales tax based on your customer's location. We handle tax remittance to authorities in 190+ countries, provide compliant invoices to your customers, and manage all tax reporting requirements. ## Further reading Want to learn more about how the Merchant of Record model works? [Learn more about MoR](https://www.creem.io/blog/what-is-a-merchant-of-record). Read our detailed guide on Understanding the Merchant of Record Business Model, where we break down the key benefits and explain why it's crucial for modern and lean SaaS businesses.