# Build with AI Coding Agents Source: https://docs.dodopayments.com/developer-resources/build-with-ai-coding-agents Install the Dodo Agent Plugin to give your coding agent one MCP server and one skill for building Dodo Payments integrations. Install the Dodo Agent Plugin to give your coding agent one MCP server and one skill for building Dodo Payments integrations. After you install it, describe what you want to build, and your agent plans and writes the integration. The plugin works with Claude Code, Codex CLI, Cursor, VS Code / GitHub Copilot, Gemini CLI, Grok Build, Meta Muse Code, Google Antigravity, JetBrains Junie, Kiro, and OpenCode. ## Install the Plugin Choose your coding agent below. Every install adds the MCP server and the `dodo-payments` skill. OpenCode needs one extra setting to load the skills, described in its section. > [accordion] Claude Code > > Install from the marketplace: > > ```bash theme={null} > claude plugins marketplace add dodopayments/dodo-agent-plugin > claude plugins install dodopayments@dodopayments > ``` > > The MCP server needs no keys at install time. When you add it, your client opens your browser so you can sign in with your Dodo Payments account. > > > [card] [Dodo Agent Plugin on GitHub](https://github.com/dodopayments/dodo-agent-plugin) > > > > Source code, configuration options, and local development instructions > [accordion] Codex CLI > > Register the marketplace, then install from the Codex TUI. > > **1. Register the marketplace** > > ```bash theme={null} > codex plugin marketplace add dodopayments/dodo-agent-plugin > ``` > > **2. Install from the Codex TUI** > > Open Codex and run `/plugins`: > > ```bash theme={null} > codex > ``` > > Type `/plugins`, switch to the **Dodo Payments** marketplace, select the **dodopayments** plugin, and choose **Install plugin**. > > The MCP server and the skill register automatically. > > If the plugin doesn't appear under `/plugins`, refresh it: > > ```bash theme={null} > codex plugin marketplace upgrade dodopayments > ``` > > > [!NOTE] > > > > To install from your shell instead of the TUI, run `codex plugin add dodopayments@dodopayments` after you register the marketplace. Codex CLI has no `codex plugin install` subcommand. See the [official Codex plugins docs](https://developers.openai.com/codex/plugins). > [accordion] Cursor > > Clone the repo into Cursor's local plugins directory: > > ```bash theme={null} > git clone https://github.com/dodopayments/dodo-agent-plugin.git ~/.cursor/plugins/local/dodo-agent-plugin > ``` > > Restart Cursor. The plugin loads skills from `skills/` and MCP servers from `.mcp.json`. > > Recent Cursor builds recognize Agent Plugins 1.0.0 directly and accept `.claude-plugin/marketplace.json` as a marketplace source. The generated `.cursor-plugin/plugin.json` is kept for older builds. > > If you installed a version before 0.5.0, delete the directory and re-clone — skills now ship as real files, not symlinks. > [accordion] OpenCode > > Install the plugin package in your project, then add it and its skills path to your `opencode.json`: > > ```bash theme={null} > npm install --save-dev @dodopayments/opencode-plugin > ``` > > ```json theme={null} > { > "$schema": "https://opencode.ai/config.json", > "plugin": ["@dodopayments/opencode-plugin"], > "skills": { > "paths": ["node_modules/@dodopayments/opencode-plugin/skills"] > } > } > ``` > > Restart OpenCode. The MCP server registers automatically. Skills need the extra `skills.paths` entry because OpenCode doesn't scan installed packages for skills. > > Relative paths resolve against the project directory, so the package must exist in that project's `node_modules`. An absolute path works too and avoids the local-install requirement. > > Verify skills loaded: > > ```bash theme={null} > opencode run "List every skill available to you by name." > ``` > > You should see `dodo-payments`. A skills path that doesn't exist is ignored silently, so verify rather than assume. > [accordion] VS Code / GitHub Copilot > > Clone the repo and register it: > > ```bash theme={null} > git clone https://github.com/dodopayments/dodo-agent-plugin.git ~/dodo-agent-plugin > ``` > > Open the Chat view, go to **Plugins**, and add the cloned folder. Or register it in `settings.json`: > > ```json theme={null} > { > "chat.pluginLocations": { "~/dodo-agent-plugin": true } > } > ``` > > The key is a path, the value enables it. Absolute paths and `~/` both work; relative paths resolve against each workspace folder. The setting is read live, so a running window picks it up without a restart. > > `chat.pluginLocations` is marked experimental and is a restricted setting, so the workspace must be trusted. Agent-plugin support is a preview feature governed by `chat.plugins.enabled`, which is on by default. > [accordion] Kiro > > Kiro reads the Agent Plugins manifest natively. > > **1. Clone the repository** > > ```bash theme={null} > git clone https://github.com/dodopayments/dodo-agent-plugin.git > ``` > > **2. Open the Powers panel** > > In Kiro, open the Powers panel (the Ghosty icon with the lightning bolt). > > **3. Import the folder** > > Choose **Add Custom Power → Import power from a folder**, select the cloned directory (the one containing `plugin.json`), and click **Install**. > > Skills load from `skills/`, MCP servers from `mcp.json`. Kiro manages MCP servers internally — they're not written to `~/.kiro/settings/mcp.json`. Kiro can also install a Power directly from a GitHub URL; see [Kiro's install docs](https://kiro.dev/docs/powers/installation/). > [accordion] Gemini CLI > > Install the plugin as a Gemini CLI extension: > > ```bash theme={null} > gemini extensions install https://github.com/dodopayments/dodo-agent-plugin > ``` > > `gemini-extension.json` at the repo root is the manifest, and Gemini CLI loads the skills from `skills/` next to it. Verify: > > ```bash theme={null} > gemini skills list > gemini mcp list > ``` > > To update, run `gemini extensions update dodopayments`. > [accordion] GitHub Copilot CLI > > Register the marketplace, then install the plugin: > > ```bash theme={null} > copilot plugin marketplace add dodopayments/dodo-agent-plugin > copilot plugin install dodopayments@dodopayments > ``` > > Verify with `copilot plugin list` and `copilot mcp list`. Use the marketplace install: Copilot CLI marks direct repository installs as deprecated. > [accordion] Grok Build > > Grok Build reads the repository as-is, including `.claude-plugin/marketplace.json`: > > ```bash theme={null} > grok plugin marketplace add dodopayments/dodo-agent-plugin > grok plugin install dodopayments --trust > ``` > > Plugins stay disabled until you trust them, either with `--trust` or from `/plugins`. The MCP server signs in through your browser when it connects. > > See the [Grok guide](https://github.com/dodopayments/dodo-agent-plugin/blob/main/docs/clients/grok.md) for MCP-only setup on grok.com and the xAI API. > [accordion] Meta Muse Code > > Muse Code plugins are experimental, so turn them on first: > > ```bash theme={null} > export MUSE_EXPERIMENTAL_PLUGINS=1 > muse plugins marketplace add dodopayments https://github.com/dodopayments/dodo-agent-plugin.git > muse plugins install dodopayments@dodopayments > muse plugins approve dodopayments > ``` > > A plugin's MCP servers stay inactive until you approve it. Sign in to the server with `muse mcp login dodopayments`. > [accordion] Google Antigravity > > Antigravity uses its own manifest format, so install the generated bundle in `providers/antigravity/`: > > ```bash theme={null} > git clone https://github.com/dodopayments/dodo-agent-plugin.git > agy plugin install ./dodo-agent-plugin/providers/antigravity > ``` > > To update, run `git pull` and then the install command again. > [accordion] JetBrains Junie > > In Junie, run `/extensions`, choose **Add marketplace**, enter `https://github.com/dodopayments/dodo-agent-plugin`, and install **dodopayments**. > > See the [Junie guide](https://github.com/dodopayments/dodo-agent-plugin/blob/main/docs/clients/antigravity-and-junie.md#junie) for the standalone bundle in `providers/junie/`. Using a different agent? The [MCP Server](/developer-resources/mcp-server) and [Agent Skills](/developer-resources/agent-skills) guides cover Claude Desktop, Windsurf, Cline, Zed, and any MCP-compatible client. ## What You Get Once installed, your agent has access to one MCP server and the `dodo-payments` skill. ### MCP Servers | Server | Purpose | Auth | | - | - | - | | `dodopayments` | Docs search, page reading, SDK and API method search, and `execute` for running SDK code against your account | OAuth (browser), when the server is added | The server speaks Streamable HTTP over HTTPS, and every client connects to it directly, with no local bridge process or Node.js dependency. See the [MCP Server](/developer-resources/mcp-server) guide for the tools. To sign in after you install the plugin, use `/mcp` in Claude Code, `codex mcp login dodopayments` in Codex, or `opencode mcp auth dodopayments` in OpenCode. In Cursor and VS Code, connect `dodopayments` from the MCP UI. ### Agent Skills | Skill | Description | | - | - | | `dodo-payments` | One skill with an index and reference topics for checkout, subscriptions, webhooks, billing models, catalog, customers, refunds, framework adapters, testing and go-live, and MCP use | Skills load automatically — your agent picks the right one when it detects a relevant task. See [Agent Skills](/developer-resources/agent-skills) for the full list and individual installation. ### Try This Prompt First Once the plugin is active, try: ``` Set up Dodo Payments webhook handlers in my Next.js app for payment.succeeded and subscription.active events. ``` Your agent will load the `dodo-payments` skill and open its `webhooks` reference topic, use the `dodopayments` MCP server to pull the latest payload shapes, and write a handler with signature verification following the Standard Webhooks spec. ## Client Support The plugin follows the [Agent Plugins 1.0.0](https://agent-plugins.org/specification) specification. Clients with native support load it directly; others use generated compatibility manifests. ### Agents with Plugin Install One install wires the MCP server and the skill. | Agent | Install | Skills | MCP Servers | | - | - | -: | -: | | **Claude Code** | marketplace command | 1 | 1 | | **Codex CLI** | marketplace command | 1 | 1 | | **Cursor** | git clone | 1 | 1 | | **VS Code / GitHub Copilot** | git clone | 1 | 1 | | **GitHub Copilot CLI** | marketplace command | 1 | 1 | | **Gemini CLI** | extension install | 1 | 1 | | **Grok Build** | marketplace command | 1 | 1 | | **Meta Muse Code** | marketplace command | 1 | 1 | | **Google Antigravity** | git clone | 1 | 1 | | **JetBrains Junie** | marketplace | 1 | 1 | | **Kiro** | git clone | 1 | 1 | | **OpenCode** | npm | 1 | 1 | OpenCode needs one extra `skills.paths` entry before its skill loads. ### Other MCP-Compatible Clients These have no Agent Plugin install. Configure the MCP server by hand, and add skills through the Skills CLI where supported. | Agent | MCP Servers | Skills | | - | - | - | | Claude Desktop | [MCP Server guide](/developer-resources/mcp-server) | not supported | | Windsurf | [MCP Server guide](/developer-resources/mcp-server) | [Skills CLI](/developer-resources/agent-skills) | | Cline / Zed / others | [MCP Server guide](/developer-resources/mcp-server) | [Skills CLI](/developer-resources/agent-skills) | ## Docs Built for Agents Every Dodo Payments documentation page is available in a format optimized for AI consumption: * **Full docs index**: [`docs.dodopayments.com/llms.txt`](https://docs.dodopayments.com/llms.txt) — complete documentation index for context ingestion * **Plain markdown**: Append `.md` to any documentation URL to get the raw markdown version (e.g., `/api-reference/introduction.md`) * **Source repository**: [`github.com/dodopayments/dodo-docs`](https://github.com/dodopayments/dodo-docs) — clone for offline indexing ## What Your Agent Can Do With the plugin installed, your coding agent can: * **Create checkout sessions and payment links** — [One-time payments](/features/one-time-payment-products) and [subscriptions](/features/subscription) * **Stand up subscription and usage-based billing end-to-end** — [Subscriptions](/features/subscription), [Usage-based billing](/features/usage-based-billing/introduction), [Credit-based billing](/features/credit-based-billing) * **Generate Standard Webhooks-compliant handlers** with signature verification — [Webhooks](/developer-resources/webhooks) * **Mount route handlers in your framework** using the official adapters — [Framework adaptors](/developer-resources/framework-adaptors) * **Wire BillingSDK React components** for pricing tables and subscription management — [BillingSDK](/developer-resources/billingsdk) * **Author license-key flows** for digital products — [License keys](/features/license-keys) * **Implement credit-based billing** with entitlements, balances, rollover, and overage — [Credits](/features/credit-based-billing) * **Build and manage your product catalog** with add-ons and collections — [Products](/features/products), [Add-ons](/features/addons), [Product collections](/features/product-collections) * **Add discounts and localized pricing** — [Discount codes](/features/discount-codes), [Localized pricing](/features/localized-pricing), [Adaptive currency](/features/adaptive-currency) * **Ship mobile in-app checkout** for React Native, Flutter, iOS, and Android — [Mobile integration](/developer-resources/mobile-integration) * **Handle refunds, disputes, and customer self-service** — [Refunds](/features/transactions/refunds), [Disputes](/features/transactions/disputes), [Customer portal](/features/customer-portal) * **Test the integration and go live safely** — [Test mode vs live mode](/miscellaneous/test-mode-vs-live-mode) ## Security and Best Practices > [!WARNING] > > Never commit live API keys. Use [test mode](/miscellaneous/test-mode-vs-live-mode) during development. * **Use test mode first.** Build and test your integration with a test mode API key before you go live. See [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). * **OAuth is the default.** The Agent Plugin authenticates via browser OAuth (no local secrets). Only use API-key mode if you need it. * **Review agent-generated code.** Always verify webhook handlers include signature verification following the [Standard Webhooks spec](https://standardwebhooks.com/). ## Common Configuration Gotchas ### Subscription Period Is Not the Billing Cycle > [!WARNING] > > The subscription period (`subscription_period_count` and `subscription_period_interval`) defines when the subscription expires, not how often it charges. The payment frequency (`payment_frequency_count` and `payment_frequency_interval`) sets how often it charges. Setting both the subscription period and the payment frequency to 1 month creates a subscription that charges once and then expires — not a monthly recurring subscription. For ongoing subscriptions, set the subscription period to 20 years (the recommended value and the maximum) with your desired payment frequency (for example, 1 month). See the [Subscription Integration Guide](/developer-resources/subscription-integration-guide) for full details. ### Use Checkout Sessions, Not Direct Payment Endpoints > [!TIP] > > `POST /payments` and `POST /subscriptions` are deprecated. For all new integrations, create payments and subscriptions through [Checkout Sessions](/developer-resources/checkout-session) (`POST /checkouts`). Checkout Sessions support both one-time payments and subscriptions, and provide a more complete API surface. ### Always Verify Webhook Signatures > [!TIP] > > Never process webhook events without verifying the signature. Use the Standard Webhooks specification to validate every incoming event with your webhook signing secret. See [Webhook Integration](/developer-resources/webhooks) for implementation details. ## Configure with an API Key By default, the Agent Plugin uses the remote MCP server with browser OAuth. To use a local API key instead, for example in CI or on a headless server, switch to stdio mode. > [accordion] Local API key mode — Claude Code > > Add the local stdio server with your key in the environment, so the key never goes into a file in your repository: > > ```bash theme={null} > claude mcp add dodopayments --scope user \ > --env DODO_PAYMENTS_API_KEY="$DODO_PAYMENTS_API_KEY" \ > --env DODO_PAYMENTS_ENVIRONMENT=test_mode \ > -- npx -y dodopayments-mcp@latest > ``` > > Use a test mode key while you build. See [MCP Server](/developer-resources/mcp-server#advanced-local-server-with-an-api-key) for the local server's requirements. > [accordion] Local API key mode — OpenCode > > Declare `dodopayments` yourself in `opencode.json` — your entry wins over the plugin's default remote server: > > ```json theme={null} > { > "$schema": "https://opencode.ai/config.json", > "plugin": ["@dodopayments/opencode-plugin"], > "mcp": { > "dodopayments": { > "type": "local", > "command": ["npx", "-y", "dodopayments-mcp@latest"], > "environment": { > "DODO_PAYMENTS_API_KEY": "dodo_test_...", > "DODO_PAYMENTS_WEBHOOK_KEY": "whsec_...", > "DODO_PAYMENTS_ENVIRONMENT": "test_mode" > }, > "enabled": true > } > } > } > ``` > > Restart OpenCode to apply. ## Next Steps > [card] [MCP Server](/developer-resources/mcp-server) > > Full reference for the MCP server — all supported clients, configuration, and available tools > [card] [Agent Skills](/developer-resources/agent-skills) > > Individual skill installation, skill reference, and per-agent setup instructions > [card] [API Reference](/api-reference/introduction) > > Complete OpenAPI reference for all Dodo Payments endpoints # Official SDKs Source: https://docs.dodopayments.com/developer-resources/dodo-payments-sdks Official Dodo Payments SDKs for TypeScript, Python, Go, PHP, Java, Kotlin, C#, Ruby, and Rust, plus checkout SDKs for mobile apps. Official Dodo Payments server SDKs are available in nine languages. Separate checkout SDKs open hosted checkout from Android, iOS, React Native, and Flutter apps. > [card] [TypeScript](/developer-resources/sdks/typescript) > > Type-safe SDK for Node.js with promise-based API and auto-pagination. > [card] [Python](/developer-resources/sdks/python) > > Pythonic interface with async/await support for Python 3.9+. > [card] [Go](/developer-resources/sdks/go) > > Idiomatic Go interface with context support and strong typing. > [card] [PHP](/developer-resources/sdks/php) > > PSR-4 compliant SDK for PHP 8.1+. > [card] [Java](/developer-resources/sdks/java) > > Thread-safe SDK for Java 8+ with Maven and Gradle support. > [card] [Kotlin](/developer-resources/sdks/kotlin) > > Kotlin SDK with coroutines and null safety. > [card] [C#](/developer-resources/sdks/csharp) > > Type-safe SDK for .NET Standard 2.0+ with async Task-based API. > [card] [Ruby](/developer-resources/sdks/ruby) > > Ruby SDK that follows Ruby conventions. > [card] [Rust](/developer-resources/sdks/rust) > > Async-first SDK built on Tokio and reqwest for Rust 1.75+. ## Quick Start **1. Install the SDK** Install the SDK for your language with its package manager. > [tab] TypeScript > > ```bash theme={null} > npm install dodopayments > ``` > [tab] Python > > ```bash theme={null} > pip install dodopayments > ``` > [tab] Go > > ```bash theme={null} > go get github.com/dodopayments/dodopayments-go > ``` > [tab] PHP > > ```bash theme={null} > composer require dodopayments/client > ``` > [tab] Java > > ```kotlin theme={null} > // build.gradle.kts > implementation("com.dodopayments.api:dodo-payments-java:1.120.0") > ``` > [tab] Kotlin > > ```kotlin theme={null} > // build.gradle.kts > implementation("com.dodopayments.api:dodo-payments-kotlin:1.120.0") > ``` > [tab] C# > > ```bash theme={null} > dotnet add package DodoPayments.Client > ``` > [tab] Ruby > > ```bash theme={null} > bundle add dodopayments > ``` > [tab] Rust > > ```bash theme={null} > cargo add dodopayments > ``` For Maven coordinates and version-specific options, see each SDK's page. **2. Initialize the Client** Read your API key from the `DODO_PAYMENTS_API_KEY` environment variable. The examples connect to test mode; see [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). > [tab] TypeScript > > ```typescript theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', > }); > ``` > [tab] Python > > ```python theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ["DODO_PAYMENTS_API_KEY"], > environment="test_mode", > ) > ``` > [tab] Go > > ```go theme={null} > import ( > "os" > > "github.com/dodopayments/dodopayments-go" > "github.com/dodopayments/dodopayments-go/option" > ) > > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > option.WithEnvironmentTestMode(), > ) > ``` > [tab] PHP > > ```php theme={null} > use Dodopayments\Client; > > $client = new Client( > bearerToken: getenv('DODO_PAYMENTS_API_KEY'), > baseUrl: 'https://test.dodopayments.com', > ); > ``` > [tab] Rust > > ```rust theme={null} > use dodopayments::{Client, ClientConfig, Environment}; > > let config = ClientConfig::from_env() > .expect("DODO_PAYMENTS_API_KEY must be set") > .with_environment(Environment::TestMode); > let client = Client::new(config).expect("failed to create client"); > ``` For Java, Kotlin, C#, and Ruby, see the client setup on each SDK's page. > [!WARNING] > > Keep API keys in environment variables or a secrets manager. Never commit them to version control. **3. Create a Checkout Session** Create a checkout session and redirect the customer to the returned `checkout_url`. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'YOUR_PRODUCT_ID', quantity: 1 }], }); console.log(session.checkout_url); ``` For the same call in other languages, and for payment links and webhooks, see the [Integration Guide](/developer-resources/integration-guide). ## Key Features All backend SDKs include: * **Type Safety**: Strong typing for compile-time safety and better IDE support. * **Error Handling**: Typed errors that expose the HTTP status and the error body the API returned. * **Authentication**: API key authentication, read from an environment variable. * **Async Support**: Modern async/await patterns where applicable. * **Auto-Pagination**: Automatic pagination for list responses. * **Usage Events**: Methods to send usage events for usage-based billing. * **Test Mode**: A setting that points the client at test mode, so no real money moves. ## Mobile Checkout SDKs For native Android, iOS, React Native, and Flutter apps, use the mobile checkout SDKs. They open Dodo's hosted checkout page in the platform's real browser surface (not a WebView), so Apple Pay and Google Pay work the same way they do on the open web. All four mobile SDKs share the same contract: `start(...)` returns a typed `CheckoutResult`, none of them hold an API key, and they never call the API directly. > [card] [Android](/developer-resources/sdks/android) > > Kotlin SDK that opens a Chrome Custom Tab. Requires `minSdk` 23. > [card] [iOS](/developer-resources/sdks/ios) > > Swift SDK that opens SFSafariViewController. Requires iOS 16+. > [card] [React Native](/developer-resources/sdks/react-native) > > Turbo Module over both native cores. Requires React Native 0.77+. > [card] [Flutter](/developer-resources/sdks/flutter) > > Pigeon channel over both native cores. Requires Flutter 3.44+. > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > End-to-end mobile payment flow, from backend checkout session to callback scheme setup. ## Command-Line Interface The Dodo CLI manages payments, customers, and webhooks from your terminal. It includes an interactive TUI, an AI assistant, and webhook testing tools. > [card] [CLI](/developer-resources/sdks/cli) > > Interactive terminal client with AI assistant and webhook testing. Install it on macOS or Linux with: ```bash theme={null} curl -fsSL https://dodopayments.com/install.sh | sh ``` ## Terraform Provider The Terraform provider manages your catalog as code: products, prices, meters, credits, discounts, entitlements, and webhook endpoints. Review each pricing change in a pull request and apply it from CI. > [card] [Terraform Provider](/developer-resources/terraform-provider) > > Pricing as code, with versioned changes and GitOps workflows. ## Framework Adaptors Adaptors add checkout, customer portal, and webhook handlers to your framework. ### Recommended Frameworks > [card] [Next.js](/developer-resources/nextjs-adaptor) > > Route handlers for checkout, customer portal, and webhooks in the App Router. > [card] [Better Auth](/developer-resources/better-auth-adaptor) > > Create a customer when a user signs up, and add checkout and the customer portal to your auth flow. > [card] [Supabase](/developer-resources/supabase-boilerplate) > > Next.js and Supabase starter with auth, database schema, webhooks, and a pricing page. > [card] [Convex](/developer-resources/convex-component) > > Checkout, customer portal, and webhook functions for your Convex backend. > [accordion] All Other Framework Adaptors > > > [card] [SvelteKit](/developer-resources/sveltekit-adaptor) > > > [card] [Nuxt](/developer-resources/nuxt-adaptor) > > > [card] [Remix](/developer-resources/remix-adaptor) > > > [card] [Express](/developer-resources/express-adaptor) > > > [card] [Fastify](/developer-resources/fastify-adaptor) > > > [card] [Hono](/developer-resources/hono-adaptor) > > > [card] [Astro](/developer-resources/astro-adaptor) > > > [card] [TanStack](/developer-resources/tanstack-adaptor) > > > [card] [Bun](/developer-resources/bun-adaptor) ## Migration from Node.js SDK > [!NOTE] > > The TypeScript SDK replaces the legacy Node.js SDK. If you use the Node.js SDK, see the [migration guide](https://github.com/dodopayments/dodopayments-typescript/blob/main/MIGRATION.md) to update your integration. ## Get Help * **Discord**: Join our [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact us at [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the respective SDK repository. * **Documentation**: Visit the [API reference](/api-reference/introduction). ## Contributing Each SDK repository accepts contributions. Most have a `CONTRIBUTING.md` file with guidelines for reporting bugs, requesting features, submitting pull requests, running tests, and code style conventions. Visit the individual SDK pages to access their GitHub repositories and contribution guidelines. # API Gateway Blueprint Source: https://docs.dodopayments.com/developer-resources/ingestion-blueprints/api-gateway Send a usage event to Dodo Payments for each API call your service handles, then bill customers per call with a Count meter. The API Gateway Blueprint sends a usage event to Dodo Payments for each API call your service handles, and a **Count** meter turns those events into a per-call charge for each customer. Use it to track API endpoint usage, to inform rate limits, and to bill for API usage. It ships in the `@dodopayments/ingestion-blueprints` npm package as `trackAPICall()`, which sends one event per call, and `createBatch()`, which queues events for high request volumes. ## Use Cases The API Gateway Blueprint fits these scenarios: > [card] API-as-a-Service > > Track calls per customer on an API platform and charge by the number of calls. > [card] Rate Limiting > > Record each customer's call volume to inform usage-based rate limits. The blueprint records usage but doesn't enforce limits. > [card] Performance Monitoring > > Record response times and status codes with each event, so error rates sit next to billing data. > [card] Multi-Tenant SaaS > > Bill customers for their API consumption across different endpoints. > [!NOTE] > > Every event needs the Dodo Payments customer ID of the customer you bill, which starts with `cus_`. Store it with your user record when you create the customer, and pass it as `customerId`. ## Quick Start To track API calls, install the package, create a meter, and send an event for each call. **1. Install the SDK** Install the Dodo Payments Ingestion Blueprints package: ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` **2. Get Your API Keys** Create a Dodo Payments API key under **Developer → API Keys** in the [Dodo Payments dashboard](https://app.dodopayments.com/developer/api-keys), and store it in the `DODO_PAYMENTS_API_KEY` environment variable. Use a test mode key while you build. A test mode key works only with `test_mode`. **3. Create a Meter** In the [Dodo Payments dashboard](https://app.dodopayments.com/), go to **Products → Meters** and click **Create Meter**. Set these fields: * **Meter Name**: a descriptive name, such as `API Calls`. * **Event Name**: `api_call`, or a name you choose. It must match `eventName` in your code exactly (case-sensitive). * **Aggregation Type**: **Count**, to bill by the number of calls. * **Measurement Unit**: the unit shown on invoices, such as `calls`. To count only some calls, turn on **Enable Event Filtering** and add conditions on metadata keys such as `endpoint`, `method`, or `status_code`. **4. Track API Calls** Create one `Ingestion` instance with your API key and event name, then choose a pattern: one event per call, a batch for high volume, or Express.js middleware that tracks every request. In the middleware, `req.user` comes from your authentication middleware, and its `id` must be a Dodo Payments customer ID. Requests without a signed-in user are sent with the customer ID `anonymous`, which doesn't match any customer. ```javascript Single API Call theme={null} import { Ingestion, trackAPICall } from '@dodopayments/ingestion-blueprints'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'api_call' }); // Track a single API call await trackAPICall(ingestion, { customerId: 'cus_123', metadata: { endpoint: '/api/v1/users', method: 'GET', status_code: 200, response_time_ms: 45 } }); ``` ```javascript High-Volume with Batching theme={null} import { Ingestion, createBatch } from '@dodopayments/ingestion-blueprints'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'api_call' }); // Create batch for high-volume tracking const batch = createBatch(ingestion, { maxSize: 100, // Flush after 100 events flushInterval: 5000 // Or flush 5 seconds after the last add() }); // Add API calls to batch batch.add({ customerId: 'cus_123', metadata: { endpoint: '/api/v1/products', method: 'GET', status_code: 200 } }); // Clean up when done await batch.cleanup(); ``` ```javascript Express.js Middleware theme={null} import express from 'express'; import { Ingestion, createBatch } from '@dodopayments/ingestion-blueprints'; const app = express(); const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'api_call' }); const batch = createBatch(ingestion, { maxSize: 50, flushInterval: 10000 }); // Middleware to track all API calls app.use((req, res, next) => { const startTime = Date.now(); res.on('finish', () => { const responseTime = Date.now() - startTime; batch.add({ // req.user is set by your auth middleware customerId: req.user?.id || 'anonymous', metadata: { endpoint: req.path, method: req.method, status_code: res.statusCode, response_time_ms: responseTime } }); }); next(); }); // Cleanup on shutdown process.on('SIGTERM', async () => { await batch.cleanup(); process.exit(0); }); ``` ## Configuration ### Ingestion Configuration Pass these options to `new Ingestion()`: **apiKey** `string` *required* Your Dodo Payments API key from the dashboard. **environment** `string` Environment mode: `test_mode` or `live_mode`. Defaults to `test_mode`. The Dodo Payments SDKs default to `live_mode` instead, so set `live_mode` explicitly in production. **eventName** `string` *required* Event name that matches your meter's **Event Name** (case-sensitive). Every event this instance sends uses it. ### Track API Call Options Pass these options to `trackAPICall()` and `batch.add()`: **customerId** `string` *required* The Dodo Payments customer ID to bill for the call, for example `cus_123`. **metadata** `object` Optional metadata about the API call, such as endpoint, method, status code, and response time. Each value must be a string, number, or boolean. The API rejects nested objects, arrays, and `null` values. ### Batch Configuration `createBatch(ingestion, options)` queues events in memory and returns an object with three methods: `add()` queues an event, `flush()` sends the queued events, and `cleanup()` sends them and stops the timer. A flush sends one ingest request per event, in parallel. **maxSize** `number` Number of queued events that triggers an immediate flush. Default: `100`. **flushInterval** `number` Milliseconds to wait after the most recent `add()` before the batch flushes. Each `add()` restarts the timer. Default: `5000` (5 seconds). ## Best Practices > [!TIP] > > **Use Batching for High Volume**: For high-traffic applications, use `createBatch()`. `batch.add()` returns immediately, so tracking doesn't add latency to your request handler. A batch holds events in memory until it flushes, and it doesn't retry events that fail to send. An automatic flush logs the error with `console.error`. A call to `flush()` or `cleanup()` throws it. > [!WARNING] > > **Clean Up Batches on Shutdown**: Call `batch.cleanup()` when your application shuts down, so pending events are flushed instead of lost. # LLM Blueprint Source: https://docs.dodopayments.com/developer-resources/ingestion-blueprints/llm Track LLM token usage per customer and bill for it in Dodo Payments. Works with AI SDK, OpenAI, Anthropic, OpenRouter, Groq, and Google Gemini. The LLM Blueprint wraps your LLM client so that each completed call sends a usage event with its input, output, and total token counts to Dodo Payments. A meter sums those counts, so you can bill each customer for the tokens they use. The blueprint ships in the `@dodopayments/ingestion-blueprints` npm package as `createLLMTracker()`. > [card] [Quick Start](#quick-start) > > Install the SDK, create a meter, and wrap your LLM client. > [card] [API Reference - Events Ingestion](/api-reference/usage-events/ingest-events) > > The API endpoint that receives usage events. > [card] [API Reference - Meters](/api-reference/meters/create-meter) > > Create and configure meters for billing. > [card] [Usage-Based Billing Guide](/developer-resources/usage-based-billing-guide) > > Set up usage-based billing with meters from start to finish. > [!NOTE] > > Use it in SaaS apps, AI chatbots, content generation tools, and any other LLM-powered application that bills by usage. ## Quick Start To track token usage, install the package, create a meter, and wrap your LLM client. **1. Install the SDK** Install the Dodo Payments Ingestion Blueprints package: ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` Also install the SDK for your LLM provider, such as `openai`, `@anthropic-ai/sdk`, `groq-sdk`, `@google/genai`, or `ai` with `@ai-sdk/google`. **2. Get Your API Keys** You need two API keys: * **Dodo Payments API key**: Create one under **Developer → API Keys** in the [Dodo Payments dashboard](https://app.dodopayments.com/developer/api-keys), and store it in `DODO_PAYMENTS_API_KEY`. Use a test mode key while you build. A test mode key works only with `test_mode`. * **LLM provider API key**: The key for the provider you call, such as OpenAI, Anthropic, Groq, OpenRouter, or Google. The examples read it from variables such as `OPENAI_API_KEY`. > [!TIP] > > Store your API keys in environment variables. Don't commit them to version control. **3. Create a Meter in Dodo Payments** Create a meter before you track usage: 1. In the [Dodo Payments dashboard](https://app.dodopayments.com/), go to **Products → Meters**. 2. Click **Create Meter**. 3. Configure the meter: * **Meter Name**: A descriptive name, such as `LLM Token Usage`. * **Event Name**: A unique event identifier, such as `llm.chat_completion`. * **Aggregation Type**: **Sum**, to add up token counts. * **Over Property**: The token count to bill for: * `inputTokens`: input (prompt) tokens. * `outputTokens`: output (completion) tokens, including reasoning tokens when the model reports them. * `totalTokens`: input and output tokens combined. * **Measurement Unit**: The unit shown on invoices, such as `tokens`. 4. Click **Create Meter**. > [!NOTE] > > The **Event Name** you set here must match the `eventName` you pass to the SDK exactly (case-sensitive). For detailed instructions, see the [Usage-Based Billing Guide](/developer-resources/usage-based-billing-guide). **4. Track Token Usage** Create a tracker, wrap your LLM client, and call the client as usual: ```javascript AI SDK theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import { generateText } from 'ai'; import { google } from '@ai-sdk/google'; const llmTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'aisdk.usage', }); const client = llmTracker.wrap({ client: { generateText }, customerId: 'cus_123' }); const response = await client.generateText({ model: google('gemini-2.0-flash'), prompt: 'Hello!', maxOutputTokens: 500 }); console.log('Usage:', response.usage); ``` ```javascript OpenRouter theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import OpenAI from 'openai'; const openrouter = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', apiKey: process.env.OPENROUTER_API_KEY }); const llmTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'openrouter.usage' }); const client = llmTracker.wrap({ client: openrouter, customerId: 'cus_123' }); const response = await client.chat.completions.create({ model: 'qwen/qwen3-max', messages: [{ role: 'user', content: 'Hello!' }], max_tokens: 500 }); console.log('Response:', response.choices[0].message.content); console.log('Usage:', response.usage); ``` ```javascript OpenAI theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import OpenAI from 'openai'; // 1. Create your LLM client (normal way) const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); // 2. Create tracker ONCE at startup const tracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', // Use 'live_mode' for production eventName: 'llm.chat_completion' // Match your meter's event name }); // 3. Wrap & use - automatic tracking! const client = tracker.wrap({ client: openai, customerId: 'cus_123' }); // Every API call is now automatically tracked const response = await client.chat.completions.create({ model: 'gpt-4', messages: [{ role: 'user', content: 'Hello!' }] }); // ✨ Usage automatically sent to Dodo Payments! console.log('Tokens used:', response.usage); ``` ```javascript Anthropic theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import Anthropic from '@anthropic-ai/sdk'; const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); const tracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'anthropic.usage' }); const client = tracker.wrap({ client: anthropic, customerId: 'cus_123' }); const response = await client.messages.create({ model: 'claude-sonnet-4-0', max_tokens: 1024, messages: [{ role: 'user', content: 'Hello Claude!' }] }); console.log('Tokens used:', response.usage); ``` ```javascript Groq theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import Groq from 'groq-sdk'; const groq = new Groq({ apiKey: process.env.GROQ_API_KEY }); const tracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'groq.usage' }); const client = tracker.wrap({ client: groq, customerId: 'cus_123' }); const response = await client.chat.completions.create({ model: 'llama-3.1-8b-instant', messages: [{ role: 'user', content: 'Hello!' }] }); console.log('Tokens:', response.usage); ``` ```javascript Google Gemini theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import { GoogleGenAI } from '@google/genai'; const googleGenai = new GoogleGenAI({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY }); const llmTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'gemini.usage' }); const client = llmTracker.wrap({ client: googleGenai, customerId: 'cus_123' }); const response = await client.models.generateContent({ model: 'gemini-2.5-flash', contents: 'Why is the sky blue?' }); console.log('Response:', response.text); console.log('Usage:', response.usageMetadata); ``` > [!TIP] > > Each completed call through the wrapped client now sends a usage event with its token counts to Dodo Payments for billing. ## Configuration ### Tracker Configuration Create a tracker once at application startup and reuse it for every customer. `createLLMTracker()` takes these options, and it throws an error if `apiKey` or `eventName` is missing or empty: **apiKey** `string` *required* Your Dodo Payments API key. Get it from the [API Keys page](https://app.dodopayments.com/developer/api-keys). ```javascript theme={null} apiKey: process.env.DODO_PAYMENTS_API_KEY ``` **environment** `string` The environment mode for the tracker: * `test_mode`: for development and testing. This is the default. * `live_mode`: for production. The Dodo Payments SDKs default to `live_mode` instead, so set `live_mode` explicitly in production. ```javascript theme={null} environment: 'test_mode' // or 'live_mode' ``` > [!WARNING] > > Use `test_mode` during development, so test traffic doesn't create live usage events. **eventName** `string` *required* The event name that triggers your meter. It must match the **Event Name** of your Dodo Payments meter exactly (case-sensitive). ```javascript theme={null} eventName: 'llm.chat_completion' ``` > [!NOTE] > > This event name links your tracked usage to the correct meter for billing calculations. Besides `wrap()`, the tracker has `track(response, customerId, metadata)`, which records usage from a response you already have, and `healthCheck()`, which returns `true` when the Dodo Payments API is reachable. ### Wrapper Configuration Pass these parameters to `wrap()`: **client** `object` *required* Your LLM client instance, such as an OpenAI, Anthropic, Groq, or Google GenAI client, or an object that holds AI SDK functions, such as `{ generateText }`. ```javascript theme={null} client: openai ``` **customerId** `string` *required* The Dodo Payments customer ID of the customer to bill. It starts with `cus_`. ```javascript theme={null} customerId: 'cus_123' ``` > [!TIP] > > Store each user's Dodo Payments customer ID with your user record, and pass it here. Your application's own user ID doesn't match a Dodo Payments customer. **metadata** `object` Optional additional data to attach to each tracking event, for filtering and analysis. Each value must be a string, number, or boolean. A key named `inputTokens`, `outputTokens`, `totalTokens`, or `model` replaces the tracked value. ```javascript theme={null} metadata: { feature: 'chat', userTier: 'premium', sessionId: 'session_123', modelVersion: 'gpt-4' } ``` ### Complete Configuration Example This example tracks an AI SDK call and attaches `provider` metadata to the event: ```javascript Full Configuration theme={null} import { createLLMTracker } from "@dodopayments/ingestion-blueprints"; import { generateText } from "ai"; import { google } from "@ai-sdk/google"; import "dotenv/config"; async function aiSdkExample() { console.log("🤖 AI SDK Simple Usage Example\n"); try { // 1. Create tracker const llmTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: "test_mode", eventName: "your_meter_event_name", }); // 2. Wrap the ai-sdk methods const client = llmTracker.wrap({ client: { generateText }, customerId: "cus_123", metadata: { provider: "ai-sdk", }, }); // 3. Use the wrapped function const response = await client.generateText({ model: google("gemini-2.5-flash"), prompt: "Hello, I am a cool guy! Tell me a fun fact.", maxOutputTokens: 500, }); console.log(response); console.log(response.usage); console.log("✅ Automatically tracked for customer\n"); } catch (error) { console.error(error); } } aiSdkExample().catch(console.error); ``` > [!NOTE] > > **Automatic Tracking:** The wrapper returns the provider's response unchanged, so your code stays the same as with the original provider SDK. It sends the usage event before it returns the response, so each call waits for the ingestion request, and a failed ingestion request makes the wrapped call throw even when the provider call succeeded. Streaming responses don't carry final token counts on the returned object, so the wrapper doesn't track them. ## Supported Providers The tracker reads token counts from the response formats of these providers and SDKs: > [accordion] AI SDK (Vercel) > > Track usage with the Vercel AI SDK, which gives one interface to many LLM providers. > > ```javascript AI SDK Integration theme={null} > import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; > import { generateText } from 'ai'; > import { google } from '@ai-sdk/google'; > > const llmTracker = createLLMTracker({ > apiKey: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', > eventName: 'aisdk.usage', > }); > > const client = llmTracker.wrap({ > client: { generateText }, > customerId: 'cus_123', > metadata: { > model: 'gemini-2.0-flash', > feature: 'chat' > } > }); > > const response = await client.generateText({ > model: google('gemini-2.0-flash'), > prompt: 'Explain neural networks', > maxOutputTokens: 500 > }); > > console.log('Usage:', response.usage); > ``` > > **Tracked Metrics:** > > * `inputTokens` → `inputTokens` > > * `outputTokens` + `reasoningTokens` → `outputTokens` > > * `totalTokens` → `totalTokens` > > * Model name: AI SDK results have no top-level `model` field, so the tracker records `unknown`. To record the model, pass it as `model` in the wrapper `metadata`, as this example does. > > > [!NOTE] > > > > When you use a reasoning-capable model through the AI SDK, such as Google's Gemini 2.5 Flash with thinking mode, the tracker adds the reported reasoning tokens to `outputTokens`. > [accordion] OpenRouter > > Track token usage across 200+ models through OpenRouter's unified API. > > ```javascript OpenRouter Integration theme={null} > import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; > import OpenAI from 'openai'; > > // OpenRouter uses OpenAI-compatible API > const openrouter = new OpenAI({ > baseURL: 'https://openrouter.ai/api/v1', > apiKey: process.env.OPENROUTER_API_KEY > }); > > const tracker = createLLMTracker({ > apiKey: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', > eventName: 'openrouter.usage' > }); > > const client = tracker.wrap({ > client: openrouter, > customerId: 'cus_123', > metadata: { provider: 'openrouter' } > }); > > const response = await client.chat.completions.create({ > model: 'qwen/qwen3-max', > messages: [{ role: 'user', content: 'What is machine learning?' }], > max_tokens: 500 > }); > > console.log('Response:', response.choices[0].message.content); > console.log('Usage:', response.usage); > ``` > > **Tracked Metrics:** > > * `prompt_tokens` → `inputTokens` > > * `completion_tokens` → `outputTokens` > > * `total_tokens` → `totalTokens` > > * Model name > > > [!TIP] > > > > OpenRouter gives access to models from OpenAI, Anthropic, Google, Meta, and other providers through a single API. > [accordion] OpenAI > > Track token usage from OpenAI's GPT models. > > ```javascript OpenAI Integration theme={null} > import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; > import OpenAI from 'openai'; > > const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); > > const tracker = createLLMTracker({ > apiKey: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', > eventName: 'openai.usage' > }); > > const client = tracker.wrap({ > client: openai, > customerId: 'cus_123' > }); > > // All OpenAI methods work automatically > const response = await client.chat.completions.create({ > model: 'gpt-4', > messages: [{ role: 'user', content: 'Explain quantum computing' }] > }); > > console.log('Total tokens:', response.usage.total_tokens); > ``` > > **Tracked Metrics:** > > * `prompt_tokens` → `inputTokens` > * `completion_tokens` → `outputTokens` > * `total_tokens` → `totalTokens` > * Model name > [accordion] Anthropic Claude > > Track token usage from Anthropic's Claude models. > > ```javascript Anthropic Integration theme={null} > import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; > import Anthropic from '@anthropic-ai/sdk'; > > const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); > > const tracker = createLLMTracker({ > apiKey: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', > eventName: 'anthropic.usage' > }); > > const client = tracker.wrap({ > client: anthropic, > customerId: 'cus_123' > }); > > const response = await client.messages.create({ > model: 'claude-sonnet-4-0', > max_tokens: 1024, > messages: [{ role: 'user', content: 'Explain machine learning' }] > }); > > console.log('Input tokens:', response.usage.input_tokens); > console.log('Output tokens:', response.usage.output_tokens); > ``` > > **Tracked Metrics:** > > * `input_tokens` → `inputTokens` > * `output_tokens` → `outputTokens` > * `totalTokens`, calculated as `input_tokens` + `output_tokens` > * Model name > [accordion] Groq > > Track token usage from models served by Groq. > > ```javascript Groq Integration theme={null} > import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; > import Groq from 'groq-sdk'; > > const groq = new Groq({ apiKey: process.env.GROQ_API_KEY }); > > const tracker = createLLMTracker({ > apiKey: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', > eventName: 'groq.usage' > }); > > const client = tracker.wrap({ > client: groq, > customerId: 'cus_123' > }); > > const response = await client.chat.completions.create({ > model: 'llama-3.1-8b-instant', > messages: [{ role: 'user', content: 'What is AI?' }] > }); > > console.log('Tokens:', response.usage); > ``` > > **Tracked Metrics:** > > * `prompt_tokens` → `inputTokens` > * `completion_tokens` → `outputTokens` > * `total_tokens` → `totalTokens` > * Model name > [accordion] Google Gemini > > Track token usage from Google's Gemini models through the Google GenAI SDK. > > ```javascript Google Gemini Integration theme={null} > import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; > import { GoogleGenAI } from '@google/genai'; > > const googleGenai = new GoogleGenAI({ > apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY > }); > > const tracker = createLLMTracker({ > apiKey: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', > eventName: 'gemini.usage' > }); > > const client = tracker.wrap({ > client: googleGenai, > customerId: 'cus_123' > }); > > const response = await client.models.generateContent({ > model: 'gemini-2.5-flash', > contents: 'Explain quantum computing' > }); > > console.log('Response:', response.text); > console.log('Usage:', response.usageMetadata); > ``` > > **Tracked Metrics:** > > * `promptTokenCount` → `inputTokens` > > * `candidatesTokenCount` + `thoughtsTokenCount` → `outputTokens` > > * `totalTokenCount` → `totalTokens` > > * Model version, from `modelVersion` > > > [!NOTE] > > > > **Gemini Thinking Mode:** For Gemini models that think before they answer, such as Gemini 2.5 Pro, the tracker adds `thoughtsTokenCount` (reasoning tokens) to `outputTokens`, so the event reflects the full output the model produced. ## Advanced Usage ### Multiple Providers To track usage across LLM providers separately, create one tracker per provider: ```javascript Multiple Provider Setup theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import OpenAI from 'openai'; import Groq from 'groq-sdk'; import Anthropic from '@anthropic-ai/sdk'; import { GoogleGenAI } from '@google/genai'; // Create separate trackers for different providers const openaiTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'openai.usage' }); const groqTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'groq.usage' }); const anthropicTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'anthropic.usage' }); const geminiTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'gemini.usage' }); const openrouterTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'openrouter.usage' }); // Initialize clients const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); const groq = new Groq({ apiKey: process.env.GROQ_API_KEY }); const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); const googleGenai = new GoogleGenAI({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY }); const openrouter = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', apiKey: process.env.OPENROUTER_API_KEY }); // Wrap clients const trackedOpenAI = openaiTracker.wrap({ client: openai, customerId: 'cus_123' }); const trackedGroq = groqTracker.wrap({ client: groq, customerId: 'cus_123' }); const trackedAnthropic = anthropicTracker.wrap({ client: anthropic, customerId: 'cus_123' }); const trackedGemini = geminiTracker.wrap({ client: googleGenai, customerId: 'cus_123' }); const trackedOpenRouter = openrouterTracker.wrap({ client: openrouter, customerId: 'cus_123' }); // Use whichever provider you need const response = await trackedOpenAI.chat.completions.create({ model: 'gpt-4', messages: [{ role: 'user', content: 'Hello!' }] }); // or const geminiResponse = await trackedGemini.models.generateContent({ model: 'gemini-2.5-flash', contents: 'Hello!' }); // or const openrouterResponse = await trackedOpenRouter.chat.completions.create({ model: 'qwen/qwen3-max', messages: [{ role: 'user', content: 'Hello!' }] }); ``` > [!TIP] > > Use a different event name for each provider, with a meter for each, to track usage separately. ### Express.js API Integration This Express.js API tracks each chat completion for the customer who made the request. For brevity, it reads `userId` from the request body. `userId` must be the user's Dodo Payments customer ID. In production, read it from the authenticated session instead of trusting the request body. ```javascript Express.js Server theme={null} import express from 'express'; import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import OpenAI from 'openai'; const app = express(); app.use(express.json()); // Initialize OpenAI client const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); // Create tracker once at startup const tracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.NODE_ENV === 'production' ? 'live_mode' : 'test_mode', eventName: 'api.chat_completion' }); // Chat endpoint with automatic tracking app.post('/api/chat', async (req, res) => { try { const { message, userId } = req.body; // Validate input if (!message || !userId) { return res.status(400).json({ error: 'Missing message or userId' }); } // Wrap client for this specific user const trackedClient = tracker.wrap({ client: openai, customerId: userId, metadata: { endpoint: '/api/chat', timestamp: new Date().toISOString() } }); // Make LLM request - automatically tracked const response = await trackedClient.chat.completions.create({ model: 'gpt-4', messages: [{ role: 'user', content: message }], temperature: 0.7 }); const completion = response.choices[0].message.content; res.json({ message: completion, usage: response.usage }); } catch (error) { console.error('Chat error:', error); res.status(500).json({ error: 'Internal server error' }); } }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` ## What Gets Tracked Each tracked call sends one usage event to Dodo Payments with this structure: ```json Event Structure theme={null} { "event_id": "llm_1704709800000_abc123", "customer_id": "cus_123", "event_name": "llm.chat_completion", "timestamp": "2024-01-08T10:30:00.000Z", "metadata": { "inputTokens": 10, "outputTokens": 25, "totalTokens": 35, "model": "gpt-4" } } ``` ### Event Fields **event\_id** `string` Unique identifier for this event. The SDK generates it. Format: `llm_[timestamp]_[random]`, where `timestamp` is the time in milliseconds and `random` is six random characters. **customer\_id** `string` The customer ID you passed when you wrapped the client. Dodo Payments bills this customer. **event\_name** `string` The event name that triggers your meter. It comes from your tracker configuration. **timestamp** `string` ISO 8601 timestamp, set when the tracker sends the event after the provider responds. **metadata** `object` Token usage and additional tracking data: * `inputTokens`: number of input (prompt) tokens used. * `outputTokens`: number of output (completion) tokens used, including reasoning tokens when applicable. * `totalTokens`: total tokens (input + output). * `model`: the LLM model used, such as `gpt-4`, or `unknown` if the response doesn't name one. * `provider`: the LLM provider, if you included it in the wrapper metadata. * Any custom metadata you provided when you wrapped the client. > [!NOTE] > > **Reasoning Tokens:** For models with reasoning capabilities, `outputTokens` includes both the completion tokens and the reasoning tokens. > [!NOTE] > > Your Dodo Payments meter uses the `metadata` fields, usually `inputTokens`, `outputTokens`, or `totalTokens`, to calculate usage and billing. # Object Storage Blueprint Source: https://docs.dodopayments.com/developer-resources/ingestion-blueprints/object-storage Track the bytes customers upload to S3, Google Cloud Storage, Azure Blob Storage, or other object storage, and bill them by upload volume. The Object Storage Blueprint sends a usage event to Dodo Payments each time a customer uploads a file, with the number of bytes uploaded. A **Sum** meter over `bytes` adds up each customer's upload volume, so you can bill for it. The blueprint ships in the `@dodopayments/ingestion-blueprints` npm package as `trackObjectStorage()`, and it works with S3, Google Cloud Storage, Azure Blob Storage, and other object storage services. ## Use Cases The Object Storage Blueprint fits these scenarios: > [card] File Hosting > > Bill customers for the total volume of files they upload. > [card] Backup Services > > Track backup data uploads and charge for the amount of data uploaded. > [card] Media CDN > > Monitor media uploads and bill for upload volume. To bill for delivery bandwidth, use the [Stream Blueprint](/developer-resources/ingestion-blueprints/stream). > [card] Document Management > > Track document uploads per customer for usage-based pricing. > [!NOTE] > > Use it to bill by upload volume for file hosting, media CDN, and backup services. The blueprint counts bytes uploaded, not bytes stored over time. ## Quick Start To track uploads, install the package, create a meter, and send an event after each successful upload. **1. Install the SDK** Install the Dodo Payments Ingestion Blueprints package: ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` **2. Get Your API Keys** You need two sets of credentials: * **Dodo Payments API key**: Create one under **Developer → API Keys** in the [Dodo Payments dashboard](https://app.dodopayments.com/developer/api-keys), and store it in `DODO_PAYMENTS_API_KEY`. Use a test mode key while you build. A test mode key works only with `test_mode`. * **Storage provider credentials**: The credentials your storage SDK uses, for AWS S3, Google Cloud Storage, Azure Blob Storage, or another provider. **3. Create a Meter** In the [Dodo Payments dashboard](https://app.dodopayments.com/), go to **Products → Meters** and click **Create Meter**. Set these fields: * **Meter Name**: a descriptive name, such as `Storage Uploads`. * **Event Name**: `object_storage_upload`, or a name you choose. It must match `eventName` in your code exactly (case-sensitive). * **Aggregation Type**: **Sum**, to add up the bytes uploaded. * **Over Property**: `bytes`, to bill by upload size. * **Measurement Unit**: the unit shown on invoices, such as `bytes`. **4. Track Storage Usage** Send the event after the storage call succeeds. In these examples, a failed upload throws before `trackObjectStorage()` runs, so it isn't billed. ```javascript AWS S3 Upload theme={null} import { Ingestion, trackObjectStorage } from '@dodopayments/ingestion-blueprints'; import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; import fs from 'fs'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'object_storage_upload' }); const s3 = new S3Client({ region: 'us-east-1' }); // Read the file (example: from disk or request) const fileBuffer = fs.readFileSync('./document.pdf'); // Upload to S3 const command = new PutObjectCommand({ Bucket: 'my-bucket', Key: 'uploads/document.pdf', Body: fileBuffer }); await s3.send(command); // Track the upload await trackObjectStorage(ingestion, { customerId: 'cus_123', bytes: fileBuffer.length }); ``` ```javascript Google Cloud Storage theme={null} import { Ingestion, trackObjectStorage } from '@dodopayments/ingestion-blueprints'; import { Storage } from '@google-cloud/storage'; import fs from 'fs'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'object_storage_upload' }); const storage = new Storage(); const bucket = storage.bucket('my-bucket'); // Read the file const fileBuffer = fs.readFileSync('./image.png'); // Upload to GCS await bucket.file('uploads/image.png').save(fileBuffer); // Track the upload await trackObjectStorage(ingestion, { customerId: 'cus_456', bytes: fileBuffer.length, metadata: { bucket: 'my-bucket', key: 'uploads/image.png' } }); ``` ## Configuration ### Ingestion Configuration Pass these options to `new Ingestion()`: **apiKey** `string` *required* Your Dodo Payments API key from the dashboard. **environment** `string` Environment mode: `test_mode` or `live_mode`. Defaults to `test_mode`. The Dodo Payments SDKs default to `live_mode` instead, so set `live_mode` explicitly in production. **eventName** `string` *required* Event name that matches your meter's **Event Name** (case-sensitive). ### Track Object Storage Options Pass these options to `trackObjectStorage()`: **customerId** `string` *required* The Dodo Payments customer ID to bill for the upload, for example `cus_123`. **bytes** `number` Number of bytes uploaded. Required for byte-based billing. If you omit it, the event has no `bytes` value, but it still counts toward a **Count** meter. **metadata** `object` Optional metadata about the upload, such as bucket name or content type. Each value must be a string, number, or boolean. ## Best Practices > [!TIP] > > **Track Before or After Upload**: You can track the event before or after the actual upload, depending on your error handling strategy. The API has no endpoint to delete an ingested event. An event sent before an upload that then fails stays in the customer's usage. > [!WARNING] > > **Handle Upload Failures**: Only track successful uploads, so you don't bill for failed operations. # Stream Blueprint Source: https://docs.dodopayments.com/developer-resources/ingestion-blueprints/stream Track the bytes each customer streams for video, audio, live streams, and real-time data transfer, and bill them for bandwidth in Dodo Payments. The Stream Blueprint sends a usage event to Dodo Payments with the number of bytes a customer consumed from a stream. A **Sum** meter over `bytes` adds up each customer's bandwidth, so you can bill for it. The blueprint ships in the `@dodopayments/ingestion-blueprints` npm package as `trackStreamBytes()`. ## Use Cases The Stream Blueprint fits these scenarios: > [card] Video Platforms > > Bill customers for video bandwidth consumption and streaming quality. > [card] Music Streaming > > Track audio streaming usage per user for subscription tiers. > [card] Live Events > > Monitor live stream consumption and charge for bandwidth usage. > [card] Real-Time Data > > Track real-time data transfer for IoT and telemetry applications. > [!NOTE] > > Use it for video and audio streaming platforms, live streaming services, and real-time data applications. ## Quick Start To track streaming usage, install the package, create a meter, and send the bytes each customer consumes. **1. Install the SDK** Install the Dodo Payments Ingestion Blueprints package: ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` **2. Get Your API Keys** Create a Dodo Payments API key under **Developer → API Keys** in the [Dodo Payments dashboard](https://app.dodopayments.com/developer/api-keys), and store it in the `DODO_PAYMENTS_API_KEY` environment variable. Use a test mode key while you build. A test mode key works only with `test_mode`. **3. Create a Meter** In the [Dodo Payments dashboard](https://app.dodopayments.com/), go to **Products → Meters** and click **Create Meter**. Set these fields: * **Meter Name**: a descriptive name, such as `Stream Bandwidth`. * **Event Name**: `stream_consumption`, or a name you choose. It must match `eventName` in your code exactly (case-sensitive). * **Aggregation Type**: **Sum**, to add up the bytes streamed. * **Over Property**: `bytes`, to bill by bandwidth usage. * **Measurement Unit**: the unit shown on invoices, such as `bytes`. **4. Track Stream Usage** Call `trackStreamBytes()` with the customer and the number of bytes consumed: ```javascript Video Streaming theme={null} import { Ingestion, trackStreamBytes } from '@dodopayments/ingestion-blueprints'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'stream_consumption' }); // Track video stream consumption await trackStreamBytes(ingestion, { customerId: 'cus_123', bytes: 10485760, // 10MB metadata: { stream_type: 'video', } }); ``` ## Configuration ### Ingestion Configuration Pass these options to `new Ingestion()`: **apiKey** `string` *required* Your Dodo Payments API key from the dashboard. **environment** `string` Environment mode: `test_mode` or `live_mode`. Defaults to `test_mode`. The Dodo Payments SDKs default to `live_mode` instead, so set `live_mode` explicitly in production. **eventName** `string` *required* Event name that matches your meter's **Event Name** (case-sensitive). ### Track Stream Bytes Options Pass these options to `trackStreamBytes()`: **customerId** `string` *required* The Dodo Payments customer ID to bill for the stream, for example `cus_123`. **bytes** `number` Number of bytes consumed in the stream. Required for bandwidth-based billing. If you omit it, the event has no `bytes` value, but it still counts toward a **Count** meter. **metadata** `object` Optional metadata about the stream, such as stream type, quality, or session ID. Each value must be a string, number, or boolean. ## Best Practices > [!TIP] > > **Track by Chunk**: For long streams, track consumption in chunks rather than waiting for the entire stream to complete. Each call to `trackStreamBytes()` sends a separate event, and a **Sum** meter adds the chunks together. > [!WARNING] > > **Accurate Byte Counting**: If you bill for total bandwidth, include all overhead, such as headers and protocol overhead, in your byte counts. # Time Range Blueprint Source: https://docs.dodopayments.com/developer-resources/ingestion-blueprints/time-range Track elapsed time for compute, serverless functions, containers, and background jobs, and bill customers for runtime in Dodo Payments. The Time Range Blueprint sends a usage event to Dodo Payments with how long a resource ran for a customer, in milliseconds, seconds, or minutes. A **Sum** meter over that duration adds up each customer's runtime, so you can bill for compute time. The blueprint ships in the `@dodopayments/ingestion-blueprints` npm package as `trackTimeRange()`. ## Use Cases The Time Range Blueprint fits these scenarios: > [card] Serverless Functions > > Bill based on function execution time and memory usage. > [card] Container Runtime > > Track container running time for usage-based billing. > [card] Compute Instances > > Monitor VM runtime and charge by the minute or hour. > [card] Background Jobs > > Track processing time for data exports, reports, and batch jobs. > [!NOTE] > > Use it to bill for compute time, function execution duration, container runtime, or any other time-based usage. ## Quick Start To track runtime, install the package, create a meter, and send the duration each time a resource finishes running. **1. Install the SDK** Install the Dodo Payments Ingestion Blueprints package: ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` **2. Get Your API Keys** Create a Dodo Payments API key under **Developer → API Keys** in the [Dodo Payments dashboard](https://app.dodopayments.com/developer/api-keys), and store it in the `DODO_PAYMENTS_API_KEY` environment variable. Use a test mode key while you build. A test mode key works only with `test_mode`. **3. Create a Meter** In the [Dodo Payments dashboard](https://app.dodopayments.com/), go to **Products → Meters** and click **Create Meter**. Set these fields: * **Meter Name**: a descriptive name, such as `Compute Time`. * **Event Name**: `time_range_usage`, or a name you choose. It must match `eventName` in your code exactly (case-sensitive). The examples in the next step use a separate event name for each resource type, such as `function_execution`, so each one needs its own meter. * **Aggregation Type**: **Sum**, to add up the total duration. * **Over Property**: the duration key you send: `durationSeconds`, `durationMinutes`, or `durationMs`. * **Measurement Unit**: the unit shown on invoices, such as `seconds`. **4. Track Time Usage** Measure how long the work ran, then call `trackTimeRange()` with the duration in the unit your meter uses: ```javascript Serverless Functions theme={null} import { Ingestion, trackTimeRange } from '@dodopayments/ingestion-blueprints'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'function_execution' }); // Track function execution time const startTime = Date.now(); // Execute your function (example: image processing) const result = await yourImageProcessingLogic(); const durationMs = Date.now() - startTime; await trackTimeRange(ingestion, { customerId: 'cus_123', durationMs: durationMs }); ``` ```javascript Container Runtime theme={null} import { Ingestion, trackTimeRange } from '@dodopayments/ingestion-blueprints'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'container_runtime' }); // Track container runtime in seconds await trackTimeRange(ingestion, { customerId: 'cus_456', durationSeconds: 120 }); ``` ```javascript VM Instance Runtime theme={null} import { Ingestion, trackTimeRange } from '@dodopayments/ingestion-blueprints'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', eventName: 'vm_runtime' }); // Track VM runtime in minutes await trackTimeRange(ingestion, { customerId: 'cus_789', durationMinutes: 60 }); ``` ## Configuration ### Ingestion Configuration Pass these options to `new Ingestion()`: **apiKey** `string` *required* Your Dodo Payments API key from the dashboard. **environment** `string` Environment mode: `test_mode` or `live_mode`. Defaults to `test_mode`. The Dodo Payments SDKs default to `live_mode` instead, so set `live_mode` explicitly in production. **eventName** `string` *required* Event name that matches your meter's **Event Name** (case-sensitive). ### Track Time Range Options Pass these options to `trackTimeRange()`. Each duration you pass is sent as a metadata key with the same name. **customerId** `string` *required* The Dodo Payments customer ID to bill for the runtime, for example `cus_123`. **durationMs** `number` Duration in milliseconds. Use for sub-second precision. **durationSeconds** `number` Duration in seconds. Most common for function execution and short tasks. **durationMinutes** `number` Duration in minutes. Useful for longer-running resources like VMs. **metadata** `object` Optional metadata about the resource, such as CPU, memory, or region. Each value must be a string, number, or boolean. ## Best Practices > [!TIP] > > **Choose the Right Unit**: Use milliseconds for short operations, seconds for functions, and minutes for longer-running resources. A meter sums only the key that its **Over Property** names, so send the duration in the same unit every time. > [!WARNING] > > **Accurate Timing**: Use `Date.now()` or `performance.now()` for accurate time tracking, especially for serverless functions. # On-Demand Subscriptions Source: https://docs.dodopayments.com/developer-resources/ondemand-subscriptions Dodo Payments on-demand subscriptions let you authorize a payment method once and charge variable amounts whenever you need. Create subscriptions, trigger charges, handle failures, and implement safe retry policies. ## Overview On-demand subscriptions let you authorize a customer's payment method once and then charge variable amounts whenever you need, instead of on a fixed schedule. This feature is available for all accounts—no approval required. Use this guide to: * Create an on-demand subscription (authorize a mandate with optional initial price) * Trigger subsequent charges with custom amounts * Track outcomes using webhooks For a general subscription setup, see the [Subscription Integration Guide](/developer-resources/subscription-integration-guide). ## Prerequisites * Dodo Payments merchant account and API key * Webhook secret configured and an endpoint to receive events * A subscription product in your catalog > [!TIP] > > This guide creates the on-demand subscription through a checkout session (`POST /checkouts`), which returns a hosted `checkout_url`. Redirect the customer there to approve the mandate, and set `return_url` to where they should land afterward. ## How On-Demand Works 1. You create a checkout session with the `subscription_data.on_demand` object to authorize a payment method and optionally collect an initial charge. 2. Later, you create charges against that subscription with custom amounts using the dedicated charge endpoint. 3. You listen to webhooks (e.g., `payment.succeeded`, `payment.failed`) to update your system. ## Create an On-Demand Subscription Endpoint: [POST /checkouts](/api-reference/checkout-sessions/create) Key request fields (body):\ Please find them in [Create Checkout Session](/api-reference/checkout-sessions/create) ### Create an On-Demand Subscription > [tab] Node.js SDK > > ```javascript theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', // defaults to 'live_mode' > }); > > async function main() { > const subscription = await client.checkoutSessions.create({ > product_cart: [{ product_id: 'pdt_123', quantity: 1 }], > billing_address: { city: 'SF', country: 'US', state: 'CA', street: '1 Market St', zipcode: '94105' }, > customer: { customer_id: 'cus_123' }, > return_url: 'https://example.com/billing/success', > subscription_data: { > on_demand: { > mandate_only: true // set false to collect an initial charge > // product_price: 1000, // optional: charge $10.00 now if mandate_only is false > // product_currency: 'USD', > // product_description: 'Custom initial charge', > // adaptive_currency_fees_inclusive: false, > } > } > }); > > console.log(subscription.checkout_url); > } > > main().catch(console.error); > ``` > [tab] Python SDK > > ```python theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ.get('DODO_PAYMENTS_API_KEY'), > environment="test_mode", # defaults to "live_mode" > ) > > checkout = client.checkout_sessions.create( > product_cart=[ > {"product_id": "pdt_123", "quantity": 1} > ], > billing_address={ > "city": "SF", > "country": "US", > "state": "CA", > "street": "1 Market St", > "zipcode": "94105", > }, > customer={ > "customer_id": "cus_123", > }, > return_url="https://example.com/billing/success", > subscription_data={ > "on_demand":{ > "mandate_only": True, # set False to collect an initial charge > # "product_price": 1000, # optional: charge $10.00 now if mandate_only is false > # "product_currency": "USD", > # "product_description": "Custom initial charge", > # "adaptive_currency_fees_inclusive": False, > } > }, > ) > > print(checkout.checkout_url) > ``` > [tab] Go SDK > > ```go theme={null} > package main > > import ( > "context" > "fmt" > "os" > > "github.com/dodopayments/dodopayments-go" > "github.com/dodopayments/dodopayments-go/option" > ) > > func main() { > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > option.WithEnvironmentTestMode(), // defaults to live mode > ) > > checkout, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{ > CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ > ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{ > { > ProductID: dodopayments.F("pdt_123"), > Quantity: dodopayments.F(int64(1)), > }, > }), > BillingAddress: dodopayments.F(dodopayments.CheckoutSessionBillingAddressParam{ > City: dodopayments.F("SF"), > Country: dodopayments.F(dodopayments.CountryCodeUs), > State: dodopayments.F("CA"), > Street: dodopayments.F("1 Market St"), > Zipcode: dodopayments.F("94105"), > }), > Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam]( > dodopayments.AttachExistingCustomerParam{ > CustomerID: dodopayments.F("cus_123"), > }, > ), > ReturnURL: dodopayments.F("https://example.com/billing/success"), > SubscriptionData: dodopayments.F(dodopayments.SubscriptionDataParam{ > OnDemand: dodopayments.F(dodopayments.OnDemandSubscriptionParam{ > MandateOnly: dodopayments.F(true), // set false to collect an initial charge > // ProductPrice: dodopayments.F(int64(1000)), // optional: charge $10.00 now if mandate_only is false > // ProductCurrency: dodopayments.F(dodopayments.CurrencyUsd), > // ProductDescription: dodopayments.F("Custom initial charge"), > }), > }), > }, > }) > if err != nil { > panic(err) > } > > fmt.Println(checkout.CheckoutURL) > } > ``` > [tab] cURL > > ```bash theme={null} > curl -X POST "$DODO_API/checkouts" \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_cart": [ > { > "product_id": "pdt_123", > "quantity": 1 > } > ], > "customer": { > "customer_id": "cus_123" > }, > "billing_address": { > "street": "1 Market St", > "city": "SF", > "state": "CA", > "country": "US", > "zipcode": "94105" > }, > "subscription_data": { > "on_demand": { > "mandate_only": true > } > }, > "return_url": "https://example.com/billing/success" > }' > ``` ```json Success theme={null} { "session_id": "cks_123", "checkout_url": "https://test.checkout.dodopayments.com/session/cks123" } ``` ## Charge an On-Demand Subscription After the mandate is authorized, create charges as needed. Endpoint: [POST /subscriptions/\{subscription\_id}/charge](/api-reference/subscriptions/create-charge) Key request fields (body): > [accordion] Charge request body parameters > > **product\_price** `integer` *required* > > Amount to charge (in the smallest currency unit). Example: to charge \$25.00, pass `2500`. > > **product\_currency** `string` > > Optional currency override for the charge. > > **product\_description** `string` > > Optional description override for this charge. > > **adaptive\_currency\_fees\_inclusive** `boolean` > > If true, includes adaptive currency fees within `product_price`. If false, fees are added on top. > > **customer\_balance\_config** `object` > > Specify whether the customer's Customer Credit balance can be used (`allow_customer_credits_usage`), or Customer Credit purchased (`allow_customer_credits_purchase`), to settle this charge. > > **metadata** `object` > > Additional metadata for the payment. If omitted, the subscription metadata is used. > [tab] Node.js SDK > > ```javascript theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY }); > > async function chargeNow(subscriptionId) { > const res = await client.subscriptions.charge(subscriptionId, { product_price: 2500 }); > console.log(res.payment_id); > } > > chargeNow('sub_123').catch(console.error); > ``` > [tab] Python SDK > > ```python theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments(bearer_token=os.environ.get('DODO_PAYMENTS_API_KEY')) > > response = client.subscriptions.charge( > subscription_id="sub_123", > product_price=2500, > ) > > print(response.payment_id) > ``` > [tab] Go SDK > > ```go theme={null} > package main > > import ( > "context" > "fmt" > "github.com/dodopayments/dodopayments-go" > "github.com/dodopayments/dodopayments-go/option" > ) > > func main() { > client := dodopayments.NewClient(option.WithBearerToken("dodo_test_...")) > res, err := client.Subscriptions.Charge(context.TODO(), "sub_123", dodopayments.SubscriptionChargeParams{ > ProductPrice: dodopayments.F(int64(2500)), > }) > if err != nil { panic(err) } > fmt.Println(res.PaymentID) > } > ``` > [tab] cURL > > ```bash theme={null} > curl -X POST "$DODO_API/subscriptions/sub_123/charge" \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_price": 2500, > "product_description": "Extra usage for March" > }' > ``` ```json Success theme={null} { "payment_id": "pay_abc123" } ``` > [!WARNING] > > Charging a subscription that isn't on-demand fails with `400` (`SUBSCRIPTION_NOT_ON_DEMAND`). Check that the subscription has `on_demand: true` before you charge it. On-demand subscriptions also can't change plan: `POST /subscriptions/{subscription_id}/change-plan` returns `422` for them. ## Handling Failed Charges When a charge against an on-demand subscription fails, you decide what happens next. Unlike scheduled subscriptions — where a failed renewal stops further automatic billing — **on-demand subscriptions remain chargeable after a failure**. You can call the charge endpoint again as part of your own retry logic. ### What Happens on Failure **1. Charge attempt fails** The `POST /subscriptions/{subscription_id}/charge` request either returns an error response or completes asynchronously and emits a `payment.failed` webhook with the decline reason. **2. Subscription may transition to on\_hold** The subscription may move to the `on_hold` state and emit a `subscription.on_hold` webhook (see [Subscription States → On Hold](/features/subscription#on-hold-state)). This is a signal — not a lock. For on-demand subscriptions, `on_hold` does **not** prevent you from charging again. A new charge is rejected with `409` while the previous payment is still pending, and with `429` once more than four payments have failed since the last successful one. **3. Retry the charge (your call)** For on-demand flows, Dodo does **not** auto-retry. You can call `POST /subscriptions/{subscription_id}/charge` again at any time to retry. Apply the [safe retry policy](#payment-retries) below — use exponential backoff, skip hard declines, and avoid burst patterns — so retries are not flagged by our fraud and risk systems. **4. Optionally, ask the customer for a new payment method** If retries keep failing because the payment method itself is broken (expired card, closed account, etc.), use [`POST /subscriptions/{subscription_id}/update-payment-method`](/api-reference/subscriptions/update-payment-method) to collect a new one from the customer. On success, the subscription returns to `active` and `payment.succeeded` followed by `subscription.active` webhooks are emitted. > [!NOTE] > > **On-demand vs scheduled**: For scheduled subscriptions, Dodo runs its own renewal retries and dunning. For on-demand subscriptions, you own the retry policy because only you know when the next charge should occur (it's driven by your usage events, not a calendar). ### Webhook Sequence on a Failed On-Demand Charge | Order | Event | Meaning | | - | - | - | | 1 | `payment.failed` | The on-demand charge attempt did not succeed (includes the decline reason) | | 2 | `subscription.on_hold` | The subscription was placed on hold (informational; does not block further charges) | | 3\* | `payment.succeeded` | A subsequent charge — either your retry or after a payment method update — succeeded | | 4\* | `subscription.active` | The subscription returned to `active` after a successful charge | > [!NOTE] > > Events 3 and 4 only fire after a follow-up charge succeeds. ### Retry Responsibility > [!WARNING] > > Dodo Payments **does not auto-retry failed on-demand charges**. You own the retry policy. Follow the safe retry guidelines below to avoid being flagged by our fraud detection systems as card testing. [Subscription Dunning](/features/recovery/subscription-dunning) — the built-in email recovery sequence — is scoped to failed *renewal* payments on scheduled subscriptions and customer-initiated cancellations. It is not designed for on-demand charge failures. Communicate with the customer directly (e.g., transactional email or in-app prompt) when you decide the payment method needs to be updated. ## Payment Retries Our fraud detection system may block aggressive retry patterns (and can flag them as potential card testing). Follow a safe retry policy. > [!WARNING] > > Burst retry patterns can be flagged as fraudulent or suspected card testing by our risk systems and processors. Avoid clustered retries; follow the backoff schedule and time alignment guidance below. ### Principles for Safe Retry Policies * **Backoff mechanism**: Use exponential backoff between retries. * **Retry limits**: Cap total retries (3–4 attempts max). * **Intelligent filtering**: Retry only on retryable failures (e.g., network/issuer errors, insufficient funds); never retry hard declines. * **Card testing prevention**: Do not retry failures like `TRANSACTION_NOT_APPROVED`, `STOLEN_CARD`, `LOST_CARD`, `PICKUP_CARD`, `FRAUDULENT`, `AUTHENTICATION_FAILURE`. * **Vary metadata (optional)**: If you maintain your own retry system, differentiate retries via metadata (e.g., `retry_attempt`). ### Suggested Retry Schedule (Subscriptions) * **1st attempt**: Immediate when you create the charge * **2nd attempt**: After 3 days * **3rd attempt**: After 7 more days (10 days total) * **4th attempt (final)**: After another 7 days (17 days total) Final step: if still unpaid, mark the subscription as unpaid or cancel it, based on your policy. Notify the customer during the window to update their payment method. ### Avoid Burst Retries; Align to Authorization Time * Anchor retries to the original authorization timestamp to avoid "burst" behavior across your portfolio. * Example: If the customer starts a trial or mandate at 1:10 pm today, schedule follow-up retries at 1:10 pm on subsequent days per your backoff (e.g., +3 days → 1:10 pm, +7 days → 1:10 pm). * Alternatively, if you store the last successful payment time `T`, schedule the next attempt at `T + X days` to preserve time-of-day alignment. > [!NOTE] > > Time-zone and DST: use a consistent time standard for scheduling and convert for display only to maintain intervals. ### Decline Codes You Should Not Retry * `STOLEN_CARD` * `TRANSACTION_NOT_APPROVED` * `FRAUDULENT` * `PICKUP_CARD` * `AUTHENTICATION_FAILURE` * `LOST_CARD` > [!NOTE] > > For a comprehensive list of decline reasons and whether they are user-correctable, see the > [Transaction Failures](/api-reference/transaction-failures) documentation. > [!TIP] > > Only retry on soft/temporary issues (e.g., `insufficient_funds`, `issuer_unavailable`, `processing_error`, network timeouts). If the same decline repeats, pause further retries. ### Implementation Guidelines (No Code) * Use a scheduler/queue that persists precise timestamps; compute next attempt at the exact time-of-day offset (e.g., `T + 3 days` at the same HH:MM). * Maintain and reference the last successful payment timestamp `T` to compute the next attempt; do not bunch multiple subscriptions at the same instant. * Always evaluate the last decline reason; stop retries for hard declines in the skip list above. * Cap concurrent retries per customer and per account to prevent accidental surges. * Communicate proactively: email/SMS the customer to update their payment method before the next scheduled attempt. * Use metadata only for observability (e.g., `retry_attempt`); never try to "evade" fraud/risk systems by rotating inconsequential fields. ## Cancellation On-demand subscriptions follow a different cancellation flow from scheduled subscriptions because there is no fixed billing cycle to anchor an immediate end date. ### Customer Portal Behavior When a customer cancels an on-demand subscription from the [Customer Portal](/features/customer-portal), the cancellation is **scheduled for the next billing date** by default. The **Cancel Now** option is intentionally not shown for on-demand subscriptions. The reason: on-demand subscriptions do not have predictable recurring renewal dates — the next charge time is driven entirely by your usage events. Scheduling cancellation at the next billing date keeps the mandate active until the period boundary so any in-flight usage can still be charged, then ends the subscription cleanly. After the customer confirms cancellation: * The subscription stays `active` and remains chargeable via `POST /subscriptions/{id}/charge` until the scheduled cancellation date. * `cancel_at_next_billing_date` is set to `true` on the subscription. * A `subscription.cancelled` webhook is emitted when the cancellation takes effect. > [!NOTE] > > If you need to end the subscription immediately (for example, in response to a refund or a support request), cancel it programmatically via the API instead of relying on the customer portal flow. ### Cancel Programmatically You can cancel an on-demand subscription via the API at any time. You control whether the cancellation is immediate or scheduled. Endpoint: [PATCH /subscriptions/\{subscription\_id}](/api-reference/subscriptions/patch-subscriptions) > [tab] Cancel immediately > > Set the subscription `status` to `cancelled` to end it right away. The mandate is revoked and no further charges can be created. > > ```javascript theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY }); > > await client.subscriptions.update('sub_123', { > status: 'cancelled', > }); > ``` > > ```bash cURL theme={null} > curl -X PATCH "$DODO_API/subscriptions/sub_123" \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ "status": "cancelled" }' > ``` > [tab] Cancel at next billing date > > Mirror the customer portal behavior — keep the subscription active until the scheduled cancellation date, then end it. > > ```javascript theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY }); > > await client.subscriptions.update('sub_123', { > cancel_at_next_billing_date: true, > }); > ``` > > ```bash cURL theme={null} > curl -X PATCH "$DODO_API/subscriptions/sub_123" \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ "cancel_at_next_billing_date": true }' > ``` ### Webhooks on Cancellation | Event | When it fires | | - | - | | `subscription.cancelled` | Subscription is fully cancelled and no longer chargeable | Setting or clearing `cancel_at_next_billing_date` sends no dedicated webhook. To track a scheduled cancellation, read `cancel_at_next_billing_date` from the API response or from the next `subscription.updated` payload. > [!TIP] > > To distinguish on-demand cancellations from scheduled-subscription cancellations in your handler, check the subscription's `on_demand` flag when processing the webhook. ## Track Outcomes with Webhooks Implement webhook handling to track the customer journey. See [Webhooks](/developer-resources/integration-guide#webhooks). * **subscription.active**: Mandate authorized and subscription activated * **subscription.failed**: Creation failed (e.g., mandate failure) * **subscription.on\_hold**: Subscription placed on hold (e.g., unpaid state) * **subscription.cancelled**: Subscription fully cancelled (see [Cancellation](#cancellation)) * **payment.succeeded**: Charge succeeded * **payment.failed**: Charge failed > [!TIP] > > For on-demand flows, focus on `payment.succeeded` and `payment.failed` to reconcile usage-based charges. When `payment.failed` is followed by `subscription.on_hold`, see [Handling failed charges](#handling-failed-charges) to recover the subscription. ## Testing and Next Steps **1. Create in test mode** Use your test API key to create the subscription, then open the returned `checkout_url` and complete the mandate. **2. Trigger a charge** Call the charge endpoint with a small `product_price` (e.g., `100`) and verify you receive `payment.succeeded`. **3. Go live** Switch to your live API key once you have validated events and internal state updates. ## Troubleshooting * **422 Invalid Request**: Ensure `subscription_data.on_demand.mandate_only` is provided on creation and `product_price` is provided for charges. * **Currency errors**: If you override `product_currency`, confirm it's supported for your account and customer. * **No webhooks received**: Verify your webhook URL and signature secret configuration. # C# Source: https://docs.dodopayments.com/developer-resources/sdks/csharp Use the Dodo Payments C# SDK to create checkout sessions, customers, and subscriptions from .NET, with typed models, automatic retries, and pagination. The C# SDK gives .NET applications typed access to the Dodo Payments REST API. Every API method is asynchronous and returns a `Task`, requests and responses are typed classes, and the client retries failed requests for you. ## Installation Install the package from [NuGet](https://www.nuget.org/packages/DodoPayments.Client): ```bash theme={null} dotnet add package DodoPayments.Client ``` > [!NOTE] > > The SDK requires .NET Standard 2.0 or later, and it also ships a .NET 8 build. It works with ASP.NET Core, console applications, and other .NET project types. The examples on this page use C# 12 syntax, such as collection expressions. ## Quick Start Create a client, then create a checkout session: ```csharp theme={null} using System; using DodoPayments.Client; using DodoPayments.Client.Models.CheckoutSessions; // Configured using the DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_WEBHOOK_KEY, and DODO_PAYMENTS_BASE_URL environment variables DodoPaymentsClient client = new(); CheckoutSessionCreateParams parameters = new() { ProductCart = [ new() { ProductID = "pdt_123", Quantity = 1, }, ], }; var checkoutSessionResponse = await client.CheckoutSessions.Create(parameters); Console.WriteLine(checkoutSessionResponse.SessionID); ``` If you don't set `BearerToken`, the client reads the `DODO_PAYMENTS_API_KEY` environment variable. If you don't set `BaseUrl` or `DODO_PAYMENTS_BASE_URL`, the client connects to live mode. To use test mode, see [Environments](#environments). A test mode API key works only in test mode. > [!WARNING] > > Keep API keys in environment variables, user secrets, or Azure Key Vault. Never hardcode them in your source code or commit them to version control. ## Core Features > [card] Async/Await > > Every API method returns a `Task` and accepts an optional `CancellationToken`. > [card] Strong Typing > > Typed request and response classes, with nullable reference type annotations. > [card] Smart Retries > > Two retries by default, with exponential backoff, for connection errors and retryable status codes. > [card] Error Handling > > An exception class for each common HTTP error status, with the status code and response body. ## Configuration ### Environment Variables Store your API key in an environment variable: ```bash .env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... ``` A client created with `new()` reads its settings from the environment: ```csharp theme={null} // Automatically reads from environment variables DodoPaymentsClient client = new(); ``` The client reads these environment variables when you don't set the matching property: | Property | Environment variable | Required | Default value | | - | - | - | - | | `BearerToken` | `DODO_PAYMENTS_API_KEY` | true | - | | `WebhookKey` | `DODO_PAYMENTS_WEBHOOK_KEY` | false | - | | `BaseUrl` | `DODO_PAYMENTS_BASE_URL` | true | `"https://live.dodopayments.com"` | If neither `BearerToken` nor `DODO_PAYMENTS_API_KEY` is set, the client throws `DodoPaymentsInvalidDataException`. `WebhookKey` holds your webhook signing secret, but the C# SDK has no method that verifies webhook signatures. To verify them, follow [Webhooks](/developer-resources/webhooks). ### Manual Configuration Set properties on the client to override the environment variables: ```csharp theme={null} DodoPaymentsClient client = new() { BearerToken = "dodo_test_..." }; ``` ### Environments The client connects to live mode (`https://live.dodopayments.com`) by default. To use test mode (`https://test.dodopayments.com`), set `BaseUrl` to `EnvironmentUrl.TestMode`: ```csharp theme={null} using DodoPayments.Client.Core; DodoPaymentsClient client = new() { BaseUrl = EnvironmentUrl.TestMode }; ``` ### Retries The SDK retries connection errors and responses with status 408, 409, 429, or 500 and above. It retries twice by default, with exponential backoff. Set `MaxRetries` to change the number of retries, or set it to `0` to turn retries off: ```csharp theme={null} // Custom retry count DodoPaymentsClient client = new() { MaxRetries = 3 }; ``` ### Timeouts Each request attempt times out after 1 minute by default. The timeout doesn't include retries. Set `Timeout` to change it: ```csharp theme={null} DodoPaymentsClient client = new() { Timeout = TimeSpan.FromSeconds(30) }; ``` ### Per-Request Overrides To change settings for a single call, call `WithOptions` on the client or on a service. It returns a modified copy that shares the same connection pool, and the original client doesn't change: ```csharp theme={null} var response = await client .WithOptions(options => options with { Timeout = TimeSpan.FromSeconds(10), MaxRetries = 5, }) .CheckoutSessions.Create(parameters); ``` ## Workload Identity The SDK can use workload identity federation instead of an API key. The SDK exchanges an OIDC token from your CI or cloud platform for a short-lived Dodo Payments token. It refreshes the token before the token expires. This feature is available from version 6.42.0. Before you start, create an identity provider and a mapping in the dashboard. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup). This example uses the GitHub Actions helper, `WorkloadIdentityProviders.GitHubActions()`: ```csharp theme={null} using DodoPayments.Client; using DodoPayments.Client.Core; DodoPaymentsClient client = new() { BaseUrl = EnvironmentUrl.LiveMode, WorkloadIdentity = new() { IdentityProviderID = "wip_...", Provider = WorkloadIdentityProviders.GitHubActions(), }, }; ``` If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the SDK uses workload identity. It finds the platform from the environment. To stop the token before it expires, for example at the end of a CI job, revoke it: ```csharp theme={null} await client.RevokeWorkloadIdentityToken(); ``` > [!WARNING] > > Do not set an API key and workload identity together. The SDK gives an error when you set the two options. For the other platform helpers and the refresh behavior, refer to [Use Workload Identity with the SDKs](/developer-resources/workload-identity/sdk-usage). ## Common Operations The examples in this section use the `client` from [Quick Start](#quick-start). ### Create a Checkout Session Create a checkout session, then redirect the customer to the returned `CheckoutUrl`: ```csharp theme={null} var parameters = new CheckoutSessionCreateParams { ProductCart = [ new() { ProductID = "pdt_123", Quantity = 1 } ], ReturnUrl = "https://yourdomain.com/return" }; var session = await client.CheckoutSessions.Create(parameters); Console.WriteLine($"Checkout URL: {session.CheckoutUrl}"); ``` Each checkout URL works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session). ### Manage Customers Create a customer with an email address and name, then retrieve it by ID: ```csharp theme={null} using DodoPayments.Client.Models.Customers; // Create a customer var customer = await client.Customers.Create(new CustomerCreateParams { Email = "customer@example.com", Name = "John Doe" }); // Retrieve customer var retrieved = await client.Customers.Retrieve(new CustomerRetrieveParams { CustomerID = "cus_123" }); Console.WriteLine($"Customer: {retrieved.Name} ({retrieved.Email})"); ``` `Customers.Retrieve` also accepts the ID as a string, for example `client.Customers.Retrieve("cus_123")`. ### Handle Subscriptions Start a subscription with a checkout session, then charge it if it's an on-demand subscription. ```csharp theme={null} using DodoPayments.Client.Models.CheckoutSessions; using DodoPayments.Client.Models.Payments; using DodoPayments.Client.Models.Subscriptions; // Start a subscription: put a subscription product in ProductCart var session = await client.CheckoutSessions.Create(new CheckoutSessionCreateParams { ProductCart = [ new() { ProductID = "pdt_456", Quantity = 1, }, ], Customer = new AttachExistingCustomer { CustomerID = "cus_123" }, ReturnUrl = "https://yourdomain.com/return", }); Console.WriteLine($"Checkout URL: {session.CheckoutUrl}"); // Charge an on-demand subscription // ProductPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD) var charge = await client.Subscriptions.Charge(new SubscriptionChargeParams { SubscriptionID = "sub_123", ProductPrice = 2500, }); ``` > [!NOTE] > > The subscription starts when the customer completes checkout. Read its `subscription_id` from the `subscription.active` webhook or from the `return_url` query parameters. `Customer` takes an `AttachExistingCustomer` to attach an existing customer or a `NewCustomer` to create one. `Charge` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions), and `ProductPrice` is in the smallest currency unit. ## Error Handling When the API returns an error status, the SDK throws a subclass of `DodoPaymentsApiException`, which has `StatusCode` and `ResponseBody` properties. The exception class depends on the status code. All 4xx exceptions inherit from `DodoPayments4xxException`. | Status | Exception | | - | - | | 400 | `DodoPaymentsBadRequestException` | | 401 | `DodoPaymentsUnauthorizedException` | | 403 | `DodoPaymentsForbiddenException` | | 404 | `DodoPaymentsNotFoundException` | | 422 | `DodoPaymentsUnprocessableEntityException` | | 429 | `DodoPaymentsRateLimitException` | | 5xx | `DodoPayments5xxException` | | others | `DodoPaymentsUnexpectedStatusCodeException` | A 4xx status without its own class, such as 409, throws `DodoPayments4xxException`. `DodoPaymentsUnexpectedStatusCodeException` covers statuses outside the 4xx and 5xx ranges. The SDK also throws these exceptions: * `DodoPaymentsIOException`: An I/O or network error. * `DodoPaymentsInvalidDataException`: The SDK couldn't interpret the response data, for example because a required property is missing. * `DodoPaymentsException`: The base class of every SDK exception. ## Pagination List methods return one page of results. You can iterate over every item or move through the pages yourself. ### Auto-Pagination `Paginate` returns an `IAsyncEnumerable` that fetches the next page when it needs it: ```csharp theme={null} var page = await client.Payments.List(); await foreach (var item in page.Paginate()) { Console.WriteLine(item); } ``` ### Manual Pagination To work with one page at a time, read `Items`, then call `HasNext()` and `Next()`: ```csharp theme={null} var page = await client.Payments.List(); while (true) { foreach (var item in page.Items) { Console.WriteLine(item); } if (!page.HasNext()) { break; } page = await page.Next(); } ``` To set the page size, pass a `PaymentListParams` from the `DodoPayments.Client.Models.Payments` namespace, for example `client.Payments.List(new PaymentListParams { PageSize = 50 })`. ## ASP.NET Core Integration Register one client as a singleton in the dependency injection container, and read the API key from configuration: ```csharp Program.cs theme={null} using DodoPayments.Client; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(sp => { var configuration = sp.GetRequiredService(); return new DodoPaymentsClient { BearerToken = configuration["DodoPayments:ApiKey"] }; }); var app = builder.Build(); app.Run(); ``` Add the key to your configuration, for example in `appsettings.json`: ```json appsettings.json theme={null} { "DodoPayments": { "ApiKey": "dodo_test_..." } } ``` > [!TIP] > > In development, store the key with [user secrets](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets) instead of in `appsettings.json`: > > ```bash theme={null} > dotnet user-secrets init > dotnet user-secrets set "DodoPayments:ApiKey" "dodo_test_..." > ``` ## Resources > [card] [NuGet Package](https://www.nuget.org/packages/DodoPayments.Client) > > Package versions and install commands. > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-csharp) > > Source code, releases, and examples. > [card] [API Reference](/api-reference/introduction) > > Every endpoint, parameter, and response. > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. ## Support For help with the C# SDK: * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-csharp). # Go Source: https://docs.dodopayments.com/developer-resources/sdks/go Use the Dodo Payments Go SDK to create checkout sessions, customers, subscriptions, and usage events, with context support, retries, and middleware. The Go SDK gives Go applications typed access to the Dodo Payments REST API. Every method takes a `context.Context`, request parameters use a `Field` wrapper that separates zero values from omitted fields, and you can add middleware to every request. ## Installation Add the module to your project: ```bash theme={null} go get github.com/dodopayments/dodopayments-go ``` To pin a specific version: ```bash theme={null} go get -u 'github.com/dodopayments/dodopayments-go@v1.120.0' ``` > [!NOTE] > > The SDK requires Go 1.22 or later. ## Quick Start Create a client, then create a checkout session: ```go expandable theme={null} package main import ( "context" "fmt" "os" "github.com/dodopayments/dodopayments-go" "github.com/dodopayments/dodopayments-go/option" ) func main() { client := dodopayments.NewClient( option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), // This is the default and can be omitted option.WithEnvironmentTestMode(), // defaults to option.WithEnvironmentLiveMode() ) checkoutSessionResponse, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{ CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{ ProductID: dodopayments.F("pdt_123"), Quantity: dodopayments.F(int64(1)), }}), }, }) if err != nil { panic(err.Error()) } fmt.Printf("Session ID: %s\n", checkoutSessionResponse.SessionID) } ``` If you omit `option.WithBearerToken`, `NewClient` reads the `DODO_PAYMENTS_API_KEY` environment variable. If you omit `option.WithEnvironmentTestMode()`, the client connects to live mode. A test mode API key works only in test mode. > [!WARNING] > > Keep API keys in environment variables or a secrets manager. Never hardcode them in your source code. ## Core Features > [card] Context Support > > Every method takes a `context.Context` for cancellation and timeouts. > [card] Strong Typing > > Typed request parameters and response structs for compile-time checks. > [card] Middleware > > Add middleware with `option.WithMiddleware` for logging, metrics, and custom logic. > [card] Goroutine Safe > > Share one client across goroutines. ## Configuration `NewClient` reads `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` (your webhook signing secret), and `DODO_PAYMENTS_BASE_URL` from the environment. Options you pass, such as `option.WithBearerToken`, `option.WithWebhookKey`, and `option.WithBaseURL`, override them. To verify a webhook, pass the raw request body and headers to `client.Webhooks.Unwrap(rawBody, r.Header)`. It checks the signature with your webhook key and returns the parsed event. `client.Webhooks.UnsafeUnwrap(rawBody)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks). The examples on this page use the `client` from [Quick Start](#quick-start). ### Context and Timeouts Requests don't time out by default. A context deadline limits the whole call, including retries. To limit each attempt, add `option.WithRequestTimeout()`: ```go expandable theme={null} import ( "context" "log" "time" "github.com/dodopayments/dodopayments-go" "github.com/dodopayments/dodopayments-go/option" ) // Create a context with timeout ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() _, err := client.CheckoutSessions.New(ctx, dodopayments.CheckoutSessionNewParams{ CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{ ProductID: dodopayments.F("pdt_456"), Quantity: dodopayments.F(int64(1)), }}), Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam]( dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F("cus_123")}, ), }, }, option.WithRequestTimeout(5*time.Second)) // Per-attempt timeout if err != nil { if ctx.Err() == context.DeadlineExceeded { log.Println("Request timed out") } else { log.Fatal(err) } } ``` ### Retry Configuration The SDK retries connection errors and responses with status 408, 409, 429, or 500 and above. It retries twice by default, with exponential backoff. Set `option.WithMaxRetries` on the client or on a single request: ```go theme={null} // Configure default for all requests (default is 2) client := dodopayments.NewClient( option.WithMaxRetries(0), // disable retries ) // Override per-request client.CheckoutSessions.New( context.TODO(), dodopayments.CheckoutSessionNewParams{ CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{ ProductID: dodopayments.F("pdt_123"), Quantity: dodopayments.F(int64(1)), }}), }, }, option.WithMaxRetries(5), ) ``` ## Workload Identity The SDK can use workload identity federation instead of an API key. The SDK exchanges an OIDC token from your CI or cloud platform for a short-lived Dodo Payments token. It refreshes the token before the token expires. This feature is available from version v1.124.0. Before you start, create an identity provider and a mapping in the dashboard. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup). This example uses the GitHub Actions helper, `workloadidentity.GitHubActions("")`: ```go theme={null} import ( "github.com/dodopayments/dodopayments-go" "github.com/dodopayments/dodopayments-go/option" "github.com/dodopayments/dodopayments-go/workloadidentity" ) client := dodopayments.NewClient( option.WithEnvironmentLiveMode(), option.WithWorkloadIdentity(option.WorkloadIdentity{ IdentityProviderID: "wip_...", Provider: workloadidentity.GitHubActions(""), }), ) ``` If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the SDK uses workload identity. It finds the platform from the environment. To stop the token before it expires, for example at the end of a CI job, revoke it: ```go theme={null} err := client.WorkloadIdentity.Revoke(ctx) ``` > [!WARNING] > > Do not set an API key and workload identity together. The SDK gives an error when you set the two options. For the other platform helpers and the refresh behavior, refer to [Use Workload Identity with the SDKs](/developer-resources/workload-identity/sdk-usage). ## Common Operations The examples in this section also use a context, for example `ctx := context.Background()`. ### Create a Checkout Session Create a checkout session, then redirect the customer to the returned `CheckoutURL`: ```go theme={null} session, err := client.CheckoutSessions.New(ctx, dodopayments.CheckoutSessionNewParams{ CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{ ProductID: dodopayments.F("pdt_123"), Quantity: dodopayments.F(int64(1)), }}), ReturnURL: dodopayments.F("https://yourdomain.com/return"), }, }) if err != nil { log.Fatal(err) } fmt.Printf("Checkout URL: %s\n", session.CheckoutURL) ``` Each checkout URL works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session). ### Manage Customers Create a customer with an email address and name, then retrieve it by ID. Metadata values use the union types from the `shared` package: ```go theme={null} import "github.com/dodopayments/dodopayments-go/shared" // Create a customer customer, err := client.Customers.New(ctx, dodopayments.CustomerNewParams{ Email: dodopayments.F("customer@example.com"), Name: dodopayments.F("John Doe"), Metadata: dodopayments.F(dodopayments.MetadataParam{ "user_id": shared.UnionString("12345"), }), }) if err != nil { log.Fatal(err) } // Retrieve customer customer, err = client.Customers.Get(ctx, "cus_123") if err != nil { log.Fatal(err) } fmt.Printf("Customer: %s (%s)\n", customer.Name, customer.Email) ``` ### Handle Subscriptions Start a subscription with a checkout session, charge an on-demand subscription, and read a subscription's usage history. ```go expandable theme={null} import "time" // Start a subscription: put a subscription product in ProductCart session, err := client.CheckoutSessions.New(ctx, dodopayments.CheckoutSessionNewParams{ CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{ ProductID: dodopayments.F("pdt_456"), Quantity: dodopayments.F(int64(1)), }}), Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam]( dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F("cus_123")}, ), ReturnURL: dodopayments.F("https://yourdomain.com/return"), }, }) if err != nil { log.Fatal(err) } fmt.Printf("Redirect to: %s\n", session.CheckoutURL) // Charge an on-demand subscription // ProductPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD) chargeResponse, err := client.Subscriptions.Charge(ctx, "sub_123", dodopayments.SubscriptionChargeParams{ ProductPrice: dodopayments.F(int64(2500)), }, ) if err != nil { log.Fatal(err) } fmt.Printf("Payment ID: %s\n", chargeResponse.PaymentID) // Get usage history (for metered subscriptions) usageHistory, err := client.Subscriptions.GetUsageHistory( ctx, "sub_123", dodopayments.SubscriptionGetUsageHistoryParams{ StartDate: dodopayments.F(time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)), EndDate: dodopayments.F(time.Date(2024, 3, 31, 23, 59, 59, 0, time.UTC)), }, ) if err != nil { log.Fatal(err) } fmt.Printf("Usage periods on this page: %d\n", len(usageHistory.Items)) ``` > [!NOTE] > > The subscription starts when the customer completes checkout. Read its `subscription_id` from the `subscription.active` webhook or from the `return_url` query parameters. `Customer` is a `CustomerRequestUnionParam`: pass `AttachExistingCustomerParam{CustomerID: ...}` for an existing customer or `NewCustomerParam{Email: ..., Name: ...}` to create one. `Charge` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions), and `ProductPrice` is in the smallest currency unit. `GetUsageHistory` returns one page of results; `GetUsageHistoryAutoPaging` iterates every page. ## Usage-Based Billing ### Ingest Usage Events Send usage events for a customer: ```go theme={null} import ( "time" "github.com/dodopayments/dodopayments-go" ) response, err := client.UsageEvents.Ingest(ctx, dodopayments.UsageEventIngestParams{ Events: dodopayments.F([]dodopayments.EventInputParam{{ EventID: dodopayments.F("api_call_12345"), CustomerID: dodopayments.F("cus_abc123"), EventName: dodopayments.F("api_request"), Timestamp: dodopayments.F(time.Now()), }}), }) if err != nil { log.Fatal(err) } fmt.Printf("Ingested %d events\n", response.IngestedCount) ``` > [!NOTE] > > The `EventID` is the idempotency key, so give each event a unique value. If the same `EventID` appears twice in one request, the whole request is rejected. If an `EventID` was already ingested, the new event is ignored. A request accepts up to 1,000 events. `Timestamp` defaults to the current time and is rejected if it's more than 1 hour in the past or more than 5 minutes in the future. ### List Usage Events List events filtered by customer and event name: ```go theme={null} // List events with filters params := dodopayments.UsageEventListParams{ CustomerID: dodopayments.F("cus_abc123"), EventName: dodopayments.F("api_request"), } events, err := client.UsageEvents.List(ctx, params) if err != nil { log.Fatal(err) } for _, event := range events.Items { fmt.Printf("Event %s: %s at %s\n", event.EventID, event.EventName, event.Timestamp) } ``` `List` returns one page. To iterate every page, call `client.UsageEvents.ListAutoPaging(ctx, params)` and loop with `iter.Next()`, `iter.Current()`, and `iter.Err()`. Other list methods have the same `AutoPaging` variant, and each page has a `GetNextPage()` method. ## Error Handling When the API returns a non-success status code, the SDK returns an error of type `*dodopayments.Error`. It has the `StatusCode`, the `*http.Request` and `*http.Response`, and the JSON of the error body. Use `errors.As` to inspect it, and branch on `StatusCode` to handle specific cases: ```go expandable theme={null} _, err := client.CheckoutSessions.New(ctx, dodopayments.CheckoutSessionNewParams{ CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{ ProductID: dodopayments.F("pdt_456"), Quantity: dodopayments.F(int64(1)), }}), Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam]( dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F("cus_123")}, ), }, }) if err != nil { var apiErr *dodopayments.Error if errors.As(err, &apiErr) { fmt.Printf("Status Code: %d\n", apiErr.StatusCode) fmt.Println(string(apiErr.DumpResponse(true))) // Serialized HTTP response // Handle specific status codes switch apiErr.StatusCode { case 401: log.Println("Authentication failed") case 422: log.Println("Invalid request parameters") case 429: log.Println("Rate limit exceeded") default: log.Printf("API error: %s", apiErr.Error()) } } else { log.Fatal(err) } } ``` Other errors are returned unwrapped. For example, if the HTTP transport fails, you might receive a `*url.Error` that wraps a `*net.OpError`. `apiErr.DumpRequest(true)` returns the serialized request. ## Middleware Add middleware with `option.WithMiddleware`. A middleware receives each request and a `next` function that sends it: ```go theme={null} func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) { // Before the request start := time.Now() log.Printf("Request: %s %s\n", req.Method, req.URL) // Forward the request to the next handler res, err = next(req) // After the request (res is nil when err is not nil) if err != nil { log.Printf("Request failed after %v: %v\n", time.Since(start), err) return res, err } log.Printf("Response: %d in %v\n", res.StatusCode, time.Since(start)) return res, err } client := dodopayments.NewClient( option.WithMiddleware(Logger), ) ``` Multiple middleware in one `option.WithMiddleware` call run left to right. Middleware passed to `NewClient` runs before middleware passed to a single request. ## Concurrency The client is safe for concurrent use, so you can share one client across goroutines: ```go theme={null} package main import ( "context" "sync" "log" "github.com/dodopayments/dodopayments-go" ) func main() { client := dodopayments.NewClient() var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func(idx int) { defer wg.Done() session, err := client.CheckoutSessions.New(context.Background(), dodopayments.CheckoutSessionNewParams{ CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{{ ProductID: dodopayments.F("pdt_456"), Quantity: dodopayments.F(int64(1)), }}), Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam]( dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F("cus_123")}, ), }, }) if err != nil { log.Printf("Failed to create checkout session %d: %v", idx, err) return } log.Printf("Created checkout session %d: %s", idx, session.SessionID) }(i) } wg.Wait() } ``` ## Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-go) > > Source code, releases, and the full method list. > [card] [API Reference](/api-reference/introduction) > > Every endpoint, parameter, and response. > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. > [card] [Report Issues](https://github.com/dodopayments/dodopayments-go/issues) > > Report bugs or request features. ## Support For help with the Go SDK: * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-go). ## Contributing To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-go/blob/main/CONTRIBUTING.md). # Java Source: https://docs.dodopayments.com/developer-resources/sdks/java Use the Dodo Payments Java SDK to create checkout sessions, customers, subscriptions, meters, and usage events from Java 8+, with sync and async clients. The Java SDK gives Java applications typed access to the Dodo Payments REST API. It uses Java types throughout: `Optional` for fields that can be missing, `Stream` for iterating results, and `CompletableFuture` for asynchronous calls. ## Installation ### Maven Add the dependency to your `pom.xml`: ```xml pom.xml theme={null} com.dodopayments.api dodo-payments-java 1.120.0 ``` ### Gradle Add the dependency to your `build.gradle.kts`: ```kotlin build.gradle.kts theme={null} implementation("com.dodopayments.api:dodo-payments-java:1.120.0") ``` > [!TIP] > > SDK releases add support for API changes. To find the most recent version, check [Maven Central](https://central.sonatype.com/artifact/com.dodopayments.api/dodo-payments-java). > [!NOTE] > > The SDK requires Java 8 or later, so it also runs on Java 11, 17, and 21. ## Quick Start Create a client, then create a checkout session: ```java theme={null} import com.dodopayments.api.client.DodoPaymentsClient; import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient; import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest; import com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse; import com.dodopayments.api.models.checkoutsessions.ProductItemReq; // Configure using environment variables (DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_WEBHOOK_KEY, DODO_PAYMENTS_BASE_URL) // Or system properties (dodopayments.apiKey, dodopayments.webhookKey, dodopayments.baseUrl) DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv(); CheckoutSessionRequest params = CheckoutSessionRequest.builder() .addProductCart(ProductItemReq.builder() .productId("pdt_123") .quantity(1) .build()) .build(); CheckoutSessionResponse checkoutSessionResponse = client.checkoutSessions().create(params); System.out.println(checkoutSessionResponse.sessionId()); ``` `fromEnv()` connects to live mode unless `DODO_PAYMENTS_BASE_URL` or `dodopayments.baseUrl` says otherwise. To use test mode, see [Test Mode](#test-mode). A test mode API key works only in test mode. > [!WARNING] > > Keep API keys in environment variables, system properties, or a secrets manager. Never hardcode them in your source code. ## Core Features > [card] Type Safety > > Typed request and response classes for compile-time checks. > [card] Shared Client > > Create one client and reuse it across requests: it holds the connection and thread pools. Request and response objects are immutable. > [card] Builder Pattern > > Every request class has a builder, and `toBuilder()` makes a modified copy. > [card] Async Support > > `client.async()` returns a client whose methods return `CompletableFuture`. ## Configuration ### Environment Variables `fromEnv()` reads these environment variables, or the matching system properties. System properties take precedence: ```bash .env theme={null} DODO_PAYMENTS_API_KEY=dodo_live_... DODO_PAYMENTS_BASE_URL=https://live.dodopayments.com ``` ```java theme={null} // Automatically reads from environment variables DodoPaymentsClient client = DodoPaymentsOkHttpClient.fromEnv(); ``` The API key comes from `DODO_PAYMENTS_API_KEY` or `dodopayments.apiKey`. The webhook signing secret comes from `DODO_PAYMENTS_WEBHOOK_KEY` or `dodopayments.webhookKey`, and the base URL from `DODO_PAYMENTS_BASE_URL` or `dodopayments.baseUrl`. Create one client and reuse it, because each client has its own connection pool and thread pools. To verify a webhook, pass the raw request body and headers to `client.webhooks().unwrap(UnwrapWebhookParams.builder().body(rawBody).headers(headers).build())`, where `headers` is a `com.dodopayments.api.core.http.Headers`. It checks the signature with your webhook key and returns the parsed event, or throws `DodoPaymentsWebhookException`. Without headers, `unwrap` doesn't verify the signature. `client.webhooks().unsafeUnwrap(rawBody)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks). ### Manual Configuration Set each option on the builder: ```java theme={null} import java.time.Duration; DodoPaymentsClient client = DodoPaymentsOkHttpClient.builder() .bearerToken("dodo_live_...") .baseUrl("https://live.dodopayments.com") .maxRetries(4) .timeout(Duration.ofSeconds(30)) .responseValidation(true) .build(); ``` By default, the client retries twice and times out after 1 minute. It retries connection errors and responses with status 408, 409, 429, or 500 and above. To override the timeout for one call, pass `RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()` as the method's second argument. `responseValidation(true)` checks that the whole response matches the expected types up front. Without it, the SDK throws `DodoPaymentsInvalidDataException` only when you read a property with an unexpected type. ### Test Mode To use test mode (`https://test.dodopayments.com`), call `testMode()` on the builder: ```java theme={null} DodoPaymentsClient testClient = DodoPaymentsOkHttpClient.builder() .fromEnv() .testMode() .build(); ``` ## Workload Identity The SDK can use workload identity federation instead of an API key. The SDK exchanges an OIDC token from your CI or cloud platform for a short-lived Dodo Payments token. It refreshes the token before the token expires. This feature is available from version 1.124.0. Before you start, create an identity provider and a mapping in the dashboard. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup). This example uses the GitHub Actions helper, `SubjectTokenProviders.githubActions()`: ```java theme={null} import com.dodopayments.api.client.DodoPaymentsClient; import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient; import com.dodopayments.api.workloadidentity.SubjectTokenProviders; import com.dodopayments.api.workloadidentity.WorkloadIdentity; DodoPaymentsClient client = DodoPaymentsOkHttpClient.builder() .workloadIdentity(WorkloadIdentity.builder() .identityProviderId("wip_...") .provider(SubjectTokenProviders.githubActions()) .build()) .build(); ``` If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the SDK uses workload identity. It finds the platform from the environment. To stop the token before it expires, for example at the end of a CI job, revoke it: ```java theme={null} client.workloadIdentity().revoke(); ``` > [!WARNING] > > Do not set an API key and workload identity together. The SDK gives an error when you set the two options. For the other platform helpers and the refresh behavior, refer to [Use Workload Identity with the SDKs](/developer-resources/workload-identity/sdk-usage). ## Common Operations The examples in this section use the `client` from [Quick Start](#quick-start). ### Create a Checkout Session Create a checkout session, then redirect the customer to the returned checkout URL: ```java theme={null} CheckoutSessionRequest params = CheckoutSessionRequest.builder() .addProductCart(ProductItemReq.builder() .productId("pdt_123") .quantity(1) .build()) .returnUrl("https://yourdomain.com/return") .build(); CheckoutSessionResponse session = client.checkoutSessions().create(params); System.out.println("Checkout URL: " + session.checkoutUrl().orElse("")); ``` `checkoutUrl()` returns an `Optional`. Each checkout URL works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session). ### Manage Customers Create a customer with an email address, name, and metadata, then retrieve it by ID: ```java theme={null} import com.dodopayments.api.core.JsonValue; import com.dodopayments.api.models.customers.Customer; import com.dodopayments.api.models.customers.CustomerCreateParams; import com.dodopayments.api.models.misc.Metadata; // Create a customer CustomerCreateParams createParams = CustomerCreateParams.builder() .email("customer@example.com") .name("John Doe") .metadata(Metadata.builder() .putAdditionalProperty("user_id", JsonValue.from("12345")) .build()) .build(); Customer customer = client.customers().create(createParams); // Retrieve customer Customer retrieved = client.customers().retrieve("cus_123"); System.out.println("Customer: " + retrieved.name() + " (" + retrieved.email() + ")"); ``` ### Handle Subscriptions Start a subscription with a checkout session, then charge it if it's an on-demand subscription. ```java theme={null} import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest; import com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse; import com.dodopayments.api.models.checkoutsessions.ProductItemReq; import com.dodopayments.api.models.payments.AttachExistingCustomer; import com.dodopayments.api.models.subscriptions.SubscriptionChargeParams; import com.dodopayments.api.models.subscriptions.SubscriptionChargeResponse; // Start a subscription: put a subscription product in the product cart CheckoutSessionRequest sessionParams = CheckoutSessionRequest.builder() .addProductCart(ProductItemReq.builder() .productId("pdt_456") .quantity(1) .build()) .customer(AttachExistingCustomer.builder() .customerId("cus_123") .build()) .returnUrl("https://yourdomain.com/return") .build(); CheckoutSessionResponse session = client.checkoutSessions().create(sessionParams); System.out.println("Checkout URL: " + session.checkoutUrl().orElse("")); // Charge an on-demand subscription // product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD) SubscriptionChargeParams chargeParams = SubscriptionChargeParams.builder() .subscriptionId("sub_123") .productPrice(2500) .build(); SubscriptionChargeResponse chargeResponse = client.subscriptions().charge(chargeParams); System.out.println("Payment ID: " + chargeResponse.paymentId()); ``` > [!NOTE] > > The subscription starts when the customer completes checkout. Read its `subscription_id` from the `subscription.active` webhook or from the `return_url` query parameters. `productPrice` is in the smallest currency unit, such as cents for USD or paise for INR. To charge \$25.00, pass `2500`. > [!TIP] > > `subscriptions().charge(...)` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions). Dodo Payments bills other subscriptions automatically on the product's billing schedule. ## Usage-Based Billing ### Configure Meters Create a meter that counts events, then list your meters. `autoPager()` iterates over every meter and fetches more pages as needed: ```java theme={null} import com.dodopayments.api.models.meters.*; // Create API calls meter MeterCreateParams apiMeterParams = MeterCreateParams.builder() .name("API Requests") .eventName("api_request") .aggregation(MeterAggregation.builder() .type(MeterAggregation.Type.COUNT) .build()) .measurementUnit("calls") .build(); Meter apiMeter = client.meters().create(apiMeterParams); System.out.println("Meter created: " + apiMeter.id()); // List all meters client.meters().list() .autoPager() .forEach(m -> System.out.println("Meter: " + m.name() + " - " + m.aggregation())); ``` ### Ingest Usage Events Send a usage event for a customer. Event metadata values are `JsonValue` objects: ```java theme={null} import com.dodopayments.api.core.JsonValue; import com.dodopayments.api.models.usageevents.EventInput; import com.dodopayments.api.models.usageevents.*; import java.time.OffsetDateTime; // Ingest single event UsageEventIngestParams singleEventParams = UsageEventIngestParams.builder() .addEvent(EventInput.builder() .eventId("api_call_" + System.currentTimeMillis()) .customerId("cus_abc123") .eventName("api_request") .timestamp(OffsetDateTime.now()) .metadata(EventInput.Metadata.builder() .putAdditionalProperty("endpoint", JsonValue.from("/api/v1/users")) .putAdditionalProperty("method", JsonValue.from("GET")) .putAdditionalProperty("tokens_used", JsonValue.from("150")) .build()) .build()) .build(); UsageEventIngestResponse response = client.usageEvents().ingest(singleEventParams); System.out.println("Processed: " + response.ingestedCount()); ``` The `eventId` is the idempotency key, so give each event a unique value. A `timestamp` more than 1 hour in the past or more than 5 minutes in the future is rejected. ### Batch Ingest Events Send up to 1,000 events in one request. This example uses the imports from the previous one: ```java theme={null} UsageEventIngestParams.Builder batchBuilder = UsageEventIngestParams.builder(); for (int i = 0; i < 100; i++) { batchBuilder.addEvent(EventInput.builder() .eventId("batch_event_" + i + "_" + System.currentTimeMillis()) .customerId("cus_abc123") .eventName("video_transcode") .timestamp(OffsetDateTime.now().minusSeconds(i)) .metadata(EventInput.Metadata.builder() .putAdditionalProperty("video_id", JsonValue.from("video_" + i)) .putAdditionalProperty("duration_seconds", JsonValue.from(String.valueOf(120 + i))) .build()) .build()); } UsageEventIngestResponse batchResponse = client.usageEvents().ingest(batchBuilder.build()); System.out.println("Batch processed: " + batchResponse.ingestedCount() + " events"); ``` ## Error Handling The SDK throws unchecked exceptions. For an error status, it throws a subclass of `DodoPaymentsServiceException`, which has `statusCode()`, `headers()`, and `body()`. Catch the specific classes you want to handle before the base class: ```java theme={null} import com.dodopayments.api.errors.*; import com.dodopayments.api.models.payments.Payment; try { Payment payment = client.payments().retrieve("pay_invalid"); } catch (NotFoundException e) { System.err.println("Payment not found: " + e.getMessage()); } catch (UnauthorizedException e) { System.err.println("Authentication failed: " + e.getMessage()); } catch (PermissionDeniedException e) { System.err.println("Permission denied: " + e.getMessage()); } catch (BadRequestException e) { System.err.println("Invalid request: " + e.getMessage()); } catch (UnprocessableEntityException e) { System.err.println("Validation error: " + e.getMessage()); } catch (RateLimitException e) { System.err.println("Rate limit exceeded: " + e.getMessage()); // Thrown after the SDK's automatic retries are used up } catch (InternalServerException e) { System.err.println("Server error: " + e.getMessage()); } catch (DodoPaymentsServiceException e) { System.err.println("API error: " + e.statusCode() + " - " + e.getMessage()); } ``` Statuses without their own class, such as 409, throw `UnexpectedStatusCodeException`. Network failures throw `DodoPaymentsIoException`, and responses the SDK can't interpret throw `DodoPaymentsInvalidDataException`. All of these extend `DodoPaymentsException`. > [!TIP] > > The SDK retries connection errors and responses with status 408, 409, 429, or 500 and above, twice by default, with exponential backoff. ## Async Operations Call `async()` on the client to get an asynchronous client. Its methods return a `CompletableFuture`: ```java theme={null} import java.util.concurrent.CompletableFuture; CompletableFuture future = client.async() .checkoutSessions() .create(params); // Handle response asynchronously future.thenAccept(response -> { System.out.println("Session created: " + response.sessionId()); }).exceptionally(ex -> { System.err.println("Error: " + ex.getMessage()); return null; }); ``` To create an asynchronous client from the start, use `DodoPaymentsOkHttpClientAsync.fromEnv()`. ## Spring Boot Integration ### Configuration Class Register one client as a bean, and choose the environment from a property: ```java theme={null} import com.dodopayments.api.client.DodoPaymentsClient; import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class DodoPaymentsConfig { @Value("${dodo.api.key}") private String apiKey; @Value("${dodo.environment:test}") private String environment; @Bean public DodoPaymentsClient dodoPayments() { return DodoPaymentsOkHttpClient.builder() .bearerToken(apiKey) .baseUrl(environment.equals("live") ? "https://live.dodopayments.com" : "https://test.dodopayments.com") .build(); } } ``` ### Service Layer Inject the client into a service: ```java theme={null} import com.dodopayments.api.client.DodoPaymentsClient; import com.dodopayments.api.models.checkoutsessions.*; import java.util.List; import org.springframework.stereotype.Service; @Service public class PaymentService { private final DodoPaymentsClient client; public PaymentService(DodoPaymentsClient client) { this.client = client; } public CheckoutSessionResponse createCheckout(List items) { CheckoutSessionRequest params = CheckoutSessionRequest.builder() .productCart(items) .returnUrl("https://yourdomain.com/return") .build(); return client.checkoutSessions().create(params); } } ``` ## Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-java) > > Source code, releases, and the full method list. > [card] [API Reference](/api-reference/introduction) > > Every endpoint, parameter, and response. > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. > [card] [Report Issues](https://github.com/dodopayments/dodopayments-java/issues) > > Report bugs or request features. ## Support For help with the Java SDK: * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-java). ## Contributing To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-java/blob/main/CONTRIBUTING.md). # Kotlin Source: https://docs.dodopayments.com/developer-resources/sdks/kotlin Use the Dodo Payments Kotlin SDK to create checkout sessions, products, subscriptions, and usage events from Kotlin, with nullable types and coroutines. The Kotlin SDK gives Kotlin applications typed access to the Dodo Payments REST API. It uses Kotlin types throughout: nullable values for fields that can be missing, `Sequence` for iterating results, and `suspend` functions for asynchronous calls. ## Installation ### Gradle (Kotlin DSL) Add the dependency to your `build.gradle.kts`: ```kotlin build.gradle.kts theme={null} implementation("com.dodopayments.api:dodo-payments-kotlin:1.120.0") ``` ### Maven Add the dependency to your `pom.xml`: ```xml pom.xml theme={null} com.dodopayments.api dodo-payments-kotlin 1.120.0 ``` > [!TIP] > > SDK releases add support for API changes. To find the most recent version, check [Maven Central](https://central.sonatype.com/artifact/com.dodopayments.api/dodo-payments-kotlin). > [!NOTE] > > The SDK requires Java 8 or later. It runs on the JVM and on Android, and it ships ProGuard and R8 keep rules. ## Quick Start Create a client, then create a checkout session: ```kotlin theme={null} import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest import com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse import com.dodopayments.api.models.checkoutsessions.ProductItemReq // Configure using environment variables (DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_WEBHOOK_KEY, DODO_PAYMENTS_BASE_URL) // Or system properties (dodopayments.apiKey, dodopayments.webhookKey, dodopayments.baseUrl) val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv() val params: CheckoutSessionRequest = CheckoutSessionRequest.builder() .addProductCart(ProductItemReq.builder() .productId("pdt_123") .quantity(1) .build()) .build() val checkoutSessionResponse: CheckoutSessionResponse = client.checkoutSessions().create(params) println(checkoutSessionResponse.sessionId()) ``` `fromEnv()` connects to live mode unless `DODO_PAYMENTS_BASE_URL` or `dodopayments.baseUrl` says otherwise. To use test mode, see [Test Mode](#test-mode). A test mode API key works only in test mode. > [!WARNING] > > Keep API keys in environment variables or a secrets manager. Never commit them to version control. ## Core Features > [card] Coroutines > > The async client's methods are `suspend` functions that you call from a coroutine. > [card] Null Safety > > Fields that can be missing are nullable types, not `Optional`. > [card] Sequences > > On the synchronous client, `autoPager()` returns a `Sequence` that fetches more pages as you iterate. On the async client, it returns a `Flow`. > [card] Immutable Models > > Model classes are immutable, and `toBuilder()` returns a builder for a modified copy. ## Configuration ### From Environment Variables `fromEnv()` reads your settings from environment variables or system properties. System properties take precedence: ```kotlin theme={null} val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.fromEnv() ``` The API key comes from `DODO_PAYMENTS_API_KEY` or `dodopayments.apiKey`. The webhook signing secret comes from `DODO_PAYMENTS_WEBHOOK_KEY` or `dodopayments.webhookKey`, and the base URL from `DODO_PAYMENTS_BASE_URL` or `dodopayments.baseUrl`. Create one client and reuse it, because each client has its own connection pool and thread pools. To verify a webhook, pass the raw request body and headers to `client.webhooks().unwrap(UnwrapWebhookParams.builder().body(rawBody).headers(headers).build())`, where `headers` is a `com.dodopayments.api.core.http.Headers`. It checks the signature with your webhook key and returns the parsed event, or throws `DodoPaymentsWebhookException`. Without headers, `unwrap` doesn't verify the signature. `client.webhooks().unsafeUnwrap(rawBody)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks). ### Manual Configuration Set each option on the builder: ```kotlin theme={null} import java.time.Duration val client = DodoPaymentsOkHttpClient.builder() .bearerToken("dodo_live_...") .baseUrl("https://live.dodopayments.com") .maxRetries(3) .timeout(Duration.ofSeconds(30)) .build() ``` ### Test Mode To use test mode (`https://test.dodopayments.com`), call `testMode()` on the builder: ```kotlin theme={null} val testClient = DodoPaymentsOkHttpClient.builder() .fromEnv() .testMode() .build() ``` ### Timeouts and Retries By default, the client retries twice and times out after 1 minute. It retries connection errors and responses with status 408, 409, 429, or 500 and above, with exponential backoff. Set the defaults on the client, or pass `RequestOptions` to a single call: ```kotlin theme={null} import com.dodopayments.api.core.RequestOptions import java.time.Duration // Global configuration val client = DodoPaymentsOkHttpClient.builder() .fromEnv() .timeout(Duration.ofSeconds(45)) .maxRetries(3) .build() // Per-request timeout override val product = client.products().retrieve( "pdt_123", RequestOptions.builder() .timeout(Duration.ofSeconds(10)) .build() ) ``` ## Workload Identity The SDK can use workload identity federation instead of an API key. The SDK exchanges an OIDC token from your CI or cloud platform for a short-lived Dodo Payments token. It refreshes the token before the token expires. This feature is available from version 1.124.0. Before you start, create an identity provider and a mapping in the dashboard. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup). This example uses the GitHub Actions helper, `SubjectTokenProviders.githubActions()`: ```kotlin theme={null} import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient import com.dodopayments.api.workloadidentity.SubjectTokenProviders import com.dodopayments.api.workloadidentity.WorkloadIdentity val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder() .workloadIdentity( WorkloadIdentity.builder() .identityProviderId("wip_...") .provider(SubjectTokenProviders.githubActions()) .build() ) .build() ``` If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the SDK uses workload identity. It finds the platform from the environment. To stop the token before it expires, for example at the end of a CI job, revoke it: ```kotlin theme={null} client.workloadIdentity()?.revoke() ``` > [!WARNING] > > Do not set an API key and workload identity together. The SDK gives an error when you set the two options. For the other platform helpers and the refresh behavior, refer to [Use Workload Identity with the SDKs](/developer-resources/workload-identity/sdk-usage). ## Common Operations The examples in this section use the `client` from [Quick Start](#quick-start). ### Create a Checkout Session Create a checkout session, then redirect the customer to the returned checkout URL: ```kotlin theme={null} val params = CheckoutSessionRequest.builder() .addProductCart(ProductItemReq.builder() .productId("pdt_123") .quantity(1) .build()) .returnUrl("https://yourdomain.com/return") .build() val session = client.checkoutSessions().create(params) println("Checkout URL: ${session.checkoutUrl()}") ``` `checkoutUrl()` returns a nullable `String?`. Each checkout URL works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session). ### Create a Product Create a monthly subscription product priced at \$29.99: ```kotlin theme={null} import com.dodopayments.api.models.products.Price import com.dodopayments.api.models.products.Product import com.dodopayments.api.models.products.ProductCreateParams import com.dodopayments.api.models.misc.Currency import com.dodopayments.api.models.misc.TaxCategory import com.dodopayments.api.models.subscriptions.TimeInterval val createParams = ProductCreateParams.builder() .name("Premium Subscription") .description("Monthly subscription with all features") .price( Price.RecurringPrice.builder() .currency(Currency.USD) .price(2999) // $29.99 in cents .discountBps(0) .purchasingPowerParity(false) .paymentFrequencyCount(1) .paymentFrequencyInterval(TimeInterval.MONTH) .subscriptionPeriodCount(1) .subscriptionPeriodInterval(TimeInterval.MONTH) .build() ) .taxCategory(TaxCategory.DIGITAL_PRODUCTS) .build() val product: Product = client.products().create(createParams) println("Created product ID: ${product.productId()}") ``` `price` is in the smallest currency unit. `discountBps` sets the discount in basis points and replaces the deprecated `discount` field. ### Activate License Key Activate a license key for a device or installation. If the key has reached its activation limit, the API returns `422` and the SDK throws `UnprocessableEntityException`. An inactive key returns `403` (`PermissionDeniedException`), and an unknown key returns `404` (`NotFoundException`): ```kotlin theme={null} import com.dodopayments.api.errors.UnprocessableEntityException import com.dodopayments.api.models.licenses.LicenseActivateParams import com.dodopayments.api.models.licenses.LicenseActivateResponse val activateParams = LicenseActivateParams.builder() .licenseKey("XXXX-XXXX-XXXX-XXXX") .name("user-laptop-01") .build() try { val activationResult: LicenseActivateResponse = client.licenses() .activate(activateParams) println("License activated successfully") println("Instance ID: ${activationResult.id()}") println("License key ID: ${activationResult.licenseKeyId()}") } catch (e: UnprocessableEntityException) { println("License activation failed: ${e.message}") } ``` ### Handle Subscriptions Start a subscription with a checkout session, then charge it if it's an on-demand subscription. ```kotlin theme={null} import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest import com.dodopayments.api.models.checkoutsessions.ProductItemReq import com.dodopayments.api.models.payments.AttachExistingCustomer import com.dodopayments.api.models.subscriptions.SubscriptionChargeParams // Start a subscription: put a subscription product in the product cart val sessionParams = CheckoutSessionRequest.builder() .addProductCart(ProductItemReq.builder() .productId("pdt_456") .quantity(1) .build()) .customer(AttachExistingCustomer.builder() .customerId("cus_123") .build()) .returnUrl("https://yourdomain.com/return") .build() val session = client.checkoutSessions().create(sessionParams) println("Checkout URL: ${session.checkoutUrl()}") // Charge an on-demand subscription // productPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD) val chargeParams = SubscriptionChargeParams.builder() .subscriptionId("sub_123") .productPrice(2500) .build() val chargeResponse = client.subscriptions().charge(chargeParams) println("Payment ID: ${chargeResponse.paymentId()}") ``` > [!NOTE] > > The subscription starts when the customer completes checkout. Read its `subscription_id` from the `subscription.active` webhook or from the `return_url` query parameters. Use `AttachExistingCustomer` to attach an existing customer, or `NewCustomer` to create one. `charge` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions), and `productPrice` is in the smallest currency unit. ## Usage-Based Billing ### Record Usage Events Send a usage event for a customer. Meters that track the event's `eventName` aggregate it: ```kotlin theme={null} import com.dodopayments.api.models.usageevents.EventInput import com.dodopayments.api.models.usageevents.UsageEventIngestParams val usageParams = UsageEventIngestParams.builder() .addEvent(EventInput.builder() .customerId("cus_456") .eventId("event_123") .eventName("api_call") .build()) .build() client.usageEvents().ingest(usageParams) println("Usage event recorded") ``` The `eventId` is the idempotency key, so give each event a unique value. A request accepts up to 1,000 events. ## Async Operations ### Async Client The async client has the same methods as the synchronous client, but most of them are `suspend` functions. Call them from a coroutine: ```kotlin theme={null} import com.dodopayments.api.client.DodoPaymentsClientAsync import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClientAsync import kotlinx.coroutines.runBlocking val asyncClient: DodoPaymentsClientAsync = DodoPaymentsOkHttpClientAsync.fromEnv() runBlocking { val customer = asyncClient.customers().retrieve("cus_123") println("Customer email: ${customer.email()}") } ``` You can also call `client.async()` on a synchronous client to get its async version. ## Error Handling For an error status, the SDK throws a subclass of `DodoPaymentsServiceException`, which has `statusCode()`, `headers()`, and `body()`. The subclasses are `BadRequestException` (400), `UnauthorizedException` (401), `PermissionDeniedException` (403), `NotFoundException` (404), `UnprocessableEntityException` (422), `RateLimitException` (429), `InternalServerException` (5xx), and `UnexpectedStatusCodeException` for other statuses, such as 409: ```kotlin theme={null} import com.dodopayments.api.errors.* try { // params is a CheckoutSessionRequest, as in Create a Checkout Session. val session = client.checkoutSessions().create(params) println("Success: ${session.sessionId()}") } catch (e: UnauthorizedException) { println("Authentication failed: ${e.message}") } catch (e: BadRequestException) { println("Invalid request: ${e.message}") println("Response body: ${e.body()}") } catch (e: RateLimitException) { println("Rate limit exceeded, retry after: ${e.headers().values("retry-after")}") } catch (e: DodoPaymentsServiceException) { println("API error: ${e.statusCode()} - ${e.message}") } ``` Network failures throw `DodoPaymentsIoException`, and responses the SDK can't interpret throw `DodoPaymentsInvalidDataException`. All SDK exceptions extend `DodoPaymentsException`. ### Functional Error Handling Use `Result` for functional error handling: ```kotlin theme={null} import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest import com.dodopayments.api.models.checkoutsessions.CheckoutSessionResponse fun safeCreateCheckout( client: DodoPaymentsClient, params: CheckoutSessionRequest, ): Result = runCatching { client.checkoutSessions().create(params) } // Usage safeCreateCheckout(client, params) .onSuccess { session -> println("Created: ${session.sessionId()}") } .onFailure { error -> println("Error: ${error.message}") } ``` > [!TIP] > > `runCatching` catches every exception, including SDK exceptions, and returns them as a failed `Result`. ## Android Integration The Kotlin SDK is a server SDK. It authenticates with your secret API key, and anyone who has your APK can extract a key compiled into it, so never use it inside an Android app. To take payments in an Android app: 1. On your server, create the checkout session with this SDK (see [Ktor Integration](#ktor-integration)) and return its `checkout_url`. 2. In the app, fetch that `checkout_url` from your server and open it with the [Android SDK](/developer-resources/sdks/android), which holds no API key. ```kotlin theme={null} import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch class PaymentViewModel(private val api: YourBackendApi) : ViewModel() { fun createCheckout(productId: String) { viewModelScope.launch { // Your backend creates the session with the Kotlin SDK and returns checkout_url. // YourBackendApi and openCheckout are your app's own code; openCheckout // passes the URL to DodoCheckout from the Android SDK. val checkoutUrl = api.createCheckoutSession(productId).checkoutUrl openCheckout(checkoutUrl) } } } ``` ## Response Validation By default, the SDK throws `DodoPaymentsInvalidDataException` only when you read a property with an unexpected type. To check the whole response up front, enable validation for a request, or call `validate()` on a response: ```kotlin theme={null} import com.dodopayments.api.core.RequestOptions // Per-request validation val product = client.products().retrieve( "pdt_123", RequestOptions.builder() .responseValidation(true) .build() ) // Or validate explicitly val validatedProduct = product.validate() ``` ## Advanced Features ### Proxy Configuration To send requests through a proxy, pass a `java.net.Proxy` to the builder: ```kotlin theme={null} import java.net.InetSocketAddress import java.net.Proxy val client = DodoPaymentsOkHttpClient.builder() .fromEnv() .proxy( Proxy( Proxy.Type.HTTP, InetSocketAddress("proxy.example.com", 8080) ) ) .build() ``` ### Temporary Configuration `withOptions` returns a client with modified settings that shares the original client's connection and thread pools. The original client doesn't change: ```kotlin theme={null} val customClient = client.withOptions { it.baseUrl("https://example.com") it.maxRetries(5) } ``` ## Ktor Integration Create the client once and call it from a route: ```kotlin theme={null} import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient import com.dodopayments.api.errors.DodoPaymentsServiceException import com.dodopayments.api.models.checkoutsessions.CheckoutSessionRequest import com.dodopayments.api.models.checkoutsessions.ProductItemReq import io.ktor.http.HttpStatusCode import io.ktor.server.application.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.configureRouting() { val client = DodoPaymentsOkHttpClient.builder() .bearerToken(environment.config.property("dodo.apiKey").getString()) .build() routing { post("/create-checkout") { try { // CheckoutRequest is your own @Serializable request class with a productId field val request = call.receive() val params = CheckoutSessionRequest.builder() .addProductCart(ProductItemReq.builder().productId(request.productId).quantity(1).build()) .build() val session = client.checkoutSessions().create(params) call.respond(mapOf("checkout_url" to session.checkoutUrl())) } catch (e: DodoPaymentsServiceException) { call.respond(HttpStatusCode.BadRequest, mapOf("error" to e.message)) } } } } ``` ## Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-kotlin) > > Source code, releases, and the full method list. > [card] [API Reference](/api-reference/introduction) > > Every endpoint, parameter, and response. > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. > [card] [Report Issues](https://github.com/dodopayments/dodopayments-kotlin/issues) > > Report bugs or request features. ## Support For help with the Kotlin SDK: * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-kotlin). ## Contributing To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-kotlin/blob/main/CONTRIBUTING.md). # PHP Source: https://docs.dodopayments.com/developer-resources/sdks/php Use the Dodo Payments PHP SDK to create checkout sessions, customers, and subscriptions from PHP 8.1+, with typed value objects, retries, and pagination. The PHP SDK gives PHP 8.1+ applications access to the Dodo Payments REST API. Methods take named parameters, responses are typed objects, and Composer loads the SDK with PSR-4 autoloading. ## Installation Install the SDK with Composer: ```bash theme={null} composer require "dodopayments/client 6.29.0" ``` > [!NOTE] > > The SDK requires PHP 8.1.0 or later and Composer. It sends requests through a PSR-18 HTTP client in your project, such as Guzzle, which it finds with `php-http/discovery`. ## Quick Start Create a client, then create a checkout session: ```php theme={null} checkoutSessions->create( productCart: [["productID" => "pdt_123", "quantity" => 1]] ); var_dump($checkoutSessionResponse->sessionID); ``` If you omit `bearerToken`, the client reads the `DODO_PAYMENTS_API_KEY` environment variable. If you omit `baseUrl`, the client reads `DODO_PAYMENTS_BASE_URL`, and connects to live mode (`https://live.dodopayments.com`) when that isn't set either. A test mode API key works only with the test mode URL, `https://test.dodopayments.com`. > [!WARNING] > > Keep API keys in environment variables or a secrets manager. Never expose them in > your codebase or commit them to version control. ## Core Features > [card] PSR-4 Compliant > > Composer loads the `Dodopayments` namespace with PSR-4 autoloading. > [card] Modern PHP > > Built for PHP 8.1 or later, with typed parameters and strict types. > [card] Extensive Testing > > The SDK repository includes a test suite for the API services. > [card] Exception Handling > > An exception class for each HTTP error status, plus timeout and connection exceptions. ## Value Objects Methods take named parameters, and parameters that have a default value must be passed by name. To build a value object, use its static `with` constructor with named parameters: ```php theme={null} withCustomerID("cus_123"); ``` Methods also accept plain arrays with the same camelCase keys, such as `["productID" => "pdt_123", "quantity" => 1]`. Response properties use camelCase names too, for example `$session->checkoutURL`. ## Configuration The `Client` constructor takes `bearerToken`, `webhookKey`, `environment` (for example, `'test_mode'`), `baseUrl`, and `requestOptions`. When you omit them, it reads `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` (your webhook signing secret), and `DODO_PAYMENTS_BASE_URL` from the environment. To verify a webhook, pass the raw request body and headers to `$client->webhooks->unwrap($body, headers: $headers)`. It checks the signature with your webhook key, returns the parsed event, and throws `WebhookException` if the check fails. If you omit `headers`, `unwrap` doesn't verify the signature. `$client->webhooks->unsafeUnwrap($body)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks). ### Retry Configuration The SDK retries some errors twice by default, with a short exponential backoff. These errors trigger a retry: * Connection errors (network connectivity problems) * 408 Request Timeout * 409 Conflict * 429 Rate Limit * 500+ Internal errors * Timeouts Set `maxRetries` in `requestOptions`, on the client or on a single request: ```php theme={null} 0]); // Or, configure per-request $result = $client->checkoutSessions->create( productCart: [["productID" => "pdt_123", "quantity" => 1]], requestOptions: ['maxRetries' => 5], ); ``` Requests time out after 60 seconds by default. To change the limit, set `timeout`, in seconds, in the same `requestOptions` array. ## Workload Identity The SDK can use workload identity federation instead of an API key. The SDK exchanges an OIDC token from your CI or cloud platform for a short-lived Dodo Payments token. It refreshes the token before the token expires. This feature is available from version 6.33.0. Before you start, create an identity provider and a mapping in the dashboard. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup). This example uses the GitHub Actions helper, `Providers::githubActions()`: ```php theme={null} use Dodopayments\Client; use Dodopayments\WorkloadIdentity\Providers; use Dodopayments\WorkloadIdentity\WorkloadIdentity; $client = new Client( workloadIdentity: new WorkloadIdentity( provider: Providers::githubActions(), identityProviderId: 'wip_...', ), ); ``` If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the SDK uses workload identity. It finds the platform from the environment. To stop the token before it expires, for example at the end of a CI job, revoke it: ```php theme={null} $client->workloadIdentity?->revoke(); ``` > [!WARNING] > > Do not set an API key and workload identity together. The SDK gives an error when you set the two options. For the other platform helpers and the refresh behavior, refer to [Use Workload Identity with the SDKs](/developer-resources/workload-identity/sdk-usage). ## Common Operations The examples in this section use the `$client` from [Quick Start](#quick-start). ### Create a Checkout Session Create a checkout session, then redirect the customer to the returned `checkoutURL`: ```php theme={null} $session = $client->checkoutSessions->create( productCart: [ ["productID" => "pdt_123", "quantity" => 1] ], returnURL: "https://yourdomain.com/return" ); header('Location: ' . $session->checkoutURL); ``` Each checkout URL works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session). ### Manage Customers Create a customer with an email address and name, then retrieve it by ID: ```php theme={null} // Create a customer $customer = $client->customers->create( email: "customer@example.com", name: "John Doe", metadata: [ "user_id" => "12345" ] ); // Retrieve customer $customer = $client->customers->retrieve("cus_123"); echo "Customer: {$customer->name} ({$customer->email})"; ``` ### Handle Subscriptions Start a subscription with a checkout session, then charge it if it's an on-demand subscription. ```php theme={null} use Dodopayments\Payments\AttachExistingCustomer; // Start a subscription: put a subscription product in productCart $session = $client->checkoutSessions->create( productCart: [["productID" => "pdt_456", "quantity" => 1]], customer: AttachExistingCustomer::with(customerID: 'cus_123'), returnURL: "https://yourdomain.com/return", ); header('Location: ' . $session->checkoutURL); // Charge an on-demand subscription // productPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD) $charge = $client->subscriptions->charge( 'sub_123', productPrice: 2500, ); ``` > [!NOTE] > > The subscription starts when the customer completes checkout. Read its `subscription_id` from the `subscription.active` webhook or from the `return_url` query parameters. Pass `AttachExistingCustomer::with(customerID: '...')` to attach an existing customer, or `NewCustomer::with(email: '...', name: '...')` to create one. Both classes are in the `Dodopayments\Payments` namespace. `charge` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions), and `productPrice` is in the smallest currency unit. ## Pagination List methods return a page object. `getItems()` returns the items on the current page, and `pagingEachItem()` returns every item from the current page onward, requesting more pages as needed: ```php theme={null} $page = $client->payments->list(); var_dump($page); // Fetch items from the current page foreach ($page->getItems() as $item) { var_dump($item->brandID); } // Auto-paginate: fetch items from all pages foreach ($page->pagingEachItem() as $item) { var_dump($item->brandID); } ``` To move one page at a time, call `hasNextPage()` and `getNextPage()`. ## Error Handling When the SDK can't connect to the API, or the API returns a 4xx or 5xx status, the SDK throws a subclass of `Dodopayments\Core\Exceptions\APIException`: ```php theme={null} checkoutSessions->create( productCart: [["productID" => "pdt_123", "quantity" => 1]] ); } catch (APIConnectionException $e) { echo "The server could not be reached", PHP_EOL; var_dump($e->getPrevious()); } catch (RateLimitException $_) { echo "A 429 status code was received; we should back off a bit.", PHP_EOL; } catch (APIStatusException $e) { echo "Another non-200-range status code was received", PHP_EOL; echo $e->getMessage(); } ``` ### Error Types The exception class depends on the cause. All classes are in the `Dodopayments\Core\Exceptions` namespace: | Cause | Error Type | | - | - | | HTTP 400 | `BadRequestException` | | HTTP 401 | `AuthenticationException` | | HTTP 403 | `PermissionDeniedException` | | HTTP 404 | `NotFoundException` | | HTTP 409 | `ConflictException` | | HTTP 422 | `UnprocessableEntityException` | | HTTP 429 | `RateLimitException` | | HTTP >= 500 | `InternalServerException` | | Other HTTP error | `APIStatusException` | | Timeout | `APITimeoutException` | | Network error | `APIConnectionException` | > [!TIP] > > Catch these exceptions around API calls so that your application can show a clear > message or try again later. For a retryable error, the SDK throws only after its > automatic retries fail. ## Advanced Usage ### Undocumented Endpoints To call an endpoint that has no SDK method, use `$client->request`. It applies the same authentication and retries as the SDK methods: ```php theme={null} request( method: "post", path: '/undocumented/endpoint', query: ['dog' => 'woof'], headers: ['useful-header' => 'interesting-value'], body: ['hello' => 'world'] ); ``` ### Undocumented Parameters To send parameters that the SDK doesn't define, pass them in `requestOptions`: ```php theme={null} checkoutSessions->create( productCart: [["productID" => "pdt_123", "quantity" => 1]], requestOptions: [ 'extraQueryParams' => ["my_query_parameter" => "value"], 'extraBodyParams' => ["my_body_parameter" => "value"], 'extraHeaders' => ["my-header" => "value"], ], ); ``` > [!NOTE] > > An `extra*` parameter that has the same name as a documented parameter overrides it. ## Framework Integration ### Laravel Wrap the client in a service class. This example sets the API URL from the configured environment: ```php theme={null} client = new Client( bearerToken: config('services.dodo.api_key'), baseUrl: config('services.dodo.environment') === 'live_mode' ? 'https://live.dodopayments.com' : 'https://test.dodopayments.com', ); } public function createCheckout(array $items) { return $this->client->checkoutSessions->create( productCart: $items, returnURL: route('checkout.return') ); } } ``` Add the settings to `config/services.php`: ```php theme={null} 'dodo' => [ 'api_key' => env('DODO_PAYMENTS_API_KEY'), 'environment' => env('DODO_PAYMENTS_ENVIRONMENT', 'test_mode') ], ``` ### Symfony Create a service that receives the API key through its constructor: ```php theme={null} client = new Client(bearerToken: $apiKey); } public function createCheckout(string $productId, string $customerId, string $returnUrl): object { return $this->client->checkoutSessions->create( productCart: [['productID' => $productId, 'quantity' => 1]], customer: ['customerID' => $customerId], returnURL: $returnUrl, ); } } ``` Register the service in `config/services.yaml`: ```yaml theme={null} services: App\Service\DodoPaymentService: arguments: $apiKey: "%env(DODO_PAYMENTS_API_KEY)%" ``` ## Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-php) > > Source code, releases, and the full method list. > [card] [API Reference](/api-reference/introduction) > > Every endpoint, parameter, and response. > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. > [card] [Report Issues](https://github.com/dodopayments/dodopayments-php/issues) > > Report bugs or request features. ## Support For help with the PHP SDK: * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-php). ## Contributing To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-php/blob/main/CONTRIBUTING.md). # Python Source: https://docs.dodopayments.com/developer-resources/sdks/python Use the Dodo Payments Python SDK, with sync and async clients, to create checkout sessions, customers, subscriptions, and usage events from Python 3.9+. The Python SDK gives Python applications typed access to the Dodo Payments REST API. It has a synchronous client, `DodoPayments`, and an asynchronous client, `AsyncDodoPayments`, both built on `httpx`. Nested request parameters are typed dictionaries, and responses are Pydantic models. ## Installation Install the SDK with pip: ```bash theme={null} pip install dodopayments ``` To use aiohttp as the HTTP backend for the async client, install the `aiohttp` extra: ```bash theme={null} pip install "dodopayments[aiohttp]" ``` To verify webhook signatures with `client.webhooks.unwrap()`, also install the `webhooks` extra: `pip install "dodopayments[webhooks]"`. > [!NOTE] > > The SDK requires Python 3.9 or later. Use the latest stable Python release to get security updates. ## Quick Start ### Synchronous Client Create a client, then create a checkout session: ```python theme={null} import os from dodopayments import DodoPayments client = DodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), # This is the default and can be omitted environment="test_mode", # defaults to "live_mode" ) checkout_session_response = client.checkout_sessions.create( product_cart=[ { "product_id": "pdt_123", "quantity": 1 } ], ) print(checkout_session_response.session_id) ``` If you omit `bearer_token`, the client reads the `DODO_PAYMENTS_API_KEY` environment variable. If you omit `environment`, the client connects to live mode. A test mode API key works only with `environment="test_mode"`. ### Asynchronous Client `AsyncDodoPayments` has the same methods as `DodoPayments`. Await each call: ```python theme={null} import os import asyncio from dodopayments import AsyncDodoPayments client = AsyncDodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), environment="test_mode", ) async def main() -> None: checkout_session_response = await client.checkout_sessions.create( product_cart=[ { "product_id": "pdt_123", "quantity": 1, } ], ) print(checkout_session_response.session_id) asyncio.run(main()) ``` > [!WARNING] > > Keep API keys in environment variables or a secrets manager. Never commit them to version control. ## Core Features > [card] Pythonic Interface > > Keyword arguments for parameters, `TypedDict` types for nested objects, and Pydantic models for responses. > [card] Async/Await > > `AsyncDodoPayments` for asyncio, with aiohttp as an optional HTTP backend. > [card] Type Hints > > Type hints on every method, for editor autocomplete and type checking with mypy. > [card] Auto-Pagination > > List methods return iterators that fetch the next page as you loop. ## Configuration ### Environment Variables Store your API key in an environment variable: ```bash .env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... ``` The client reads these variables when you don't pass the matching argument: | Variable | Client argument | Purpose | | - | - | - | | `DODO_PAYMENTS_API_KEY` | `bearer_token` | Your API key. The client raises an error if neither is set. | | `DODO_PAYMENTS_WEBHOOK_KEY` | `webhook_key` | Your webhook signing secret, used to verify webhooks. | | `DODO_PAYMENTS_BASE_URL` | `base_url` | A custom API URL that replaces the `environment` URL. | | `DODO_PAYMENTS_LOG` | No matching argument | The log level. See [Logging](#logging). | If `DODO_PAYMENTS_BASE_URL` is set and you also pass `environment`, the constructor raises an "Ambiguous URL" error. To use `environment` in that case, pass `base_url=None`. To verify a webhook, pass the raw request body and headers to `client.webhooks.unwrap(payload, headers=headers)`. It checks the signature with your webhook key and returns the parsed event. `client.webhooks.unsafe_unwrap(payload)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks). ### Timeouts Requests time out after 1 minute by default, with a 5-second connection timeout. Pass `timeout` in seconds, or an `httpx.Timeout` for separate read, write, and connect limits: ```python theme={null} import httpx from dodopayments import DodoPayments # Configure default for all requests (default is 1 minute) client = DodoPayments( timeout=20.0, # 20 seconds ) # More granular control client = DodoPayments( timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0), ) # Override per-request client.with_options(timeout=5.0).checkout_sessions.create( product_cart=[ { "product_id": "pdt_123", "quantity": 1, } ], ) ``` When a request times out, the SDK raises `APITimeoutError`. Timed-out requests are retried, so a call can take longer than `timeout` before it fails. ### Retries Set `max_retries` on the client, or on a single request with `with_options()`: ```python theme={null} from dodopayments import DodoPayments # Configure default for all requests (default is 2) client = DodoPayments( max_retries=0, # disable retries ) # Override per-request client.with_options(max_retries=5).checkout_sessions.create( product_cart=[ { "product_id": "pdt_123", "quantity": 1, } ], ) ``` The SDK retries connection errors and responses with status 408, 409, 429, or 500 and above. It retries twice by default, with exponential backoff. When a request still fails, the SDK raises a subclass of `dodopayments.APIError`: | Status | Exception | | - | - | | 400 | `BadRequestError` | | 401 | `AuthenticationError` | | 403 | `PermissionDeniedError` | | 404 | `NotFoundError` | | 409 | `ConflictError` | | 422 | `UnprocessableEntityError` | | 429 | `RateLimitError` | | 500 and above | `InternalServerError` | | No response | `APIConnectionError` | The status exceptions inherit from `dodopayments.APIStatusError`, which has `status_code` and `response` attributes. `APITimeoutError` is a subclass of `APIConnectionError`. ## Workload Identity The SDK can use workload identity federation instead of an API key. The SDK exchanges an OIDC token from your CI or cloud platform for a short-lived Dodo Payments token. It refreshes the token before the token expires. This feature is available from version 1.124.0. Before you start, create an identity provider and a mapping in the dashboard. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup). This example uses the GitHub Actions helper, `github_actions()`: ```python theme={null} from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, github_actions client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id="wip_...", provider=github_actions(), ), ) ``` If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the SDK uses workload identity. It finds the platform from the environment. To stop the token before it expires, for example at the end of a CI job, revoke it: ```python theme={null} client.workload_identity.revoke() ``` > [!WARNING] > > Do not set an API key and workload identity together. The SDK gives an error when you set the two options. For the other platform helpers and the refresh behavior, refer to [Use Workload Identity with the SDKs](/developer-resources/workload-identity/sdk-usage). ## Common Operations The examples in this section use the `client` from [Quick Start](#quick-start). ### Create a Checkout Session Create a checkout session, then redirect the customer to the returned `checkout_url`: ```python theme={null} session = client.checkout_sessions.create( product_cart=[ { "product_id": "pdt_123", "quantity": 1 } ], return_url="https://yourdomain.com/return" ) print(f"Checkout URL: {session.checkout_url}") ``` Each `checkout_url` works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session). ### Manage Customers Create a customer with an email address and name, then retrieve it by ID: ```python theme={null} # Create a customer customer = client.customers.create( email="customer@example.com", name="John Doe", metadata={ "user_id": "12345" } ) # Retrieve customer customer = client.customers.retrieve("cus_123") print(f"Customer: {customer.name} ({customer.email})") ``` ### Handle Subscriptions Start a subscription with a checkout session, charge an on-demand subscription, and read a subscription's usage history. ```python expandable theme={null} # Start a subscription: put a subscription product in product_cart session = client.checkout_sessions.create( product_cart=[{"product_id": "pdt_456", "quantity": 1}], customer={"customer_id": "cus_123"}, # or {"email": "...", "name": "..."} for a new customer return_url="https://yourdomain.com/return", ) print("Redirect to:", session.checkout_url) # Charge an on-demand subscription # product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD) charge_response = client.subscriptions.charge( subscription_id="sub_123", product_price=2500, ) # Retrieve usage history (for metered subscriptions) usage_history = client.subscriptions.retrieve_usage_history( subscription_id="sub_123", start_date="2024-01-01T00:00:00Z", ) ``` > [!NOTE] > > The subscription starts when the customer completes checkout. Read its `subscription_id` from the `subscription.active` webhook or from the `return_url` query parameters. `customer` takes `{"customer_id": ...}` to attach an existing customer or `{"email": ..., "name": ...}` to create one. `charge` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions), and `product_price` is in the smallest currency unit. `retrieve_usage_history` returns a paginated list, which you can iterate as shown in [Pagination](#pagination). ## Usage-Based Billing ### Ingest Usage Events Send usage events for a customer: ```python theme={null} from datetime import datetime, timezone response = client.usage_events.ingest( events=[ { "event_id": "api_call_12345", "customer_id": "cus_abc123", "event_name": "api_request", "timestamp": datetime.now(timezone.utc), "metadata": { "endpoint": "/api/v1/users", "method": "GET", "tokens_used": "150" } } ] ) ``` > [!NOTE] > > The `event_id` is the idempotency key, so give each event a unique value. If the same `event_id` appears twice in one request, the whole request is rejected. If an `event_id` was already ingested, the new event is ignored. A request accepts up to 1,000 events. `timestamp` defaults to the current time and is rejected if it's more than 1 hour in the past or more than 5 minutes in the future. ### List and Retrieve Events Retrieve a single event by its `event_id`, or list events filtered by customer and event name: ```python theme={null} # Get a specific event event = client.usage_events.retrieve("api_call_12345") # List events with filtering events = client.usage_events.list( customer_id="cus_abc123", event_name="api_request", page_size=20 ) for event in events.items: print(f"Event: {event.event_id} at {event.timestamp}") ``` `usage_events.list` also accepts `meter_id`, `start`, and `end` filters. ## Pagination ### Auto-Pagination List methods return an iterator that fetches the next page as you loop: ```python theme={null} from dodopayments import DodoPayments client = DodoPayments() all_payments = [] # Automatically fetches more pages as needed for payment in client.payments.list(): all_payments.append(payment) print(all_payments) ``` ### Async Pagination With the async client, loop with `async for`: ```python theme={null} import asyncio from dodopayments import AsyncDodoPayments client = AsyncDodoPayments() async def main() -> None: all_payments = [] # Iterate through items across all pages async for payment in client.payments.list(): all_payments.append(payment) print(all_payments) asyncio.run(main()) ``` ### Manual Pagination To work with one page at a time, read `items` and call `has_next_page()` and `get_next_page()`. `next_page_info()` returns the parameters for the next request: ```python theme={null} # Access items from current page first_page = client.payments.list() for payment in first_page.items: print(payment.brand_id) # Check for more pages if first_page.has_next_page(): next_page = first_page.get_next_page() print(f"Fetched {len(next_page.items)} more items") ``` ## HTTP Client Configuration To add a proxy, a custom transport, or other `httpx` settings, pass your own `http_client`. `DefaultHttpxClient` keeps the SDK's default connection limits, timeout, and redirect settings: ```python theme={null} import httpx from dodopayments import DodoPayments, DefaultHttpxClient client = DodoPayments( base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` To use a different HTTP client for one request, call `client.with_options(http_client=...)`. ## Async with AIOHTTP By default, the async client sends requests with `httpx`. For better concurrency, install the `aiohttp` extra and pass `DefaultAioHttpClient()` as `http_client`: ```python theme={null} import os import asyncio from dodopayments import DefaultAioHttpClient from dodopayments import AsyncDodoPayments async def main() -> None: async with AsyncDodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), http_client=DefaultAioHttpClient(), ) as client: checkout_session_response = await client.checkout_sessions.create( product_cart=[ { "product_id": "pdt_123", "quantity": 1, } ], ) print(checkout_session_response.session_id) asyncio.run(main()) ``` ## Logging The SDK logs with the standard library `logging` module. To turn on logging, set `DODO_PAYMENTS_LOG` to `info`: ```bash theme={null} export DODO_PAYMENTS_LOG=info ``` For more detail, set it to `debug`: ```bash theme={null} export DODO_PAYMENTS_LOG=debug ``` ## Framework Integration These examples create a checkout session from a web endpoint and return its URL. ### FastAPI This endpoint uses the async client: ```python theme={null} from fastapi import FastAPI, HTTPException from dodopayments import AsyncDodoPayments from pydantic import BaseModel import os app = FastAPI() dodo = AsyncDodoPayments(bearer_token=os.getenv("DODO_PAYMENTS_API_KEY")) class CheckoutRequest(BaseModel): product_id: str quantity: int @app.post("/create-checkout") async def create_checkout(request: CheckoutRequest): try: session = await dodo.checkout_sessions.create( product_cart=[{ "product_id": request.product_id, "quantity": request.quantity }], return_url="https://yourdomain.com/return" ) return {"checkout_url": session.checkout_url} except Exception as e: raise HTTPException(status_code=400, detail=str(e)) ``` ### Django This view uses the sync client: ```python theme={null} from django.http import JsonResponse from django.views.decorators.http import require_POST from django.views.decorators.csrf import csrf_exempt from dodopayments import DodoPayments import os import json client = DodoPayments(bearer_token=os.getenv("DODO_PAYMENTS_API_KEY")) @csrf_exempt @require_POST def create_checkout(request): try: data = json.loads(request.body) session = client.checkout_sessions.create( product_cart=[{ "product_id": data.get("product_id"), "quantity": data.get("quantity", 1) }], return_url="https://yourdomain.com/return" ) return JsonResponse({ "status": "success", "checkout_url": session.checkout_url, "session_id": session.session_id }) except Exception as e: return JsonResponse({ "status": "error", "message": str(e) }, status=400) ``` ## Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-python) > > Source code, releases, and the full method list. > [card] [API Reference](/api-reference/introduction) > > Every endpoint, parameter, and response. > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. > [card] [Report Issues](https://github.com/dodopayments/dodopayments-python/issues) > > Report bugs or request features. ## Support For help with the Python SDK: * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-python). ## Contributing To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-python/blob/main/CONTRIBUTING.md). # Ruby Source: https://docs.dodopayments.com/developer-resources/sdks/ruby Use the Dodo Payments Ruby SDK to create checkout sessions, customers, and subscriptions from Ruby 3.2+, with auto-pagination, retries, and Sorbet types. The Ruby SDK gives Ruby applications access to the Dodo Payments REST API. It sends requests with the standard library's `net/http` and a connection pool, retries failed requests, iterates through paginated lists for you, and ships RBI and RBS type definitions. ## Installation Add the gem to your Gemfile: ```ruby Gemfile theme={null} gem "dodopayments", "~> 2.30" ``` > [!TIP] > > SDK releases add support for API changes. Run `bundle update dodopayments` regularly to stay up to date. Then install it: ```bash theme={null} bundle install ``` > [!NOTE] > > The SDK requires Ruby 3.2.0 or later. ## Quick Start Create a client, then create a checkout session: ```ruby theme={null} require "bundler/setup" require "dodopayments" dodo_payments = Dodopayments::Client.new( bearer_token: ENV["DODO_PAYMENTS_API_KEY"], # This is the default and can be omitted environment: "test_mode" # defaults to "live_mode" ) checkout_session_response = dodo_payments.checkout_sessions.create( product_cart: [{product_id: "pdt_123", quantity: 1}] ) puts(checkout_session_response.session_id) ``` If you omit `bearer_token`, the client reads the `DODO_PAYMENTS_API_KEY` environment variable. If you omit `environment`, the client connects to live mode. A test mode API key works only with `environment: "test_mode"`. > [!WARNING] > > Keep API keys in environment variables or a secrets manager. Never commit them to version control or expose them in your code. ## Core Features > [card] Ruby Conventions > > Snake\_case methods and keyword arguments, with plain hashes accepted for nested parameters. > [card] Elegant Syntax > > Responses are objects with attribute readers, and `obj[:prop]` also reads fields the SDK doesn't define. > [card] Auto-Pagination > > `auto_paging_each` iterates over every item and fetches the next page when needed. > [card] Type Safety > > RBI definitions for Sorbet, with no dependency on `sorbet-runtime`. ## Configuration `Dodopayments::Client.new` takes `bearer_token`, `webhook_key`, `environment`, `base_url`, `max_retries`, `timeout`, `initial_retry_delay`, and `max_retry_delay`. When you omit them, it reads `DODO_PAYMENTS_API_KEY`, `DODO_PAYMENTS_WEBHOOK_KEY` (your webhook signing secret), and `DODO_PAYMENTS_BASE_URL` from the environment. The client is thread-safe and keeps its own connection pool, so create one client for your application and reuse it. To verify a webhook, pass the raw request body and headers to `dodo_payments.webhooks.unwrap(payload, headers: headers)`. It checks the signature with your webhook key and returns the parsed event. `dodo_payments.webhooks.unsafe_unwrap(payload)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks). ### Timeout Configuration Requests time out after 60 seconds by default. Set `timeout`, in seconds, on the client or on a single request: ```ruby theme={null} # Configure default for all requests (default is 60 seconds) dodo_payments = Dodopayments::Client.new( timeout: nil # disable timeout ) # Or, configure per-request dodo_payments.checkout_sessions.create( product_cart: [{product_id: "pdt_123", quantity: 1}], request_options: {timeout: 5} ) ``` When a request times out, the SDK raises `Dodopayments::Errors::APITimeoutError`. Timed-out requests are retried by default. ### Retry Configuration The SDK retries connection errors, timeouts, and responses with status 408, 409, 429, or 500 and above. It retries twice by default, with a short exponential backoff. Set `max_retries` on the client or on a single request: ```ruby theme={null} # Configure default for all requests (default is 2) dodo_payments = Dodopayments::Client.new( max_retries: 0 # disable retries ) # Or, configure per-request dodo_payments.checkout_sessions.create( product_cart: [{product_id: "pdt_123", quantity: 1}], request_options: {max_retries: 5} ) ``` ## Workload Identity The SDK can use workload identity federation instead of an API key. The SDK exchanges an OIDC token from your CI or cloud platform for a short-lived Dodo Payments token. It refreshes the token before the token expires. This feature is available from version 2.36.0. Before you start, create an identity provider and a mapping in the dashboard. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup). This example uses the GitHub Actions helper, `Dodopayments::WorkloadIdentity.github_actions`: ```ruby theme={null} client = Dodopayments::Client.new( environment: "live_mode", workload_identity: Dodopayments::WorkloadIdentity::Config.new( identity_provider_id: "wip_...", provider: Dodopayments::WorkloadIdentity.github_actions ) ) ``` If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the SDK uses workload identity. It finds the platform from the environment. To stop the token before it expires, for example at the end of a CI job, revoke it: ```ruby theme={null} client.workload_identity.revoke ``` > [!WARNING] > > Do not set an API key and workload identity together. The SDK gives an error when you set the two options. For the other platform helpers and the refresh behavior, refer to [Use Workload Identity with the SDKs](/developer-resources/workload-identity/sdk-usage). ## Common Operations The examples in this section use the `dodo_payments` client from [Quick Start](#quick-start). ### Create a Checkout Session Create a checkout session, then redirect the customer to the returned `checkout_url`: ```ruby theme={null} session = dodo_payments.checkout_sessions.create( product_cart: [ { product_id: "pdt_123", quantity: 1 } ], return_url: "https://yourdomain.com/return" ) # In a Rails controller, redirect to checkout redirect_to session.checkout_url, allow_other_host: true ``` Each checkout URL works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session). ### Manage Customers Create a customer with an email address and name, then retrieve it by ID: ```ruby theme={null} # Create a customer customer = dodo_payments.customers.create( email: "customer@example.com", name: "John Doe", metadata: { user_id: "12345" } ) # Retrieve customer customer = dodo_payments.customers.retrieve("cus_123") puts "Customer: #{customer.name} (#{customer.email})" ``` ### Handle Subscriptions Start a subscription with a checkout session, charge an on-demand subscription, and update a subscription's metadata. ```ruby theme={null} # Start a subscription: put a subscription product in product_cart session = dodo_payments.checkout_sessions.create( product_cart: [{ product_id: "pdt_456", quantity: 1 }], customer: { customer_id: "cus_123" }, # or { email: "...", name: "..." } for a new customer return_url: "https://yourdomain.com/return" ) puts "Redirect to: #{session.checkout_url}" # Charge an on-demand subscription # product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD) charge = dodo_payments.subscriptions.charge( "sub_123", product_price: 2500 ) # Update subscription metadata updated = dodo_payments.subscriptions.update( "sub_123", metadata: { plan_type: "premium" } ) ``` > [!NOTE] > > The subscription starts when the customer completes checkout. Read its `subscription_id` from the `subscription.active` webhook or from the `return_url` query parameters. `customer` takes `{ customer_id: "..." }` to attach an existing customer or `{ email: "...", name: "..." }` to create one. `charge` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions), and `product_price` is in the smallest currency unit. ## Pagination ### Auto-Pagination List methods return a page. Read `items` for the current page, or call `auto_paging_each` to iterate over every item. It fetches the next page when it needs it: ```ruby theme={null} page = dodo_payments.payments.list # Fetch single item from page payment = page.items[0] puts(payment.brand_id) # Automatically fetches more pages as needed page.auto_paging_each do |payment| puts(payment.brand_id) end ``` ### Manual Pagination To move one page at a time, call `next_page?` and `next_page`: ```ruby theme={null} page = dodo_payments.payments.list if page.next_page? new_page = page.next_page puts(new_page.items[0].brand_id) end ``` ## Error Handling When the SDK can't connect to the API, or the API returns a 4xx or 5xx status, the SDK raises a subclass of `Dodopayments::Errors::APIError`: ```ruby theme={null} begin checkout_session = dodo_payments.checkout_sessions.create( product_cart: [{product_id: "pdt_123", quantity: 1}] ) rescue Dodopayments::Errors::APIConnectionError => e puts("The server could not be reached") puts(e.cause) # an underlying Exception, likely raised within `net/http` rescue Dodopayments::Errors::RateLimitError => e puts("A 429 status code was received; we should back off a bit.") rescue Dodopayments::Errors::APIStatusError => e puts("Another non-200-range status code was received") puts(e.status) end ``` The error class depends on the cause. Each error has `status`, `headers`, and `body` attributes: | Cause | Error class | | - | - | | HTTP 400 | `BadRequestError` | | HTTP 401 | `AuthenticationError` | | HTTP 403 | `PermissionDeniedError` | | HTTP 404 | `NotFoundError` | | HTTP 409 | `ConflictError` | | HTTP 422 | `UnprocessableEntityError` | | HTTP 429 | `RateLimitError` | | HTTP 500 and above | `InternalServerError` | | Other HTTP error | `APIStatusError` | | Timeout | `APITimeoutError` | | Network error | `APIConnectionError` | > [!TIP] > > The SDK already retries 429 responses with exponential backoff. A `RateLimitError` means those retries also failed, so wait longer before you send the request again. ## Type Safety with Sorbet The SDK ships RBI definitions and doesn't depend on `sorbet-runtime`. To get type-checked request parameters, pass model classes instead of hashes: ```ruby theme={null} # Type-safe using Sorbet RBI definitions dodo_payments.checkout_sessions.create( product_cart: [ Dodopayments::ProductItemReq.new( product_id: "pdt_123", quantity: 1 ) ] ) # Hashes work, but are not typesafe dodo_payments.checkout_sessions.create( product_cart: [{product_id: "pdt_123", quantity: 1}] ) # You can also splat a full Params class params = Dodopayments::CheckoutSessionCreateParams.new( product_cart: [ Dodopayments::ProductItemReq.new( product_id: "pdt_123", quantity: 1 ) ] ) dodo_payments.checkout_sessions.create(**params) ``` ## Advanced Usage ### Undocumented Endpoints To call an endpoint that has no SDK method, use `request`. It applies the same authentication and retries as the SDK methods: ```ruby theme={null} response = dodo_payments.request( method: :post, path: '/undocumented/endpoint', query: {"dog": "woof"}, headers: {"useful-header": "interesting-value"}, body: {"hello": "world"} ) ``` ### Undocumented Parameters To send parameters that the SDK doesn't define, pass them in `request_options`. An `extra_*` parameter that has the same name as a documented parameter overrides it: ```ruby theme={null} checkout_session_response = dodo_payments.checkout_sessions.create( product_cart: [{product_id: "pdt_123", quantity: 1}], request_options: { extra_query: {my_query_parameter: "value"}, extra_body: {my_body_parameter: "value"}, extra_headers: {"my-header": "value"} } ) # Access undocumented response properties puts(checkout_session_response[:my_undocumented_property]) ``` ## Rails Integration ### Create an Initializer Create one client when Rails starts, in `config/initializers/dodo_payments.rb`: ```ruby theme={null} require "dodopayments" DODO_CLIENT = Dodopayments::Client.new( bearer_token: Rails.application.credentials.dodo_api_key, environment: Rails.env.production? ? "live_mode" : "test_mode" ) ``` ### Service Object Pattern Wrap the client in a service object: ```ruby theme={null} # app/services/payment_service.rb class PaymentService def initialize @client = DODO_CLIENT end def create_checkout(items) @client.checkout_sessions.create( product_cart: items, return_url: Rails.application.routes.url_helpers.checkout_return_url ) end def checkout_for_customer(product_id:, customer_id:) @client.checkout_sessions.create( product_cart: [{ product_id: product_id, quantity: 1 }], customer: { customer_id: customer_id }, return_url: Rails.application.routes.url_helpers.checkout_return_url ) end end ``` ### Controller Integration Call the service from a controller and redirect to the checkout page: ```ruby theme={null} # app/controllers/checkouts_controller.rb class CheckoutsController < ApplicationController def create service = PaymentService.new session = service.create_checkout(checkout_params[:items]) redirect_to session.checkout_url, allow_other_host: true rescue Dodopayments::Errors::APIError => e flash[:error] = "Payment error: #{e.message}" redirect_to cart_path end private def checkout_params params.require(:checkout).permit(items: [:product_id, :quantity]) end end ``` ## Sinatra Integration Create the client once in a `configure` block and use it in your routes: ```ruby theme={null} require "sinatra" require "dodopayments" configure do set :dodo_client, Dodopayments::Client.new( bearer_token: ENV["DODO_PAYMENTS_API_KEY"] ) end post "/create-checkout" do content_type :json begin session = settings.dodo_client.checkout_sessions.create( product_cart: JSON.parse(request.body.read)["items"], return_url: "#{request.base_url}/return" ) { checkout_url: session.checkout_url }.to_json rescue Dodopayments::Errors::APIError => e status 400 { error: e.message }.to_json end end ``` ## Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-ruby) > > Source code, releases, and the full method list. > [card] [API Reference](/api-reference/introduction) > > Every endpoint, parameter, and response. > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. > [card] [Report Issues](https://github.com/dodopayments/dodopayments-ruby/issues) > > Report bugs or request features. ## Support For help with the Ruby SDK: * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-ruby). ## Contributing To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-ruby/blob/main/CONTRIBUTING.md). # TypeScript Source: https://docs.dodopayments.com/developer-resources/sdks/typescript Use the Dodo Payments TypeScript SDK to create checkout sessions, customers, subscriptions, and usage events from Node.js and other JavaScript runtimes. The TypeScript SDK gives server-side TypeScript and JavaScript code typed access to the Dodo Payments REST API. It includes type definitions for every request and response, typed errors, automatic retries, timeouts, and auto-pagination. ## Installation Install the `dodopayments` package with your package manager: ```bash npm theme={null} npm install dodopayments ``` ```bash yarn theme={null} yarn add dodopayments ``` ```bash pnpm theme={null} pnpm add dodopayments ``` ## Quick Start Create a client, then create a checkout session: ```javascript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], // This is the default and can be omitted environment: 'test_mode', // defaults to 'live_mode' }); const checkoutSessionResponse = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], }); console.log(checkoutSessionResponse.session_id); ``` If you omit `bearerToken`, the client reads the `DODO_PAYMENTS_API_KEY` environment variable. If you omit `environment`, the client connects to live mode. A test mode API key works only with `environment: 'test_mode'`. > [!WARNING] > > Keep API keys in environment variables or a secrets manager. Never commit them to version control or expose them in client-side code. ## Core Features > [card] TypeScript First > > Type definitions for every request parameter and response field, shown in your editor. > [card] Auto-Pagination > > List methods fetch the next page for you when you iterate with `for await...of`. > [card] Error Handling > > A typed error class for each HTTP error status, with the status, headers, and response body. > [card] Smart Retries > > Two retries by default, with exponential backoff, for connection errors and retryable status codes. ## Configuration ### Environment Variables Store your API key in an environment variable: ```bash .env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... ``` The client reads these variables when you don't pass the matching option: | Variable | Client option | Purpose | | - | - | - | | `DODO_PAYMENTS_API_KEY` | `bearerToken` | Your API key. The client throws an error if neither is set. | | `DODO_PAYMENTS_WEBHOOK_KEY` | `webhookKey` | Your webhook signing secret, used to verify webhooks. | | `DODO_PAYMENTS_BASE_URL` | `baseURL` | A custom API URL that replaces the `environment` URL. | | `DODO_PAYMENTS_LOG` | `logLevel` | The log level. See [Logging](#logging). | If a base URL is set and you also pass `environment`, the constructor throws an "Ambiguous URL" error. To use `environment` in that case, pass `baseURL: null`. To verify a webhook, pass the raw request body and headers to `client.webhooks.unwrap(rawBody, { headers })`. It checks the signature with your webhook key and returns the parsed event. `client.webhooks.unsafeUnwrap(rawBody)` parses the body without verifying it, so use it only for testing. See [Webhooks](/developer-resources/webhooks). ### Timeout Configuration Requests time out after 1 minute by default. Set `timeout`, in milliseconds, on the client or on a single request: ```typescript theme={null} // Configure default timeout for all requests (default is 1 minute) const client = new DodoPayments({ timeout: 20 * 1000, // 20 seconds }); // Override per-request await client.checkoutSessions.create( { product_cart: [{ product_id: 'pdt_123', quantity: 1 }] }, { timeout: 5 * 1000 }, ); ``` When a request times out, the SDK throws `APIConnectionTimeoutError`. Timed-out requests are retried, so a call can take longer than `timeout` before it fails. ### Retry Configuration Set `maxRetries` on the client or on a single request: ```javascript theme={null} // Configure default for all requests (default is 2 retries) const client = new DodoPayments({ maxRetries: 0, // disable retries }); // Override per-request await client.checkoutSessions.create( { product_cart: [{ product_id: 'pdt_123', quantity: 1 }] }, { maxRetries: 5 }, ); ``` > [!TIP] > > The SDK retries connection errors and responses with status 408, 409, 429, or 500 and above. It retries twice by default, with exponential backoff. When a request still fails, the SDK throws a subclass of `DodoPayments.APIError`. Each error has `status`, `headers`, and `error` (the response body) properties. Check for a specific class with `instanceof`, for example `err instanceof DodoPayments.RateLimitError`: | Status | Error class | | - | - | | 400 | `BadRequestError` | | 401 | `AuthenticationError` | | 403 | `PermissionDeniedError` | | 404 | `NotFoundError` | | 409 | `ConflictError` | | 422 | `UnprocessableEntityError` | | 429 | `RateLimitError` | | 500 and above | `InternalServerError` | | No response | `APIConnectionError` | ## Workload Identity The SDK can use workload identity federation instead of an API key. The SDK exchanges an OIDC token from your CI or cloud platform for a short-lived Dodo Payments token. It refreshes the token before the token expires. This feature is available from version 2.58.0. Before you start, create an identity provider and a mapping in the dashboard. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup). This example uses the GitHub Actions helper, `DodoPayments.workloadIdentity.githubActions()`: ```typescript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: 'wip_...', provider: DodoPayments.workloadIdentity.githubActions(), }, }); ``` If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the SDK uses workload identity. It finds the platform from the environment. To stop the token before it expires, for example at the end of a CI job, revoke it: ```typescript theme={null} await client.workloadIdentity.revoke(); ``` > [!WARNING] > > Do not set an API key and workload identity together. The SDK gives an error when you set the two options. For the other platform helpers and the refresh behavior, refer to [Use Workload Identity with the SDKs](/developer-resources/workload-identity/sdk-usage). ## Common Operations The examples in this section use the `client` from [Quick Start](#quick-start). ### Create a Checkout Session Create a checkout session, then redirect the customer to the returned `checkout_url`: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], return_url: 'https://yourdomain.com/return' }); console.log('Redirect to:', session.checkout_url); ``` Each `checkout_url` works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session). ### Manage Customers Create a customer with an email address and name, then retrieve it by ID: ```typescript theme={null} // Create a customer const customer = await client.customers.create({ email: 'customer@example.com', name: 'John Doe', metadata: { user_id: '12345' } }); // Retrieve customer const retrieved = await client.customers.retrieve('cus_123'); console.log(`Customer: ${retrieved.name} (${retrieved.email})`); ``` ### Handle Subscriptions Start a subscription with a checkout session, charge an on-demand subscription, and read a subscription's usage history. ```typescript expandable theme={null} // Start a subscription: put a subscription product in product_cart const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_456', quantity: 1 }], customer: { customer_id: 'cus_123' }, // or pass { email, name } to create a new customer return_url: 'https://yourdomain.com/return', }); console.log('Redirect to:', session.checkout_url); // Charge an on-demand subscription // product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD) const chargeResponse = await client.subscriptions.charge('sub_123', { product_price: 2500, }); // Retrieve subscription usage history (for metered subscriptions) const usageHistory = await client.subscriptions.retrieveUsageHistory('sub_123', { start_date: '2024-01-01T00:00:00Z', end_date: '2024-03-31T23:59:59Z', }); ``` > [!NOTE] > > The subscription starts when the customer completes checkout. Read its `subscription_id` from the `subscription.active` webhook or from the `return_url` query parameters. `customer` takes `{ customer_id }` to attach an existing customer or `{ email, name? }` to create one. `charge` is for [on-demand subscriptions](/developer-resources/ondemand-subscriptions), and `product_price` is in the smallest currency unit. `retrieveUsageHistory` returns a paginated list, which you can iterate as shown in [Auto-Pagination](#auto-pagination). ## Usage-Based Billing ### Ingest Usage Events Send usage events for a customer: ```typescript theme={null} await client.usageEvents.ingest({ events: [ { event_id: 'api_call_12345', customer_id: 'cus_abc123', event_name: 'api_request', timestamp: new Date().toISOString(), metadata: { endpoint: '/api/v1/users', method: 'GET', tokens_used: '150' } } ] }); ``` > [!NOTE] > > The `event_id` is the idempotency key, so give each event a unique value. If the same `event_id` appears twice in one request, the whole request is rejected. If an `event_id` was already ingested, the new event is ignored. A request accepts up to 1,000 events. `timestamp` defaults to the current time and is rejected if it's more than 1 hour in the past or more than 5 minutes in the future. ### Retrieve Usage Events Retrieve a single event by its `event_id`, or list events filtered by customer, event name, and time range: ```typescript theme={null} // Get a specific event const event = await client.usageEvents.retrieve('api_call_12345'); // List events with filtering const events = await client.usageEvents.list({ customer_id: 'cus_abc123', event_name: 'api_request', start: '2024-01-14T10:30:00Z', end: '2024-01-15T10:30:00Z' }); ``` `usageEvents.list` also accepts `meter_id`, and returns a paginated list. ## Proxy Configuration To send requests through a proxy, pass your runtime's proxy settings in `fetchOptions`. ### Node.js (Using Undici) Pass an undici `ProxyAgent` as the `dispatcher`: ```typescript theme={null} import DodoPayments from 'dodopayments'; import * as undici from 'undici'; const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const client = new DodoPayments({ fetchOptions: { dispatcher: proxyAgent, }, }); ``` ### Bun Set the `proxy` option: ```typescript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` ### Deno Create an HTTP client with `Deno.createHttpClient` and pass it as `client`: ```typescript theme={null} import DodoPayments from 'npm:dodopayments'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new DodoPayments({ fetchOptions: { client: httpClient, }, }); ``` ## Logging Set the log level with the `logLevel` client option or the `DODO_PAYMENTS_LOG` environment variable. The client option overrides the environment variable. > [!WARNING] > > At the `debug` level, the SDK logs every HTTP request and response, including headers and bodies. Some authentication headers are redacted, but sensitive data in bodies may still be visible. ```typescript theme={null} // Via client option const client = new DodoPayments({ logLevel: 'debug', // Show all log messages }); ``` ```bash theme={null} # Via environment variable export DODO_PAYMENTS_LOG=debug ``` The log levels, from most to least verbose, are: * `'debug'`: Debug messages, info, warnings, and errors. * `'info'`: Info messages, warnings, and errors. * `'warn'`: Warnings and errors. This is the default. * `'error'`: Errors only. * `'off'`: No logging. The SDK logs to `console` by default. To use `pino`, `winston`, or another logging library, pass your logger as the `logger` option; `logLevel` still controls which messages reach it. Log messages are for debugging only, and their format can change between releases. ## Migration from Node.js SDK If you use the legacy Node.js SDK, follow the migration guide to upgrade. The current SDK uses the built-in `fetch` API instead of `node-fetch`, requires Node.js 20, TypeScript 4.9, and Jest 28 or later, and includes a migration tool that updates most of your code. > [card] [View Migration Guide](https://github.com/dodopayments/dodopayments-typescript/blob/main/MIGRATION.md) > > Learn how to migrate from the Node.js SDK to the TypeScript SDK ## Auto-Pagination List methods return paginated results. Iterate with `for await...of` to get items from every page. The SDK requests the next page when it needs it: ```typescript theme={null} async function fetchAllPayments() { const allPayments = []; // Automatically fetches more pages as needed. for await (const paymentListResponse of client.payments.list()) { allPayments.push(paymentListResponse); } return allPayments; } ``` To work with one page at a time, read `page.items` and call `hasNextPage()` and `getNextPage()`: ```typescript theme={null} let page = await client.payments.list(); for (const paymentListResponse of page.items) { console.log(paymentListResponse); } // Convenience methods are provided for manually paginating: while (page.hasNextPage()) { page = await page.getNextPage(); // Process page.items here } ``` To set the page size, pass `page_size` to the list method, for example `client.payments.list({ page_size: 50 })`. ## Requirements The SDK supports TypeScript 4.9 or later and these runtimes: * Web browsers (up-to-date Chrome, Firefox, Safari, Edge, and others) * Node.js 20 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions * Deno 1.28.0 or later * Bun 1.0 or later * Cloudflare Workers * Vercel Edge Runtime * Jest 28 or later with the `"node"` environment (the `"jsdom"` environment isn't supported) * Nitro 2.6 or later React Native isn't supported. ## Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-typescript) > > Source code, releases, and the full method list. > [card] [API Reference](/api-reference/introduction) > > Every endpoint, parameter, and response. > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. > [card] [Report Issues](https://github.com/dodopayments/dodopayments-typescript/issues) > > Report bugs or request features. ## Support For help with the TypeScript SDK: * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-typescript). ## Contributing To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-typescript/blob/main/CONTRIBUTING.md). # Balances Source: https://docs.dodopayments.com/features/account-summary-payout-wallet Track payments, refunds, disputes, fees, taxes, and payouts across your USD, GBP, and EUR wallets with the Balances ledger in Dodo Payments. ## Introduction The **Balances** page shows every change to your wallet balances: payments, refunds, disputes, fees, taxes, and payouts. Use it to see what you earned, what was deducted, and what remains for your next payout. Open it from **Payouts → Balances** in the dashboard. ## Key Details ![Balances dashboard showing wallet overview and transaction ledger](https://mintcdn.com/dodopayments/86riaeMBxlAcW9Bk/images/balances.png?fit=max\&auto=format\&n=86riaeMBxlAcW9Bk\&q=85\&s=d15b189037b8797e83c79d3f211638a5) The page shows your **Total Balance** in your settlement currency, next to a tile for each wallet with that wallet's balance. Select a wallet tile to show only that wallet's entries in the ledger. Below it, the ledger table lists each entry with its **Transaction Type**, **Transaction Amount**, **Transaction ID**, **Previous Wallet Balance**, **Updated Wallet Balance**, and **Date**. You can filter the ledger and download a report of the entries you select. ## Wallet Structure Each business account has **three native wallets**, one for each supported payout currency: | Wallet | Currency Code | | - | - | | USD Wallet | USD | | GBP Wallet | GBP | | EUR Wallet | EUR | ### Wallet Logic Each sale is **credited to one wallet**, chosen from the **customer's payment currency** and **billing country**. The routing is designed for **payment processor efficiency**, **lower transaction fees**, and **lower currency conversion charges**. ## Balance Ledger Each wallet has an **independent ledger** that records its activity in that wallet's currency. The **All** view combines the ledgers of every wallet into one history. ### Filters and Navigation * **Currency Filter:** Shows the entries of one wallet (USD, INR, EUR, or GBP), or **All** wallets together. * **Event Type Filter:** Shows only the transaction types you select. * **Date Filter and Report:** Narrows the ledger to a date range, and downloads the matching entries as a report. ### Transaction Types The Balances ledger records transaction types such as the following. For the full list of `event_type` values, see [List Balance Ledger Entries](/api-reference/balance-ledger/list-ledger-entries). | Transaction Type | Symbol | Description | | - | - | - | | **Payment** | Credit (+) | Successful customer payment | | **Refund** | Debit (-) | Amount returned to the customer | | **Refund Reversal** | Credit (+) | A reversed refund, returned to your wallet | | **Dispute** | Debit (-) | Disputed amount, deducted and held while the dispute is open | | **Dispute Reversal** | Credit (+) | Disputed amount returned after a dispute resolves in your favor | | **Tax** | Debit (-) | Tax collected on a payment, which Dodo Payments remits | | **Tax Reversal** | Credit (+) | Tax returned when a payment is refunded or a dispute is reversed | | **Payment Fees** | Debit (-) | Dodo Payments transaction fees on a payment | | **Gateway Fee** | Debit (-) | Fixed Dodo Payments fee, charged once on each payment with interchange-plus-plus (IC++) pricing, including a failed payment | | **Interchange Fee** | Debit (-) | Interchange fee and its tax on an IC++ payment, passed through from the processor after settlement | | **Scheme Fee** | Debit (-) | Card scheme fees and their tax on an IC++ payment, passed through from the processor after settlement | | **Refund Fees** | Debit (-) | Fee for processing a refund | | **Refund Fees Reversal** | Credit (+) | Refund fee returned when a refund is reversed | | **Dispute Fees** | Debit (-) | Fee for handling a dispute, not returned when you win | | **Dispute Fees Reversal** | Credit (+) | Dispute fee cancelled, for example when a **Visa RDR Fee** replaces it | | **Visa RDR Fee** | Debit (-) | Fee for a dispute resolved through Visa Rapid Dispute Resolution | | **Deflection Fees** | Debit (-) | Fee for a dispute prevented before it was filed | | **Deflection Fees Reversal** | Credit (+) | Deflection fee returned to your wallet | | **BYOP Fee** | Debit (-) | [BYOP](/features/byop) billing fee on a payment routed through your own processor | | **Moderation Fees** | Debit (-) | Fee for each full block of [moderation](/features/moderation) screens | | **Payout** | Debit (-) | Amount transferred to your bank account | | **Payout Fees** | Debit (-) | Fee deducted from a payout | | **Payout Reversal** | Credit (+) | Payout amount returned after a failed payout | | **Payout Fees Reversal** | Credit (+) | Payout fee returned after a failed payout | | **Dodo Credits** | Credit (+) | Credit issued to your wallet by Dodo Payments | | **Adjustment** | Credit (+) or Debit (-) | Manual correction made by Dodo Payments | **Gateway Fee**, **Interchange Fee**, and **Scheme Fee** appear only on payments with IC++ pricing. The API returns them as the `dodo_fixed_fee`, `interchange_fee`, and `scheme_fee` event types. The **Payout Report** export labels the gateway fee column **Dodo Fixed Fee**. On an IC++ payment, **Payment Fees** holds the percentage payment method fee. #### Additional Fields * **Transaction Amount** and **Date:** The value of the entry, and the date and time it was recorded. * **Transaction ID:** Unique identifier for tracking and support requests. * **Previous Wallet Balance** and **Updated Wallet Balance:** The wallet balance before and after the entry. ## Total Balance The **Total Balance** shows a **consolidated, indicative amount** of your **USD, GBP, and EUR** wallet balances after conversion to your settlement currency, the currency that Dodo Payments pays your payout in. The tooltip names the currency. > [!NOTE] > > **Indicative Display:** The displayed amount is **for reference only**. The final payout amount depends on the exchange rate at the time of transfer. ## Conclusion Use the **Balances** page to reconcile each payout against the entries that make it up, and to trace any single payment, refund, or fee through its **Transaction ID**. For how and when your balance is paid out, see [Payouts Process](/features/payouts/payout-structure). > [!TIP] > > For discrepancies or questions, email [support@dodopayments.com](mailto:support@dodopayments.com) with the **Transaction ID** and a description of the issue. # Adaptive Currency Source: https://docs.dodopayments.com/features/adaptive-currency Display prices in each customer's local currency to reduce friction and improve conversion. Automatic detection, conversion, and same-currency refunds. Adaptive Currency displays product prices in the customer's local currency instead of only your base currency. When enabled, checkout defaults to the detected local currency for supported countries, with the option to switch back to your base currency. ## How It Works Your base currency is whatever you priced the product or add-on in — it can be any currency Dodo Payments can charge, not just USD. Adaptive Currency converts that base price at live exchange rates. To set your own fixed price per currency or country instead, see [Localized Pricing](/features/localized-pricing). ## Key Benefits * **Localized checkout** — Prices appear in the customer's local currency by default * **More payment methods** — Unlocks payment methods available only for the local currency * **Same-currency refunds** — Refund the customer in the currency they paid with * **Advanced pricing** — Enables [Purchasing Power Parity](/features/purchasing-power-parity) and [Charm Pricing](/features/charm-pricing) for automatic price optimization by market ## Enable Adaptive Currency **1. Open Settings** Log in to your Merchant Dashboard and go to **Settings → Pricing**. **2. Enable Adaptive Currency** Toggle on Adaptive Currency. You can disable it at any time. > [!WARNING] > > Changes apply only to future transactions. **3. Save and Test** Save your settings, then verify a test checkout shows prices in your local currency when supported. ![Adaptive Currency toggle in Settings](https://mintcdn.com/dodopayments/5D2vY2CKcFOZLLyz/images/our-features/adaptive_currency.png?fit=max\&auto=format\&n=5D2vY2CKcFOZLLyz\&q=85\&s=14a6ae2a3c6d45833adc68d88e1f9ba8) ## Customer Experience When Adaptive Currency is enabled: 1. **Detection** — The system detects the customer's country based on their billing address 2. **Currency selection** — If the country is supported, prices show in the local currency by default. Customers can switch back to your base currency 3. **Payment methods** — Localized payment methods appear where applicable 4. **Checkout** — Payment is completed in the selected currency ## Conversion and Fees Adaptive Currency charges the customer in their local currency using live exchange rates. Fees are tiered by order value: * 4% for orders under \$500 * 3% for orders \$500 to \$1,500 * 2% for orders over \$1,500 By default, these fees are added on top of your displayed price and borne by the customer. With the **Fees Inclusive** setting, you can absorb the fee yourself: the customer sees the same local-currency price, and the fee is deducted from your settlement. ### Enable Fees Inclusive **1. Open Settings** Go to **Settings → Pricing** and enable Adaptive Currency if you haven't already. **2. Enable Fees Inclusive** Once Adaptive Currency is on, enable the **Fees Inclusive** toggle in the same section. | Mode | Customer Sees | Merchant Settles | | :- | :- | :- | | Exclusive (default) | Local price + 2–4% fee on top | Full base price | | Inclusive | Local price (unchanged) | Base price minus the 2–4% fee | ### Override Per Request You can override the merchant default per request with `adaptive_currency_fees_inclusive` (boolean). On a checkout session, pass it for an on-demand subscription as `subscription_data.on_demand.adaptive_currency_fees_inclusive`. A checkout session doesn't accept it at the top level, so one-time checkouts use your business setting. Subscription charges and plan changes also accept the field. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_abc', quantity: 1 }], customer: { customer_id: 'cus_123' }, subscription_data: { on_demand: { mandate_only: true, adaptive_currency_fees_inclusive: true, // override the business setting }, }, return_url: 'https://yoursite.com/return' }); ``` > [!NOTE] > > INR → INR transactions are always treated as inclusive regardless of the business setting or per-request override. > [!NOTE] > > When a [Localized Pricing](/features/localized-pricing) rule matches, the transaction is always treated as inclusive, regardless of your **Fees Inclusive** setting or any per-request override. The customer pays exactly the localized amount you set, and the conversion fee is deducted from your settlement. ## Minimum Amounts Every payment must meet the minimum for the currency the customer pays in, and subscriptions have higher minimums than one-time payments. The same minimums apply to every payment method. The check uses the total, including tax. | Billing Currency | One-Time Payments | Subscriptions | | :- | :- | :- | | USD | \$0.50 | \$1.00 | | EUR and GBP | 0.50 EUR, 0.30 GBP | 0.50 EUR, 0.30 GBP | | Every other currency | The minimum in [Supported Currencies](#supported-currencies), and at least the equivalent of \$0.50 | The minimum in [Supported Currencies](#supported-currencies), and at least the equivalent of \$1.00 | Payments in currencies other than USD, EUR, and GBP settle in USD. For these currencies, checkout first checks the price converted to USD, before the Adaptive Currency fee is added, and then checks the amount in the customer's currency. The amount must pass both checks, so the effective minimum can be higher than the listed minimum for the currency. For example, the listed minimum for AED is 2.00 AED, but a subscription in AED must be worth at least \$1.00, which is about 3.70 AED. A subscription of 2.00 AED fails the USD check. If a payment is below the minimum, the API returns `TOTAL_PAYMENT_AMOUNT_BELOW_MINIMUM_AMOUNT`. The message names the minimum that failed. For a payment in another currency, that can be the USD minimum, such as `Minimum amount of 1.00 USD is required to process payment`. ## Supported Currencies The table lists each currency's minimum amount. The minimum applies to one-time payments and subscriptions. See [Minimum Amounts](#minimum-amounts) for the additional USD check. | Currency Code | Currency Name | Countries | Minimum Amount | | - | - | - | - | | AED | UAE Dirham | United Arab Emirates | 2.00 AED | | ALL | Albanian Lek | Albania | 50.00 ALL | | AMD | Armenian Dram | Armenia | 500.00 AMD | | AUD | Australian Dollar | Australia, Nauru | 0.50 AUD | | AWG | Aruban Florin | Aruba | 2.00 AWG | | AZN | Azerbaijani Manat | Azerbaijan | 2.00 AZN | | BAM | Bosnia-Herzegovina Convertible Mark | Bosnia and Herzegovina | 2.00 BAM | | BDT | Bangladeshi Taka | Bangladesh | 100.00 BDT | | BMD | Bermudian Dollar | Bermuda | 1.00 BMD | | BND | Brunei Dollar | Brunei | 1.00 BND | | BOB | Bolivian Boliviano | Bolivia | 5.00 BOB | | BRL | Brazilian Real | Brazil | 0.50 BRL | | BSD | Bahamian Dollar | Bahamas | 1.00 BSD | | BWP | Botswanan Pula | Botswana | 15.00 BWP | | BZD | Belize Dollar | Belize | 2.00 BZD | | CAD | Canadian Dollar | Canada | 0.50 CAD | | CHF | Swiss Franc | Switzerland, Liechtenstein | 0.50 CHF | | CLP | Chilean Peso | Chile | 500 CLP | | CNY | Chinese Yuan | China | 4.00 CNY | | CRC | Costa Rican Colón | Costa Rica | 500.00 CRC | | CZK | Czech Koruna | Czech Republic | 15.00 CZK | | DKK | Danish Krone | Denmark, Greenland | 2.50 DKK | | DOP | Dominican Peso | Dominican Republic | 100.00 DOP | | EGP | Egyptian Pound | Egypt | 50.00 EGP | | ETB | Ethiopian Birr | Ethiopia | 100.00 ETB | | EUR | Euro | Austria, Belgium, Cyprus, Estonia, Finland, France, Germany, Greece, Ireland, Italy, Latvia, Lithuania, Luxembourg, Malta, Netherlands, Portugal, Slovakia, Slovenia, Spain, Andorra, Monaco, Croatia, San Marino, Montenegro | 0.50 EUR | | FJD | Fijian Dollar | Fiji | 2.00 FJD | | GBP | British Pound | United Kingdom | 0.30 GBP | | GEL | Georgian Lari | Georgia | 3.00 GEL | | GMD | Gambian Dalasi | Gambia | 100.00 GMD | | GTQ | Guatemalan Quetzal | Guatemala | 10.00 GTQ | | GYD | Guyanese Dollar | Guyana | 200.00 GYD | | HKD | Hong Kong Dollar | Hong Kong | 4.00 HKD | | HNL | Honduran Lempira | Honduras | 25.00 HNL | | HUF | Hungarian Forint | Hungary | 175.00 HUF | | IDR | Indonesian Rupiah | Indonesia | 8500.00 IDR | | ILS | Israeli New Shekel | Israel | 3.00 ILS | | INR | Indian Rupee | India | 5.00 INR | | JPY | Japanese Yen | Japan | 50 JPY | | KRW | South Korean Won | South Korea | 50 KRW | | KZT | Kazakhstani Tenge | Kazakhstan | 500.00 KZT | | LKR | Sri Lankan Rupee | Sri Lanka | 300.00 LKR | | LRD | Liberian Dollar | Liberia | 200.00 LRD | | LSL | Lesotho Loti | Lesotho | 20.00 LSL | | MAD | Moroccan Dirham | Morocco | 10.00 MAD | | MKD | Macedonian Denar | North Macedonia | 50.00 MKD | | MOP | Macanese Pataca | Macau | 10.00 MOP | | MUR | Mauritian Rupee | Mauritius | 50.00 MUR | | MVR | Maldivian Rufiyaa | Maldives | 15.00 MVR | | MWK | Malawian Kwacha | Malawi | 2000.00 MWK | | MXN | Mexican Peso | Mexico | 10.00 MXN | | MYR | Malaysian Ringgit | Malaysia | 4.00 MYR | | NGN | Nigerian Naira | Nigeria | 2000.00 NGN | | NOK | Norwegian Krone | Norway | 3.00 NOK | | NPR | Nepalese Rupee | Nepal | 150.00 NPR | | NZD | New Zealand Dollar | New Zealand | 1.00 NZD | | PEN | Peruvian Sol | Peru | 3.00 PEN | | PGK | Papua New Guinean Kina | Papua New Guinea | 4.00 PGK | | PHP | Philippine Peso | Philippines | 50.00 PHP | | PLN | Polish Zloty | Poland | 2.00 PLN | | PYG | Paraguayan Guaraní | Paraguay | 4000 PYG | | QAR | Qatari Rial | Qatar | 3.00 QAR | | RON | Romanian Leu | Romania | 2.00 RON | | RSD | Serbian Dinar | Serbia | 60.00 RSD | | SAR | Saudi Riyal | Saudi Arabia | 2.00 SAR | | SBD | Solomon Islands Dollar | Solomon Islands | 10.00 SBD | | SCR | Seychellois Rupee | Seychelles | 15.00 SCR | | SEK | Swedish Krona | Sweden | 3.00 SEK | | SGD | Singapore Dollar | Singapore | 0.50 SGD | | SZL | Swazi Lilangeni | Eswatini | 20.00 SZL | | THB | Thai Baht | Thailand | 25.00 THB | | TOP | Tongan Paʻanga | Tonga | 2.00 TOP | | TRY | Turkish Lira | Turkey | 20.00 TRY | | TWD | New Taiwan Dollar | Taiwan | 20.00 TWD | | TZS | Tanzanian Shilling | Tanzania | 3000.00 TZS | | UYU | Uruguayan Peso | Uruguay | 50.00 UYU | | VND | Vietnamese Dong | Vietnam | 12000 VND | | WST | Samoan Tala | Samoa | 2.00 WST | | XAF | Central African CFA Franc | Cameroon, Central African Republic, Chad, Republic of the Congo, Equatorial Guinea, Gabon | 300 XAF | | XOF | West African CFA Franc | Benin, Burkina Faso, Côte d'Ivoire, Guinea-Bissau, Mali, Niger, Senegal, Togo | 300 XOF | | ZAR | South African Rand | South Africa | 20.00 ZAR | | ZMW | Zambian Kwacha | Zambia | 30.00 ZMW | ## Refunds and Adjustments Dodo Payments issues refunds in the currency the customer originally paid, using the latest exchange rate. The amount in your base currency remains fixed on your dashboard, invoices, and in the refund. The customer may receive more or less than the original local-currency amount depending on FX changes. > [!NOTE] > > Adaptive Currency fees (FX fees) are not refunded. ### Example Refund 1. You sell a product for 100 USD with Adaptive Currency enabled 2. A Canadian customer sees 137 CAD at an exchange rate of 1.37 CAD per 1 USD and completes the purchase 3. Dodo Payments processes the payment, converting 137 CAD to 100 USD for your settlement 4. Later, the exchange rate changes to 1.40 CAD per 1 USD and you issue a full refund 5. Dodo Payments deducts 100 USD and refunds the customer 140 CAD ## Invoices and Taxation * Invoices show only the settlement currency amount * Taxes and platform fees are calculated on the settlement currency amount * Example: a \$10 sale converted to 36 AED still reflects as \$10 in the Dashboard and invoices > [!NOTE] > > All amounts are rounded according to Dodo Payments' internal rounding logic. ## Set Billing Currency Per Checkout Pass `billing_currency` to explicitly set the billing currency for a checkout session: > [!NOTE] > > When Adaptive Currency is disabled, `billing_currency` is ignored. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_one_time_or_subscription', quantity: 1 } ], billing_currency: 'AED', return_url: 'https://example.com/return' }); ``` ## Related Pages > [card] [Purchasing Power Parity](/features/purchasing-power-parity) > > Reduce prices by country automatically. Requires Adaptive Currency. > [card] [Charm Pricing](/features/charm-pricing) > > Round converted prices to clean endings like 49.99. Requires Adaptive Currency. > [card] [Localized Pricing](/features/localized-pricing) > > Set an exact price per country or currency instead of automatic conversion. > [card] [Tax-Inclusive Pricing](/features/tax-inclusive-pricing) > > Control whether your prices include tax. > [card] [Checkout Session](/api-reference/checkout-sessions/create) > > Create checkout sessions with billing currency configuration. # Add-ons for Subscriptions Source: https://docs.dodopayments.com/features/addons Attach add-ons to subscriptions for seat-based billing, feature upgrades, and flexible pricing. Customers choose quantities at checkout or via the API. Add-ons are supplementary products attached to subscriptions. Customers choose a quantity at checkout or when updating their subscription, and the add-on is billed on the parent subscription's cycle. > [card] [Seat-Based Billing](/developer-resources/seat-based-pricing) > > Create add-ons for additional team seats or user licenses. > [card] [Usage Extensions](/features/usage-based-billing/introduction) > > Extend usage limits, API calls, or data allowances with add-ons. ## What Are Add-ons? Add-ons are supplementary products that customers can purchase alongside their main subscription. They're perfect for seat-based billing, feature upgrades, usage extensions, and service add-ons. ![Add-ons attached to subscription products in the dashboard](https://mintcdn.com/dodopayments/ajOhO6Du1yNsg0hy/images/cookbooks/seat-based/seat-based-addons.png?fit=max\&auto=format\&n=ajOhO6Du1yNsg0hy\&q=85\&s=ea4ce0d437201c92590eea6c31a14e80) ## Key Benefits Add-ons enable flexible pricing models, revenue optimization through upsell opportunities, simplified management from one dashboard, and customer choice in customizing their subscriptions. ## Creating Add-ons Add-ons are created as separate products in the dashboard, then attached to subscription products. This lets you reuse add-ons across multiple subscriptions and manage pricing independently. ![Creating add-ons in the dashboard interface](https://mintcdn.com/dodopayments/ajOhO6Du1yNsg0hy/images/cookbooks/seat-based/seat-based-addons-creation.png?fit=max\&auto=format\&n=ajOhO6Du1yNsg0hy\&q=85\&s=d2c17b4a9f2f9a1b19f537f0507656a4) ### Add-on Configuration When creating add-ons, you can configure: * **Pricing**: Set the add-on amount (`price`) in the smallest currency unit. The add-on is billed on the parent subscription's cycle * **Currency**: Set the base price in any currency Dodo Payments can charge. The searchable currency selector pins **USD, GBP, EUR, and INR** to the top; customers outside your base currency are billed through [Adaptive Currency](/features/adaptive-currency) * **Quantity**: Customers choose a quantity when the add-on is attached to a subscription * **Availability**: Attach the add-on to subscription products through each product's `addons` list. The add-on itself has no availability setting * **Tax settings**: Configure the appropriate `tax_category` ### Getting Started Ready to implement add-ons in your subscription business? Here's how to get started: **1. Plan Your Add-ons** Identify the additional features, services, or capacity that would benefit your customers as add-ons. Consider: * What do customers frequently request? * What features could be monetized separately? * What would create natural upgrade paths? **2. Create Your First Add-on** Use the Dodo Payments dashboard or API to create your first add-on product. > [card] [Dashboard Guide](/developer-resources/seat-based-pricing) > > Follow our step-by-step guide to create add-ons in the dashboard. **3. Attach to Subscriptions** Connect your add-ons to the appropriate subscription products where they should be available. **4. Test Integration** Create test checkout sessions with different add-on combinations to ensure everything works correctly. **5. Monitor Performance** Track add-on adoption rates and revenue impact to optimize your pricing strategy. ## Common Use Cases * **Seat-based billing**: Additional team members, user licenses, or concurrent users * **Feature upgrades**: Premium features, advanced analytics, or priority support * **Usage extensions**: Extra storage, API calls, or bandwidth allowances * **Service add-ons**: Professional services, training, or consultation hours ## Integration Examples ### Checkout Sessions with Add-ons When creating a checkout session, include add-ons with quantities: ```typescript Node.js theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1, addons: [ { addon_id: 'addon_456', quantity: 3 // 3 additional seats } ] } ], customer: { email: 'customer@example.com' }, return_url: 'https://yourapp.com/success' }); ``` ```python Python theme={null} session = client.checkout_sessions.create( product_cart=[ { "product_id": "pdt_123", "quantity": 1, "addons": [ { "addon_id": "addon_456", "quantity": 3 # 3 additional seats } ] } ], customer={"email": "customer@example.com"}, return_url="https://yourapp.com/success" ) ``` ```bash cURL theme={null} curl -X POST https://test.dodopayments.com/checkouts \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "product_cart": [ { "product_id": "pdt_123", "quantity": 1, "addons": [ { "addon_id": "addon_456", "quantity": 3 } ] } ], "customer": {"email": "customer@example.com"}, "return_url": "https://yourapp.com/success" }' ``` > [!TIP] > > To let customers add or remove add-ons themselves on the checkout page, set the [`allow_editing_addons`](/developer-resources/checkout-session#optional-fields) feature flag to `true` when creating the session. It defaults to `false` and applies only to subscription products. > > ```typescript theme={null} > const session = await client.checkoutSessions.create({ > product_cart: [{ product_id: 'pdt_123', quantity: 1 }], > feature_flags: { > allow_editing_addons: true // customers can edit add-ons at checkout > }, > }); > ``` ### Plan Changes with Add-ons Modify existing subscriptions to add, remove, or update add-ons: ```typescript Node.js theme={null} // Add add-ons to existing subscription await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_new', quantity: 1, proration_billing_mode: 'difference_immediately', addons: [ { addon_id: 'addon_123', quantity: 2 } ] }); // Remove all existing add-ons await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_new', quantity: 1, proration_billing_mode: 'difference_immediately', addons: [] // Empty array removes all existing add-ons }); ``` ```python Python theme={null} # Add add-ons to existing subscription client.subscriptions.change_plan( 'sub_123', product_id='pdt_new', quantity=1, proration_billing_mode='difference_immediately', addons=[ {'addon_id': 'addon_123', 'quantity': 2} ] ) # Remove all existing add-ons client.subscriptions.change_plan( 'sub_123', product_id='pdt_new', quantity=1, proration_billing_mode='difference_immediately', addons=[] ) ``` ### Dynamic Pricing Calculate total costs dynamically based on add-on selections: ```typescript theme={null} interface AddonSelection { price: number; quantity: number; } function calculateTotalCost(basePrice: number, addons: AddonSelection[]) { const addonTotal = addons.reduce((sum, addon) => sum + (addon.price * addon.quantity), 0 ); return basePrice + addonTotal; } ``` ## API Management Dodo Payments provides a comprehensive API for managing add-ons programmatically: > [accordion] Create Add-ons > > Use the `POST /addons` endpoint to create new add-ons with custom pricing, descriptions, and configuration options. > > > [card] [API Reference](/api-reference/addons/create-addon) > > > > View the complete API documentation for creating add-ons. > [accordion] Update Add-ons > > Modify existing add-ons using the `PATCH /addons/{id}` endpoint to update pricing, descriptions, or tax categories. > > > [card] [API Reference](/api-reference/addons/update-addon) > > > > Learn how to update add-on details programmatically. > [accordion] List and Retrieve > > Use `GET /addons` to list all add-ons or `GET /addons/{id}` to retrieve specific add-on details. > > > [card] [API Reference](/api-reference/addons/list-addons) > > > > Access the complete listing and retrieval API documentation. > [accordion] Image Management > > Update add-on images using the `PUT /addons/{id}/images` endpoint for better product presentation. > > > [card] [API Reference](/api-reference/addons/update-addon-images) > > > > Learn how to manage add-on images via API. > [accordion] Archive and Unarchive > > Use `DELETE /addons/{id}` to archive an add-on and `POST /addons/{id}/unarchive` to restore it. List archived add-ons with `GET /addons?archived=true`. > > > [card] [API Reference](/api-reference/addons/archive-addon) > > > > Learn how to archive add-ons programmatically. ## Archiving Add-ons Archive an add-on to stop offering it. To archive an add-on in the dashboard, open the add-on's row menu and select **Archive**. * Archiving removes the add-on from every product it is attached to. * Existing subscriptions keep the add-on and continue to renew with it. * An archived add-on can't be attached to a product. A product create or update with an archived add-on ID returns `422` with the `MISSING_ADDON_IDS` error code. To restore an add-on, click **View archived add-ons** on the add-ons page, then select **Unarchive**. Unarchiving doesn't attach the add-on to products again, so add it back to each product that should offer it. ## Best Practices * **Start simple**: Launch with 2-3 core add-ons and expand options based on customer feedback and usage. * **Maintain pricing clarity**: Clearly communicate add-on pricing and value, so customers understand what they're getting for the extra cost. * **Test thoroughly**: Validate add-on combinations to ensure pricing calculations remain accurate and checkout flows function smoothly. ### Design Considerations * **Clear Value Proposition**: Each add-on should have a clear benefit that customers can understand * **Logical Grouping**: Group related add-ons together in your checkout flow * **Flexible Quantities**: Allow customers to adjust quantities of add-ons as needed * **Transparent Pricing**: Show total costs clearly throughout the checkout process ## Related > [card] [Seat-Based Billing](/developer-resources/seat-based-pricing) > > Guide to implementing per-seat pricing with add-ons. > [card] [Checkout Sessions](/developer-resources/checkout-session) > > Full checkout session API and configuration. > [card] [Subscriptions](/features/subscription) > > Subscription lifecycle, billing cycles, and renewal. > [card] [Adaptive Currency](/features/adaptive-currency) > > Show prices in local currencies at checkout. # Affiliates Source: https://docs.dodopayments.com/features/affiliates Run an affiliate program on Dodo Payments with Affonso, Dub Partners, or Rekomi to track referrals, attribute sales, and calculate affiliate commissions. ## Introduction Run an affiliate program while Dodo Payments processes your sales. An affiliate platform tracks referral visits, receives payment events from Dodo Payments through webhooks, and credits each sale to the affiliate who referred it. Dodo Payments integrates with three affiliate platforms: **Affonso**, **Dub Partners**, and **Rekomi**. ## Key Features > [card] Automated Commission Attribution > > Referrals are attributed and logged automatically when a purchase is made, with no spreadsheets or manual tracking. > [card] Real-Time Reporting > > You and your affiliates can monitor performance and leads from dedicated dashboards. > [card] Flexible Tracking Options > > Use tracking scripts, metadata fields, and webhook events to capture referral data across signups and transactions. > [card] Encrypted Credentials and Signed Webhooks > > Affonso encrypts the API key you give it, and every webhook event is signed so the platform can verify that it came from Dodo Payments. > [card] Quick Setup > > Setup takes an API key, a webhook, and a tracking script. The only code you add is the script snippet and the referral metadata at checkout. > [card] Checkout Integration > > Add affiliate tracking to your checkout flows with the Affonso, Dub Partners, and Rekomi integrations. ## Integration Options Dodo Payments integrates with these affiliate management platforms: * **[Affonso](https://affonso.io)**: An affiliate management platform with automated commission tracking, real-time reporting, and dedicated affiliate dashboards. * **[Dub Partners](https://dub.co)**: Dub's link management and conversion tracking, with attribution analytics for each affiliate link. * **[Rekomi](https://rekomi.com)**: An affiliate tracking and management platform with a one-paste Dodo Payments connection. Rekomi also pays your affiliates and handles their tax forms. Choose the platform that fits your program, or combine several for different use cases. ## Affonso Integration Affonso is an affiliate management platform that partners with Dodo Payments. To connect your Dodo Payments account to Affonso and start tracking affiliate-driven sales, follow these steps. [Affiliate Integration | Dodo Payments](https://www.youtube.com/embed/8tw8o9yOjsA) **1. Connect with Dodo Payments** To connect your Dodo Payments account, add a Dodo Payments API key to Affonso. ### How to Get Your Dodo Payments API Key 1. Log in to the Dodo Payments dashboard. 2. Go to **Developer → API Keys**. 3. Click **Create New Key**. 4. Enter a **Key Name**, for example "Affonso Integration". 5. Use **Select all** and choose **Write**. 6. Click **Create Key**, then copy your API key. The dashboard shows the key only once. ### Add Your API Key to Affonso 1. Open your Affonso dashboard at [affonso.io](https://affonso.io/). 2. Go to **Program Details > Connect**. 3. Click the **Dodo Payments** integration card. 4. Paste your Dodo Payments API key. 5. Click **Connect**. > [!NOTE] > > Affonso encrypts your API key. **2. Add Webhook to Dodo Payments** After you connect, Affonso gives you a unique webhook URL. Dodo Payments sends payment events to this URL, and Affonso uses them to track payments and trigger affiliate commissions. ### Add Webhook URL in Dodo Payments 1. In the Dodo Payments dashboard, go to **Developer → Webhooks**. 2. Click **Add endpoint**. 3. Paste your Affonso webhook URL from your Affonso program settings. 4. Click **Create endpoint**. ### Add Webhook Secret in Affonso 1. In Dodo Payments, open the endpoint you created and copy its **Signing secret**. 2. Paste it into Affonso under the Dodo Payments webhook settings. > [!NOTE] > > Affonso uses the signing secret to verify that incoming events come from Dodo Payments. **3. Add the Tracking Script** To track affiliate visits and conversions, add the Affonso pixel to your site. Replace `YOUR_PUBLIC_PROGRAM_ID` with your Affonso program ID and `YOUR_COOKIE_DURATION` with how long the referral cookie lasts. ```html theme={null} ``` The script: * Tracks affiliate visits. * Sets a cookie with the referral ID (`affonso_referral`) and exposes it as `window.affonso_referral`. * Enables signup and payment tracking. > [!NOTE] > > Add the script to every domain where users visit or convert, such as your marketing site and your app. **4. Track User Signups** To see your full funnel and improve affiliate performance, track user signups as leads. ```js theme={null} // After successful registration. userEmail is the new user's email address. window.Affonso.signup(userEmail); ``` This call: * Logs a new referral as a **LEAD** if the user came through an affiliate link. * Shows the lead in your dashboard and in the affiliate's stats. > [!NOTE] > > Call it after a successful registration or after double opt-in (DOI). **5. Pass Referral Data to Dodo Payments** To attribute commissions correctly, pass the Affonso referral ID to Dodo Payments at checkout as `affonso_referral` metadata. Read `window.affonso_referral` in the browser, then send it to your server, where your API key is available. ### Checkout Session Integration The same call works for one-time and subscription products. Put the subscription product's ID in `product_cart` to start a subscription. ```js theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], }); // Runs on your server. referralId is window.affonso_referral from the browser. async function createCheckout(referralId) { const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], customer: { email: 'customer@example.com', name: 'John Doe' }, return_url: 'https://example.com/success', metadata: { affonso_referral: referralId, }, }); console.log(session.checkout_url); } ``` ### Payment Links ```js theme={null} // Original Dodo Payments link const originalLink = 'https://checkout.dodopayments.com/buy/pdt_123'; // Append the referral ID as metadata const linkWithReferral = `${originalLink}?metadata_affonso_referral=${window.affonso_referral}`; ``` > [!NOTE] > > For more details, see the [Dodo Payments API documentation](/api-reference/introduction). **6. Testing Your Integration** Before you launch publicly, test your setup with live affiliate links and test transactions. Work through this checklist: 1. Create an affiliate and generate a tracking link. 2. Visit your website through the affiliate link. 3. Check that the Affonso script loads and sets the `affonso_referral` cookie. 4. Complete a signup (optional). 5. Complete a payment through Dodo Payments. 6. Confirm the tracking and attribution in your Affonso dashboard. ## Dub Partners Integration You can also use [Dub Partners](https://dub.co) to track affiliate referrals and conversions. Dub's conversion tracking attributes sales to your affiliate links, so you can see which partners drive the most revenue. > [!NOTE] > > For detailed setup instructions, see the [Dub integration guide](/integrations/dub). It covers how to track sale conversion events and attribute revenue to your affiliate links. ### Quick Setup with Dub Partners 1. **Enable conversion tracking** in your Dub dashboard for affiliate links. 2. **Capture the Dub click ID** (`dub_id` cookie) when you create checkout sessions. 3. **Store the click ID** in payment metadata, along with customer information. 4. **Configure the webhook integration** to send sale data to Dub when payments succeed. The integration tracks these events automatically: * One-time payments * Subscription activations * Recurring subscription payments > [card] [Learn More](/integrations/dub) > > The complete Dub integration guide, with code examples and transformation templates. ## Rekomi Integration You can also use [Rekomi](https://rekomi.com) to run your affiliate program end to end. Rekomi tracks clicks and conversions, calculates commissions on the pre-tax sale amount, and pays your affiliates in 130+ countries, including their tax forms. > [!NOTE] > > For detailed setup instructions, see the [Rekomi integration guide](/integrations/rekomi). The connection is a single pasted API key: Rekomi creates the webhook endpoint in your Dodo Payments account itself, so there is no manual webhook setup. ### Quick Setup with Rekomi 1. **Create an API key** in your Dodo Payments dashboard under **Developer → API Keys**, with **Write** access to every resource. Use **Select all** and choose **Write**. 2. **Paste the key into Rekomi**, which validates it and creates the webhook endpoint automatically. 3. **Install the Rekomi tracking script** on your site so affiliate clicks are captured. 4. **Pass the referral** into checkout as `rekomi_ref` metadata, or as the `metadata_rekomi_ref` payment link parameter. The integration tracks these events automatically: * One-time payments * Subscription activations and renewals * Refunds and disputes, with automatic commission clawback > [card] [Learn More](/integrations/rekomi) > > The complete Rekomi integration guide, with code examples for checkout sessions and payment links. ## Need Help? If you run into issues during integration, contact the platform involved: > [card] Affonso Support > > * Use the live chat on [affonso.io](https://affonso.io/). > * Email **[support@affonso.io](mailto:support@affonso.io)**. > [card] Dub Support > > * Read the [Dub documentation](https://dub.co/docs) for conversion tracking guides. > * Contact Dub support through the [Dub dashboard](https://app.dub.co). > [card] Rekomi Support > > * Read the [Rekomi documentation](https://rekomi.com/docs) for setup and troubleshooting guides. > * Email **[support@rekomi.com](mailto:support@rekomi.com)**, or use the live chat in the [Rekomi dashboard](https://app.rekomi.com). > [card] Dodo Payments Support > > For questions about the Dodo Payments API, see the [API reference](/api-reference/introduction) or email **[support@dodopayments.com](mailto:support@dodopayments.com)**. > [card] Integration Guides > > * [Affonso Integration](#affonso-integration) (on this page) > * [Dub Partners Integration](/integrations/dub) > * [Rekomi Integration](/integrations/rekomi) # Third-Party Analytics Source: https://docs.dodopayments.com/features/analytics Track page views and e-commerce events on your Dodo Payments storefront, checkout, and Customer Portal with Google Analytics 4, Google Tag Manager, and Meta Pixel. ![Third-party analytics integrations for Dodo Payments hosted pages](https://mintcdn.com/dodopayments/OJISfHo1pPGtWHk9/images/analytics-cover.png?fit=max\&auto=format\&n=OJISfHo1pPGtWHk9\&q=85\&s=6f9b234fb9bb78755cd79b315e594826) Follow each customer from your storefront through checkout to a completed purchase. Dodo Payments sends events from your hosted pages to Google Analytics 4, Google Tag Manager, and Meta Pixel. Tracking turns on for your Storefront, checkout pages, and Customer Portal as soon as you add a tracking ID in the dashboard. > [!WARNING] > > Ad blockers in customer browsers can stop tracking for some visitors to your store. ## Supported Platforms > [card] Google Analytics 4 > > Page views and e-commerce tracking with GA4. > [card] Google Tag Manager > > Add and manage marketing tags. > [card] Meta Pixel > > Track Facebook and Instagram ad conversions. ## Getting Started You need an ID from at least one platform: a Google Analytics 4 Measurement ID, a Google Tag Manager Container ID, or a Meta Pixel ID. **1. Open Tracking Integrations** In the Dodo Payments dashboard, go to **Settings → Tracking Integrations**. **2. Enable Your Tracking Platform** Turn on the toggle for the platform you want to use, then enter its tracking ID: * **Google Analytics**: your Measurement ID, which starts with `G-` (format: `G-XXXXXXXXXX`). * **Google Tag Manager**: your Container ID, which starts with `GTM-` (format: `GTM-XXXXXXX`). * **Meta Pixel**: your Pixel ID, a number of 10 to 20 digits. **3. Save Your Settings** Click **Save** next to the ID. To change a saved ID, click **Edit**. To stop tracking, turn the toggle off, which removes the ID. **4. Verify Tracking** Open your storefront or a test checkout, then confirm that the events arrive in your analytics dashboard. ## Google Analytics 4 [Google Analytics 4](https://marketingplatform.google.com/about/analytics/) reports web traffic and e-commerce activity. With your Measurement ID added, it records the customer journey from browsing your store to completing a purchase. ### Add Your Google Analytics Measurement ID 1. In Google Analytics, go to **Admin** → **Data Streams** and select your web stream. 2. Copy the **Measurement ID**, which starts with `G-`. 3. In the Dodo Payments dashboard, go to **Settings → Tracking Integrations**. 4. Turn on **Google Analytics** and paste your Measurement ID. 5. Click **Save**. > [!TIP] > > If you don't have a Google Analytics property yet, follow [Google's setup guide](https://support.google.com/analytics/answer/9304153) to create one. ### Events Tracked in Google Analytics Dodo Payments sends these events from your hosted storefront and checkout pages. Events carry product details, amounts, and currency where they apply. #### Storefront Events | Event | Description | | - | - | | `view_item_list` | Fires when the storefront page loads with products. | | `select_item` | Fires when a customer clicks a product to start checkout. | #### Checkout Events | Event | Description | | - | - | | `view_item` | Fires when the checkout page loads. | | `apply_discount`\* | Fires when a valid discount code is applied. | | `remove_discount`\* | Fires when a discount code is removed. | | `add_payment_info` | Fires when the customer submits the payment form. | | `purchase` | Fires when the payment succeeds. | > [!NOTE] > > `apply_discount` and `remove_discount` are custom events. They aren't part of the [standard Google Analytics e-commerce events](https://support.google.com/analytics/answer/9267735). ### Using GA4 with Overlay/Inline Checkout To track Google Analytics events in overlay or inline checkout on your own website, install the Google Analytics tracking code on the page where you embed checkout. The embedded checkout then sends the checkout events listed above to your Google Analytics property. No other configuration is needed. ## Google Tag Manager [Google Tag Manager](https://marketingplatform.google.com/about/tag-manager/) manages marketing and analytics tags without code changes. Dodo Payments loads your GTM container on your storefront, checkout, and Customer Portal pages, so the tags you publish in the container fire there. The payment status page, which reports the `purchase` event, doesn't load your GTM container. ### Add Your GTM Container ID 1. In Google Tag Manager, copy your **Container ID**, which starts with `GTM-`. 2. In the Dodo Payments dashboard, go to **Settings → Tracking Integrations**. 3. Turn on **Google Tag Manager** and paste your Container ID. 4. Click **Save**. > [!NOTE] > > You can add more tracking in your GTM container, such as Google Ads conversions. Dodo Payments injects both the GTM script and its `noscript` fallback. ### Using GTM with Overlay/Inline Checkout For overlay or inline checkout embedded on your website, install GTM on your own site. The embedded checkout loads the Container ID saved in your dashboard and fires its events inside the checkout frame. ## Meta Pixel [Meta Pixel](https://www.facebook.com/business/tools/meta-pixel/) tracks customer actions on your store, so you can measure your Facebook and Instagram ad campaigns from ad click to completed purchase. ### Add Your Meta Pixel ID 1. In [Meta Events Manager](https://www.facebook.com/events_manager2/), create or select your Pixel. 2. Copy the **Pixel ID**, a number that is typically 15 or 16 digits long. 3. In the Dodo Payments dashboard, go to **Settings → Tracking Integrations**. 4. Turn on **Meta Pixel** and paste your Pixel ID. 5. Click **Save**. > [!TIP] > > If you haven't created a Pixel yet, follow Meta's [Pixel setup guide](https://www.facebook.com/business/help/952192354843755). ### Events Tracked with Meta Pixel These events appear in your [Meta Events Manager](https://www.facebook.com/events_manager2/). Events carry content IDs, values, and currency where they apply. > [!NOTE] > > Events can take several minutes to appear in Meta Events Manager. #### Storefront Events | Event | Description | | - | - | | `PageView` | Fires when the storefront page loads. | | `ViewContent` | Fires when the storefront loads with products. | | `InitiateCheckout` | Fires when a customer clicks a product to start checkout. | #### Checkout Events | Event | Description | | - | - | | `PageView` | Fires when the checkout page loads. | | `AddToCart` | Fires when the checkout loads. | | `ApplyDiscount`\* | Fires when a valid discount code is applied. | | `RemoveDiscount`\* | Fires when a discount code is removed. | | `AddPaymentInfo` | Fires when the customer submits the payment form. | | `Purchase` | Fires when the payment succeeds. | > [!NOTE] > > `ApplyDiscount` and `RemoveDiscount` are custom events. They aren't part of [Meta's standard events](https://developers.facebook.com/docs/meta-pixel/reference#standard-events). ## Complete Events Reference This table maps each trigger to its Google Analytics 4 and Meta Pixel events: | Trigger | GA4 Event | Meta Pixel Event | Location | | - | - | - | - | | Page loads | - | `PageView` | Storefront and Checkout | | Storefront page loads | `view_item_list` | `ViewContent` | Storefront | | Customer clicks product | `select_item` | `InitiateCheckout` | Storefront | | Checkout page loads | `view_item` | `AddToCart` | Checkout | | Discount code applied | `apply_discount` | `ApplyDiscount` | Checkout | | Discount code removed | `remove_discount` | `RemoveDiscount` | Checkout | | Payment form submitted | `add_payment_info` | `AddPaymentInfo` | Checkout | | Payment successful | `purchase` | `Purchase` | Checkout | ## Platform Coverage Tracking support differs by Dodo Payments surface: | Surface | Google Analytics 4 | Google Tag Manager | Meta Pixel | | - | - | - | - | | Storefront | Yes | Yes | Yes | | Checkout (Hosted) | Yes | Yes | Yes | | Checkout (Overlay/Inline)\* | Yes | Yes | Yes | | Customer Portal | Yes | Yes | No | > [!NOTE] > > \*For overlay and inline checkout, install the tracking code on your own website for full attribution. The embedded checkout tracks its own events automatically. ## Event Data Included Each event carries the e-commerce data you need to analyze customer behavior. Amounts are in major currency units, for example `10.5` for \$10.50. ### Product Data * Product ID * Product name * Price * Currency * Quantity ### Transaction Data (Purchase Events) * Payment ID, sent as the transaction ID * Total amount * Tax amount * Currency Purchase events don't include the discount code. The code is sent only with the `ApplyDiscount` and `RemoveDiscount` events. ### Customer Data Events don't include customer data. Dodo Payments sends no customer ID and no email address to Google Analytics, Google Tag Manager, or Meta Pixel. ## Best Practices > [accordion] Test Your Integration > > After you add your tracking IDs, open your storefront and complete a test checkout, then confirm that the events appear in your analytics dashboards. Use the Google Analytics Realtime report or the Test Events tool in Meta Events Manager. > [accordion] Use UTM Parameters > > Add UTM parameters to your marketing links to see which campaigns drive conversions. > [accordion] Set Up Conversion Goals > > In Google Analytics, create a conversion event for `purchase` to track your conversion rate. In Meta Ads Manager, use the `Purchase` event as the optimization goal for your campaigns. > [accordion] Enable Enhanced E-commerce > > If you use Google Tag Manager, consider setting up Enhanced E-commerce reports for funnel analysis and product performance metrics. ## Troubleshooting > [accordion] Events not appearing in Google Analytics > > * Check that your Measurement ID is correct (format: `G-XXXXXXXXXX`). > * Check the Google Analytics Realtime report, where events appear first. > * Confirm that the **Google Analytics** toggle is on in **Settings → Tracking Integrations**. > * Wait a few minutes, because Google Analytics can take time to process events. > * Test in a private browser window to rule out ad blockers. > [accordion] Events not appearing in Meta Events Manager > > * Check that your Pixel ID is correct: a number of 10 to 20 digits. > * Debug with the Meta Pixel Helper browser extension. > * Check the **Test Events** tab in Events Manager. > * Wait several minutes, because events can take that long to appear. > * Turn off ad blockers while you test. > [accordion] GTM tags not firing > > * Check that your Container ID is correct (format: `GTM-XXXXXXX`). > * Debug tag firing with GTM Preview mode. > * Check that the triggers in your GTM container are configured correctly. > * Confirm that the container is published, not only saved as a draft. > [accordion] Overlay/Inline checkout not tracking > > * Install the tracking code on your own website first. > * Make sure the tracking code loads before the checkout overlay opens. > * Check the browser console for JavaScript errors. > * If you use GA4, check that cross-domain tracking is configured. > [accordion] Purchase events showing wrong amounts > > * Amounts are sent in major currency units, for example `10.5` for \$10.50, not in the smallest currency unit. > * Check that your analytics tool displays the correct currency. > * Check whether tax is included or excluded as you expect. The `purchase` event reports tax in its own `tax` field. ## Related Resources > [card] [Segment Integration](/integrations/segment) > > Send payment events to Segment for analytics and customer data platform workflows. > [card] [Dub Integration](/integrations/dub) > > Track sale conversions and affiliate attribution with Dub. > [card] [Customer.io Integration](/integrations/customer-io) > > Trigger automated email campaigns from payment events. > [card] [Webhooks](/developer-resources/webhooks) > > Build custom analytics integrations with webhook events. # Dashboard Analytics Source: https://docs.dodopayments.com/features/analytics-and-reporting Track revenue, customers, subscriptions, retention, payment success, and recovery in the Dodo Payments dashboard, for your whole business or for one product. ![Analytics and Reporting dashboard overview](https://mintcdn.com/dodopayments/r426DlzEVUSPZlYb/images/cover-images/Analytics%20and%20Reporting.webp?fit=max\&auto=format\&n=r426DlzEVUSPZlYb\&q=85\&s=bae83b093bf129bcab92988d2f85fbe2) ## Introduction Dashboard analytics show how your business performs: revenue, customers, subscriptions, retention, payment success, and recovered revenue. **Home** gives you a quick daily view. **Analytics** holds the full set of metrics, with filters for period, comparison, and product. > [card] [Home](#home) > > Today's activity (**Today**) plus an overview you can customize. > [card] [Business Analytics](#analytics) > > Revenue, customers, subscriptions, retention, transaction health, and recovery across your business. > [card] [Product-Level Analytics](#product-level-analytics) > > The same metrics for one product: revenue, customers, churn, subscribers, and MRR. > [card] [Page Highlight Tiles](#page-highlight-tiles) > > Summary metrics at the top of your products, subscriptions, payments, and other list pages. > [card] [Reports](/features/reports) > > Reconcile your balance, review every fee, and export any date range as CSV or XLSX. ![Dashboard Analytics Home page showing the Today pulse and a customizable overview of key business metrics](https://mintcdn.com/dodopayments/8P4fvt_KSsKSfwZl/images/analytics/home.png?fit=max\&auto=format\&n=8P4fvt_KSsKSfwZl\&q=85\&s=d4678ae6716875ad95a17e2d91c4b53a) The Home dashboard: a daily pulse plus a customizable overview ## Home **Home** is your landing page in the sidebar. It has two sections: **Today** and **Overview**. ### Today ![Home Today view with an hourly volume chart, cash position, and next payout tiles](https://mintcdn.com/dodopayments/8P4fvt_KSsKSfwZl/images/analytics/home-today.png?fit=max\&auto=format\&n=8P4fvt_KSsKSfwZl\&q=85\&s=aba02c05900a0e040ca3c6f04710113c) Today: your day's pulse, hour by hour **Today** shows the current day's activity, hour by hour. * **Headline chart:** Switch between **Net Volume** and **Gross Volume**. It defaults to **Net Volume** and plots each hour against the same hour yesterday. To compare against a different day, pick a date. * **Cash Position:** The funds available in your balance. It follows the mode you're in, so test mode and live mode show different balances. * **Next Payout:** The amount and date of your next payout. It always shows live mode data, even in test mode. > [!NOTE] > > Each card has an info tooltip (ⓘ) and an "Updated" timestamp, so you can see how recent the data is. ### Your Overview ![Home Your overview view with customizable cards for revenue by country, payouts received, top customers by spend, and refunds](https://mintcdn.com/dodopayments/8P4fvt_KSsKSfwZl/images/analytics/home-overview.png?fit=max\&auto=format\&n=8P4fvt_KSsKSfwZl\&q=85\&s=4d7c7f48fa1c4599ea767c6cbdf10d7e) Your overview: a fully customizable set of metric cards **Overview** is a grid of metric cards you choose. To change it, click **Customise**. In **Customise Your Layout**, you can drag cards to reorder them, remove cards, and select which metrics each section shows. Your layout is saved for each business. * **Default cards:** **Gross Volume**, **Net Volume**, **Refunds**, **New Customers**, **Top Customers by Spend**, **Average Order Value**, **Revenue By Country**, and **Payment Success Rate**. * **Controls:** * **Period:** A preset range such as **Last 30 days**, or a custom date range. * **Compare:** **Previous Period** (the default), **Previous Week**, **Previous Month**, or **Previous Year**. * **Product:** One or more products. Defaults to **All Products**. ## Analytics Open **Analytics** from the sidebar, directly below **Home**, to analyze your entire business. It has six tabs, and each tab has its own filters. > [card] Revenue > > Gross and net volume, payouts, refunds, disputes, and top markets. > [card] Customers > > Active and new customers, ARPU, top customers, and modeled LTV. > [card] Subscriptions > > MRR, Projected ARR, active subscriptions, and the full MRR breakdown. > [card] Retention > > Customer and revenue churn, NRR and GRR, cohorts, and trial conversion. > [card] Success Rate > > Payment and refund success rates with failure-reason analysis. > [card] Recovery > > Payment retries, dunning, and abandoned cart recovery performance. ### Filtering & Customization Each tab has a filter bar with these controls: * **Time Period:** A preset range (**Today**, **Last 7 days**, **Last 30 days**, **Last 6 months**, **1 year**, **This month**, **This quarter**, **This year**, or **All time**) or a custom date range. New dashboards start on **Last 30 days**. **This month**, **This quarter**, and **This year** chart the whole period, with the current line stopping at today. * **Interval:** For longer ranges, switch the charts between **Daily**, **Weekly**, and **Monthly** points with the toggle next to the date picker. The options depend on the range: for example, **Last 30 days** offers Daily and Weekly, and **All time** offers Weekly and Monthly. The interval isn't saved with your date range. * **Compare:** **Previous Period** (the default), **Previous Week**, **Previous Month**, or **Previous Year**. Comparison is unavailable on **All time**, because there is no earlier window to compare against. * **Product:** Multi-select, defaults to **All Products**. It filters the Revenue, Customers, Subscriptions, and Retention tabs. **Payouts Received**, **Refunds**, **Disputes**, and most Success Rate and Recovery cards always cover every product. Dodo Payments remembers your date range and compare selections for each business and syncs them to your profile. Switching businesses, returning later, or signing in on another device keeps each business on the window you last used. The product filter isn't saved and resets in each session. > [!TIP] > > Use filters to focus on specific products or time periods. ### Revenue Tab ![Revenue tab showing gross volume, net volume, payouts received, and refunds cards with trend charts](https://mintcdn.com/dodopayments/8P4fvt_KSsKSfwZl/images/analytics/revenue-tab.png?fit=max\&auto=format\&n=8P4fvt_KSsKSfwZl\&q=85\&s=05e52b0d85dcb7f87a4ec0796604e00e) Revenue tab: gross/net volume, payouts, and refunds Track income, payouts, and dispute activity to see revenue trends and your top markets. | Metric | Description | | - | - | | **Gross Volume** | Total amount charged across all successful payments in the period, before fees, refunds, or disputes are removed. | | **Net Volume** | Net volume = gross volume − fees − refunds − lost disputes. | | **Payouts Received** | Payout = eligible sales − taxes − fees − refunds − chargebacks. | | **Refunds** | Refund rate = refunded amount ÷ gross volume. | | **Disputes** | The headline is the chargeback rate, gross of outcome. Every chargeback received counts, so chargebacks you later win, or that are withdrawn, don't lower it. Card networks judge risk the same way. Won, lost, and pending disputes are shown as counts for context and compared across the two periods. Chargeback rate = chargebacks received ÷ payments. | | **Payments Count** | Count of payments with a Successful status. In-progress, failed, and not-initiated attempts are excluded. | | **Payments Breakdown** | Splits attempts into total, success, failed (network), failed (customer), and not initiated. | | **Average Order Value** | AOV = revenue ÷ number of orders, across one-time and usage-based products. | | **Revenue by Product** | Gross revenue attributed to each product, ranked from highest to lowest. | | **Revenue By Country** | Revenue attributed to each country, based on the customer's billing country. A full-width card pairs a world map with the ranked country list, and darker countries earned more. The top 150 countries are listed individually, and any remaining countries are grouped into one "Others" row. | ### Customers Tab ![Customers tab showing active customers, new customers, ARPU, and top customers by spend](https://mintcdn.com/dodopayments/8P4fvt_KSsKSfwZl/images/analytics/customers-tab.png?fit=max\&auto=format\&n=8P4fvt_KSsKSfwZl\&q=85\&s=ec5027add00c9429797d4df46e1c50d0) Customers tab: active and new customers, ARPU, and top customers Analyze customer acquisition, retention, and spending patterns. | Metric | Description | | - | - | | **Active Customers** | Customers who made a payment or held an active subscription at any point in the period. | | **New Customers** | Customers whose first successful payment with you falls in this period. | | **ARPU** | ARPU = revenue ÷ active customers. | | **Top Customers by Spend** | Customers ranked by revenue in the period, highest first. Each entry shows the customer's name, or their email address when no name is on record. | | **New VS Returning** | New = first purchase in this period. Returning = purchased with you in an earlier period. | | **LTV (model)** | Modeled revenue from a customer before they churn. LTV = ARPU ÷ subscriber churn rate, with both on a monthly basis. | ### Subscriptions Tab Monitor your recurring revenue and see how your Monthly Recurring Revenue (MRR) changes over time. | Metric | Description | | - | - | | **Current MRR** | Recurring revenue expected in a month, with every plan converted to monthly (a yearly plan counts as 1/12). One-time payments are excluded. | | **Projected ARR** | Projected ARR = current MRR × 12. | | **Net New MRR** | Net New MRR = New + Expansion − Contraction − Churned. | | **Active Subscriptions** | Subscriptions that are billing, including those still in a trial. | | **New MRR** | MRR added by brand-new subscriptions in the period. | | **Expansion MRR** | Extra MRR from existing customers upgrading or buying add-ons. | | **Contraction MRR** | MRR lost when existing customers move to a cheaper plan but stay subscribed. | | **Churned MRR** | MRR lost when customers cancel their subscriptions in the period. | > [!NOTE] > > MRR counts each subscription separately, so a customer with **concurrent subscriptions** adds all of them. Each subscription adds its recurring amount, including add-ons, converted to a monthly rate. Trials add nothing until they convert, and usage-based subscriptions add only their fixed base price. ### Retention Tab ![Retention tab showing the user retention cohort matrix, customer churn rate, revenue churn rate, and net revenue retention](https://mintcdn.com/dodopayments/8P4fvt_KSsKSfwZl/images/analytics/retention-tab.png?fit=max\&auto=format\&n=8P4fvt_KSsKSfwZl\&q=85\&s=a20e0311e799e0c2b08930cfd878bc1c) Retention tab: churn rates, retention matrix, and NRR/GRR Monitor customer retention and churn patterns. | Metric | Description | | - | - | | **User Retention** | Groups customers by signup month (cohort), then shows the share of each cohort still active in every later month. Retention (month k) = cohort customers active in month k ÷ cohort size. | | **Customer Churn Rate** | Share of starting subscribers who cancelled during the period, with the churned-customer count beside it. Customer churn rate = churned subscribers ÷ subscribers at start of period. | | **Revenue Churn Rate** | Revenue churn rate = churned MRR ÷ starting MRR. Starting MRR is the recurring revenue from existing customers at the start of the period, which is where the prior period ended. | | **Net Revenue Retention (NRR)** | Includes upgrades, so it can exceed 100%. NRR = (starting MRR + Expansion − Contraction − Churned) ÷ starting MRR. | | **Gross Revenue Retention (GRR)** | Excludes upgrades, so it caps at 100%. GRR = (starting MRR − Contraction − Churned) ÷ starting MRR. | | **Trial Conversion** | Trial conversion = trials converted ÷ trials that ended in the period. | ### Success Rate Tab ![Success Rate tab showing payment success rate, payments breakdown, payment failure reasons, and success by payment method](https://mintcdn.com/dodopayments/8P4fvt_KSsKSfwZl/images/analytics/success-rate-tab.png?fit=max\&auto=format\&n=8P4fvt_KSsKSfwZl\&q=85\&s=fbbce6df48c5101228aef438e19e7194) Success Rate tab: payment and refund success rates with failure analysis Monitor payment and refund success rates to find and resolve transaction issues. | Metric | Description | | - | - | | **Payment Success Rate** | Only processor and network failures count against it. Customer-fixable failures, such as a wrong or expired card, are excluded from the denominator. Payment success rate = succeeded ÷ (attempts − customer-fixable failures). | | **Payments Breakdown** | Splits attempts into total, success, failed (network), failed (customer), and not initiated. | | **Payment Failure Reason** | Breakdown of payment failures by reason. | | **By Payment Method** | Per method (card, wallet, UPI, BNPL): success rate = succeeded ÷ attempts, and volume = succeeded amount. | | **Checkouts** | How many checkout sessions customers began, whether or not they completed them. | | **Refund Success Rate** | The share of initiated refunds that processed successfully. | > [card] [Transaction Failure Reference](/api-reference/transaction-failures) > > All transaction failure codes and their reasons. > [!WARNING] > > If success rates drop or failures spike, review the failure reasons and address them promptly to limit lost revenue. ### Recovery Tab ![Recovery tab showing recovery overview, recovery by flow, payment retries, and dunning metrics](https://mintcdn.com/dodopayments/8P4fvt_KSsKSfwZl/images/analytics/recovery-tab.png?fit=max\&auto=format\&n=8P4fvt_KSsKSfwZl\&q=85\&s=57113eb4539464654f2ac48c75d17cd2) Recovery tab: retries, dunning, and abandoned cart recovery Track how much revenue Dodo Payments recovers for you through automated payment retries, dunning emails, and abandoned cart recovery. | Metric | Description | | - | - | | **Recovery Overview** | Recovered revenue as a trend, with the overall recovery rate. Recovery rate = recovered ÷ recoverable failed amount. Hard declines, such as closed accounts, are excluded from the recoverable amount. | | **Recovery by Flow** | Recovered revenue broken down across retries, dunning, and abandoned cart. | | **Payment Retries** | Retry attempts, successful retries, retry success rate, and subscriptions saved. | | **Dunning** | Dunning entries, emails sent, recovered revenue, recovery rate, and average time to recover. | | **Abandoned Cart** | Abandoned checkouts, recovered revenue, recovery rate, and average time to recover. | > [card] [Recovery Features](/features/recovery/overview) > > Configure payment retries, dunning, and abandoned cart recovery. ## Product-Level Analytics To see analytics for one product, go to **Products** and select the product. The product page shows the same cards as **Analytics**, scoped to that product. ![Product analytics overview tab with total revenue, successful payments, and revenue trend chart](https://mintcdn.com/dodopayments/QP0nYJEAkU83kGFn/images/product-analytics/overview.png?fit=max\&auto=format\&n=QP0nYJEAkU83kGFn\&q=85\&s=f2ce88b712ba0205839cd334d0f2a367) Product analytics overview showing revenue summary and trend chart The product page has five tabs. **Subscribers** and **MRR** appear only for subscription products. > [card] Overview > > Revenue cards, plus the product's transactions and discounts. > [card] Customers > > Customer cards for this product, including top customers by spend. > [card] Retention > > Churn, retention, and trial conversion for this product. > [card] Subscribers > > All subscriptions with status and billing details. > [card] MRR > > Monthly Recurring Revenue breakdown: new, expansion, contraction, churned, and net. One filter bar sets the period and comparison for every tab. It starts on **Last 30 days**, or on the range you last used for this business. ### Overview Tab The Overview tab shows the product's Revenue cards: **Gross Volume**, **Net Volume**, **Payments Count**, **Payments Breakdown**, **Average Order Value**, and **Revenue By Country**. The [Revenue Tab](#revenue-tab) defines each metric. Below the cards, a **Transactions** table lists every payment for this product: | Column | Description | | - | - | | Payment ID | Unique identifier for the transaction | | Status | The payment status, such as `Successful`, `Failed`, or `Processing` | | Amount | Transaction amount with currency | | Date | Timestamp of the transaction | | Payment Method | Card, UPI, or other method used | | Refund | Option to initiate a refund | More columns show customer, subscription, currency, invoice, card, refund status, and dispute status details. ![Product transactions table with payment IDs, statuses, amounts, and refund actions](https://mintcdn.com/dodopayments/QP0nYJEAkU83kGFn/images/product-analytics/overview-transactions.png?fit=max\&auto=format\&n=QP0nYJEAkU83kGFn\&q=85\&s=c7971b1b43694a5604736d2a8490b404) Transactions table showing payment history for the product To narrow the list by status, click **Filter by status** and choose **Not initiated**, **In progress**, **On hold**, **Failed**, or **Success**. A **Discounts** table follows the transactions. ### Customers Tab See who buys this product and how much they spend. ![Customers tab showing top 3 customers ranked by revenue with a detailed breakdown table](https://mintcdn.com/dodopayments/QP0nYJEAkU83kGFn/images/product-analytics/customers.png?fit=max\&auto=format\&n=QP0nYJEAkU83kGFn\&q=85\&s=c067951f3033c2fdc57b541b019a0c67) Top customers of the month with podium ranking and customer table The Customers tab shows the product's customer cards: **Active Customers**, **New Customers**, **ARPU**, **Top Customers by Spend**, **New VS Returning**, and **LTV (model)**. **Top Customers by Spend** ranks customers by the revenue this product earned from them. The [Customers Tab](#customers-tab) under **Analytics** defines each metric. ### Retention Tab See how well this product keeps its subscribers. ![Retention tab showing customer churn rate, revenue churn rate, and churn rate trend chart](https://mintcdn.com/dodopayments/QP0nYJEAkU83kGFn/images/product-analytics/retention.png?fit=max\&auto=format\&n=QP0nYJEAkU83kGFn\&q=85\&s=8c5cbe5dbb01ba3240251546250251a9) Customer and revenue churn rates with trend analysis The Retention tab shows the product's retention cards: **User Retention**, **Customer Churn Rate**, **Revenue Churn Rate**, **Net Revenue Retention**, **Gross Revenue Retention**, and **Trial Conversion**. Customer churn rate is the share of subscribers who cancelled. Revenue churn rate is the share of MRR lost to cancellations. Track both over time to spot trends early and act on them. ### Subscribers Tab A list of the subscriptions for this product that were created in the selected period. ![Subscribers tab with subscription IDs, customer emails, statuses, start dates, and next billing information](https://mintcdn.com/dodopayments/QP0nYJEAkU83kGFn/images/product-analytics/subscribers.png?fit=max\&auto=format\&n=QP0nYJEAkU83kGFn\&q=85\&s=da5b781227a499f40d6c9d73251b4f90) Subscribers table showing all subscriptions with statuses and billing details | Column | Description | | - | - | | Subscription ID | Unique identifier for the subscription | | Customer Email | The subscriber's email address | | Status | `Active`, `Pending`, `On hold`, `Paused`, `Failed`, `Cancelled`, `Expired`, or `Scheduled for Cancellation` | | Product Name | The product this subscription belongs to | | Quantity | The number of units on the subscription | | Start Date | When the subscription began | | Next Billing Date | The upcoming renewal date | | Next Billing Amount | The amount due at next renewal (excluding tax) | More columns show the customer's name and business name, billing frequency, trial days, cancellation details, tax details, and IDs. ### MRR Tab A breakdown of the product's Monthly Recurring Revenue. ![MRR tab with stacked bar chart showing new, expansion, and churned MRR by month](https://mintcdn.com/dodopayments/QP0nYJEAkU83kGFn/images/product-analytics/mrr.png?fit=max\&auto=format\&n=QP0nYJEAkU83kGFn\&q=85\&s=5a8d503e53ab124fb1bacc6400174fac) MRR stacked bar chart showing monthly revenue composition The MRR tab shows the product's subscription cards: **Current MRR**, **Projected ARR**, **Net New MRR**, and **Active Subscriptions**, plus the MRR components below. ![MRR breakdown showing New MRR, Expansion MRR, Churned MRR, and Net New MRR with trend charts](https://mintcdn.com/dodopayments/QP0nYJEAkU83kGFn/images/product-analytics/mrr-breakdown.png?fit=max\&auto=format\&n=QP0nYJEAkU83kGFn\&q=85\&s=fde89031b89baad28e36841241002a1f) Detailed MRR breakdown with New, Expansion, Churned, and Net New MRR | Metric | Description | | - | - | | **New MRR** | MRR from new subscriptions in the period | | **Expansion MRR** | Extra MRR from existing subscribers upgrading or buying add-ons | | **Contraction MRR** | MRR lost when existing subscribers downgrade without cancelling | | **Churned MRR** | MRR lost from cancelled subscriptions | | **Net New MRR** | The net result: New MRR + Expansion MRR − Contraction MRR − Churned MRR | Each card compares its value with the comparison period you pick in the filter bar. ## Page Highlight Tiles Many list pages in your dashboard show **highlight tiles** at the top, with summary metrics you can read without opening **Analytics**. The tiles follow the page's active filters. | Page | Highlight Tiles | | - | - | | **Products** | All Products, Active Products, Archived Products | | **Add-ons** | All Add-Ons, Active Add-Ons, Linked to Products | | **Collections** | All Collections, Active Collections, Archived Collections | | **Subscriptions** | Active Subscriptions, On Hold, Cancelled | | **Payments** | Successful Payments, Payment Volume, Failed Payments | | **Refunds** | Successful Refunds, Refund Volume, Failed Refunds | | **Disputes** | Disputes Created, Won, Accepted, Lost | > [!NOTE] > > "Active" products, add-ons, collections, and meters are those that have been part of at least one successful payment. ## Reports Reports have their own page: **Settings → Reports**. There you can track money movement on screen and build a CSV or XLSX export for any date range. Reports cover live mode only. > [card] [Reports](/features/reports) > > Balance and Payout Summary, All Fees, and four downloadable reports, with filters, row limits, and your full report history. Two views explain your balance and your fees on screen. Four more build a download for any date range. ![The Reports tab in Settings, showing Track Money Movement, Download Reports, and Generated Reports](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/reports-hub.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=5ca9b31a0a29106dba531c8e1c5a7f9d) Settings → Reports: live views, custom exports, and your report history > [!NOTE] > > Fees have a dedicated view. Open **All Fees** under **Settings → Reports** for a total and a per-transaction breakdown. ## Best Practices > [!TIP] > > * Review your analytics regularly to spot trends and anomalies early. > * Use filters to compare performance across products and time periods, and **Revenue By Country** to compare markets. > * Open product-level analytics to see which products drive the most revenue and which have the highest churn. > * If data looks wrong or missing, check your filters and date range first. > [!WARNING] > > If discrepancies persist or data is still missing after you check your filters, contact support. > [card] [Contact Support](mailto:support@dodopayments.com) > > Email [support@dodopayments.com](mailto:support@dodopayments.com) with the page, the metric, and the date range. ## Next Steps > [card] [Account Summary & Payout Wallet](/features/account-summary-payout-wallet) > > Understand your earnings, deductions, and payout cycles. > [card] [Products](/features/products) > > Create and manage your products. > [card] [Payments](/features/transactions/payments) > > Track and manage all payment transactions. > [card] [Refunds](/features/transactions/refunds) > > Initiate and monitor refunds. # Selling Digital Goods on iOS Source: https://docs.dodopayments.com/features/appstore-digital-goods Sell subscriptions, courses, downloads, and SaaS plans in your iOS app with Dodo Payments hosted checkout, in the App Store regions that allow it. ## Introduction Dodo Payments lets you sell digital goods and services in your iOS app, and handles tax compliance, currency conversion, and payouts for you. This page covers how the integration works for SaaS tools, content subscriptions, and digital utilities, and in which App Store regions you can use it. ## Overview Dodo Payments is your **Merchant of Record (MoR)** and takes on these parts of your digital business: > [tab] What We Handle > > * Tax collection and remittance (VAT, GST, and other regional taxes) > * Global payments, including local payment methods, subject to Dodo Payments policies > * Currency conversion and foreign exchange > * Fraud prevention and dispute tools > * End-customer invoicing and receipts > * Compliance with regional regulations > [tab] What You Get > > * One API for web and mobile platforms > * Checkout opened from your app, with UPI, cards, wallets, and BNPL > * Global payouts by local bank transfer or SWIFT wire, including to Payoneer receiving accounts > * Analytics and reporting dashboard > * Secure payment processing ## Use Cases > [card] Subscriptions > > * Premium content or feature access > * Recurring billing with free trials, proration, and upgrades or downgrades > [card] Courses and Learning > > * Pay-per-course access > * Bundled content packages > * Lifetime or renewable licenses > * Progress tracking in your app > [card] Digital Downloads > > * One-time purchases (PDFs, music, tools) > * Digital asset delivery > * License key management > [card] SaaS Tools > > * Software-as-a-Service subscriptions > * Usage-based billing > * Team and enterprise plans ## Integration Flow Your app opens Dodo Payments hosted checkout with the [iOS checkout SDK](/developer-resources/sdks/ios). The SDK presents checkout in `SFSafariViewController` and returns a typed result. > [!WARNING] > > Use the SDK rather than embedding checkout in a `WebView`. Apple documents > Apple Pay support in `SFSafariViewController`, while an embedded `WebView` can > suppress Apple Pay and Google Pay, which costs you wallet conversions. For example, `WKWebView` disables Apple Pay when your app injects scripts into the page. App Review applies the same purchase rules > (guideline 3.1.1) to a `WebView` checkout as to a native one. ```mermaid theme={null} flowchart LR A[Mobile App] -->|Request checkout| B(Your Server) B -->|Create checkout session| C(Dodo API) C -->|checkout_url| B B -->|checkout_url| A A -->|SDK opens SFSafariViewController| D[Hosted Checkout] D -->|Webhook| B B -->|Grant access| A ``` ### Integration Steps **1. Mobile App to Your Server** Your app asks your backend for a checkout URL. Authenticate the request with the signed-in user's session token. **2. Your Server to Dodo API** Your backend creates a [checkout session](/developer-resources/checkout-session) with your API key and returns the `checkout_url` to the app. > [!WARNING] > > Create checkout sessions on your server, never in the app. Anyone can extract > an API key from an app binary. **3. Mobile App Opens Checkout** Pass the `checkout_url` to `DodoCheckout.start(...)`. The SDK presents it in `SFSafariViewController` and returns a typed result when the customer completes or dismisses checkout. **4. Dodo Payments to Your Server** Dodo Payments sends the `payment.succeeded` or `subscription.active` webhook to your endpoint when the payment succeeds or the subscription activates. **5. Your Server Grants Access** Unlock the purchased content from that webhook, not from the result the app received. The SDK result is a UI hint, not proof of payment. > [card] [iOS Checkout SDK](/developer-resources/sdks/ios) > > Install steps and the full `start(...)` contract for Swift. > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > The end-to-end flow, plus the same contract for Android, React Native, and Flutter. ## Regional Availability Dodo Payments supports alternative purchase flows only in App Store regions where Apple explicitly allows external payments, or where a regulator or court order requires it. ### Supported Regions > [accordion] United States > > Supported to the extent that current court orders and Apple's App Store Review Guidelines allow. > > * Guideline 3.1.1(a) lets apps on the U.S. storefront include buttons and links to other purchase methods without an entitlement > * Subject to the outcome of the Epic v. Apple court proceedings > * You must follow Apple's implementation guidelines > [accordion] European Union (EU) App Store > > Supported through Apple's EU terms and Apple's external purchase entitlement for the EU. > > * Enabled through Apple's EU Alternative Terms. From October 1, 2026, Apple replaces these terms with a single set of EU terms > * Requires the [StoreKit External Purchases or Offers Entitlement](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu/) under the terms that take effect on October 1, 2026. Under the earlier terms, the entitlement is the StoreKit External Purchase Link Entitlement > * You must comply with EU Digital Markets Act requirements > [accordion] Japan > > Supported under Japan's Mobile Software Competition Act (MSCA), in force since December 18, 2025. > > * Apple allows alternative payment methods and links to external purchases on the Japan storefront > * You must follow Apple's Japan-specific entitlement and App Store Connect requirements > * Commission terms differ from other regions; check Apple's current terms for Japan > [!NOTE] > > South Korea isn't a supported region. Apple's [StoreKit External Purchase Entitlement for South Korea](https://developer.apple.com/support/storekit-external-entitlement-kr/) requires a native in-app payment flow that "may not be within a web view", processed by an Apple-approved Korean payment service provider (such as KCP, Inicis, Toss, or NICE), with prices in South Korean Won. Dodo Payments checkout opens as a web page, so it doesn't meet these requirements. > [!WARNING] > > Before you enable Dodo Payments for any storefront, review and follow Apple's region-specific entitlements and App Store Connect requirements. Alternative payment flows in unsupported regions can get your app rejected or removed. > [!NOTE] > > Some business models don't require in-app purchase (IAP). Under guideline 3.1.3(e), apps that sell physical goods or services consumed outside the app must use a payment method other than IAP. Dodo Payments supports these models too. Check your app's category against Apple's current guidelines to confirm whether IAP is required for your use case. ### Learn More For global policies, legal history, and strategies to reduce App Store fees, see: > [card] [Bypassing App Store & Play Store Fees: A Strategic and Legal Playbook](/features/bypassing-app-store-fees) > > Learn where and how you can legally implement alternative payment flows, with up-to-date regional guidance and compliance tips. # Archiving a Business Source: https://docs.dodopayments.com/features/archive-business Permanently retire a business you no longer trade under. Check the eligibility requirements, confirm with an emailed code, and see what changes after. ## Introduction Archiving retires a business you no longer trade under. The business disappears from your dashboard, its API keys stop working, and its checkout, payment links, storefront, and Customer Portal stop serving your customers. Archiving is not deletion. Dodo Payments is your [Merchant of Record](/features/mor-introduction), so your payments, refunds, invoices, and tax records must be kept for compliance long after you stop trading. Archiving closes the business to new activity and leaves those records intact. > [!WARNING] > > Archiving is permanent. An archived business can't be restored, and support can't reverse the archive for you. To retire one brand and keep trading under the others, archive the brand instead. See [Multi-Brand Setup](/features/multi-brands). ## Eligibility Requirements A business can be archived only once it is fully settled. Dodo Payments checks seven requirements and shows a live checklist of them. You clear each outstanding item yourself, with the same tools you use day to day. | Requirement | Cleared when | How to clear it | | - | - | - | | **Dormancy** | The business has had no payment activity in the last 180 days | Wait out the window. The checklist shows the date you become eligible. | | **Payout Wallet** | Every currency balance is exactly zero | Withdraw your remaining funds. See [Balances](/features/account-summary-payout-wallet). | | **Payouts** | No payout is still in progress, on hold, or awaiting initiation | Wait for each payout to settle. See [Payout Structure](/features/payouts/payout-structure). | | **Disputes** | No dispute is open or challenged | Resolve or accept every dispute. See [Disputes](/features/transactions/disputes). | | **Refunds** | No refund is pending or under review | Wait for each refund to complete. See [Refunds](/features/transactions/refunds). | | **Subscriptions** | No subscription is pending, active, on hold, or paused | Cancel each subscription. See [Subscriptions](/features/subscription). | | **Customer Balances** | No customer holds a cash balance | Bring each balance to zero through the [Customer Wallet](/features/customer-wallet) ledger. | > [!NOTE] > > A subscription scheduled to cancel at its next billing date blocks archiving until it ends. Dodo Payments doesn't cancel subscriptions on your behalf, so you stay in control of what your customers are charged. Every payment counts towards the dormancy window, whatever its outcome. A failed or abandoned payment attempt restarts the 180 days, the same as a successful one. Customer credit grants don't block archiving. Only cash balances do. Credits expire on their own schedule. Dodo Payments evaluates the checklist each time you open it. After you clear an item, refresh the checklist to see the requirement turn green. ## How to Archive Your Business Only the **Owner** of a business can archive it. Editors and Viewers can see the checklist but can't archive. If you aren't the Owner, ask the Owner to complete this flow, or ask them to [transfer ownership](/features/ownership-transfer) to you. Archiving is available in live mode only. If the dashboard is in test mode, turn on the **Live Mode** switch in the sidebar first. **1. Open the Danger Zone** Go to **Settings → Business** and scroll to the **Danger Zone** panel. Select **See Details** next to the status line to expand the checklist. ![Danger Zone panel showing the Archive Business button and the seven-item eligibility checklist, all met](https://mintcdn.com/dodopayments/wseRJZn2cgbMg0kW/images/archive-business/danger-zone-checklist.png?fit=max\&auto=format\&n=wseRJZn2cgbMg0kW\&q=85\&s=055e362ab0dc06d7a26f0dc7e8b6949b) **2. Clear Every Outstanding Requirement** Work through the items that haven't passed, using the links in the [eligibility table](#eligibility-requirements). Return to the panel and expand the checklist again as you go. The status line above the checklist reads **All conditions met** when nothing is left to clear. **3. Confirm You Want to Archive** Select **Archive Business** and read the confirmation dialog. Select **Continue** to send a confirmation code to the Owner's email address. ![Confirmation dialog warning that the business cannot be restored once archived](https://mintcdn.com/dodopayments/wseRJZn2cgbMg0kW/images/archive-business/archive-confirmation.png?fit=max\&auto=format\&n=wseRJZn2cgbMg0kW\&q=85\&s=38ab5c72086218d58792298bf4dad93e) **4. Enter the Code from Your Email** Dodo Payments emails a 6-digit code to the Owner's login email address. The code expires after 10 minutes, and you can request a new one every 60 seconds. After 3 wrong attempts, you need a new code. ![Verification dialog waiting for the 6-digit code, with a resend countdown](https://mintcdn.com/dodopayments/wseRJZn2cgbMg0kW/images/archive-business/otp-prompt.png?fit=max\&auto=format\&n=wseRJZn2cgbMg0kW\&q=85\&s=d591f21372189b8358cdd6942d529a28) If you no longer have access to the Owner's mailbox, use the **Contact support** link in the dialog. **5. Verify and Archive** Enter the code and select **Verify & Archive**. This step can't be undone: Dodo Payments archives the business as soon as it accepts the code. ![Verification dialog with all six digits entered and the Verify and Archive button active](https://mintcdn.com/dodopayments/wseRJZn2cgbMg0kW/images/archive-business/otp-entered.png?fit=max\&auto=format\&n=wseRJZn2cgbMg0kW\&q=85\&s=e33f8c3c466b30dc2a9a620ecee95b71) **6. Switch to Another Business** Dodo Payments confirms the archive and moves you to another of your businesses after a short countdown. Select **Switch Now** to go there immediately. ![Confirmation that the business has been archived, with a countdown to switch to another business](https://mintcdn.com/dodopayments/wseRJZn2cgbMg0kW/images/archive-business/archive-complete.png?fit=max\&auto=format\&n=wseRJZn2cgbMg0kW\&q=85\&s=17803ac8b5eb3b9a251be7c2f6ea6177) ## What Happens After Archiving **For you** * The business no longer appears in your dashboard or in the business switcher. Dodo Payments moves you to another of your businesses right after the archive. * Live mode and live payments are turned off. * Every API key for the business stops working, in both live mode and test mode. Cached credentials can take up to a minute to expire, so an integration may keep working briefly after you archive. * The business no longer counts toward the limit of 10 businesses that one account can own. You can create a new business in its place. **For your customers** * Checkout sessions, payment links, and static checkout pages stop accepting payments. * Your storefront stops serving products. * Customer Portal sessions end, and customers can no longer sign in to manage their purchases. * License key activation and deactivation stop. Tell your customers before you archive. After the archive, customers have no self-serve route back to their purchase history, and Dodo Payments returns a terminal error, not a retry. **For your records** Payments, refunds, invoices, payouts, and tax filings are retained. Download the invoices and reports you want to keep before you archive, because dashboard access ends the moment the business is archived. Contact [support](/miscellaneous/help-support) if you need a copy of your records afterwards. ## Limits * **Archiving can't be undone.** The action is permanent for merchants and support alike. * **You can't archive your last business this way.** If the business is the only one you own, contact [support](/miscellaneous/help-support) to close your account instead. * **Archiving is all or nothing.** To retire part of your catalog and keep trading, archive a brand instead of the business. > [card] [Multi-Brand Setup](/features/multi-brands) > > Archive a single brand and keep the rest of the business trading. > [card] [Balances](/features/account-summary-payout-wallet) > > Withdraw your remaining balance before you archive. > [card] [My Account](/miscellaneous/accounts) > > Manage business profiles and switch between businesses. > [card] [Help and Support](/miscellaneous/help-support) > > Get in touch about account closure or record requests. # B2B Payments Source: https://docs.dodopayments.com/features/b2b-payments Collect Tax IDs and business names during B2B checkout. Validate Tax IDs and apply the correct tax treatment for the customer's country. B2B payments let you collect Tax IDs and business names during checkout, validate the Tax IDs, and apply the correct tax treatment based on the customer's country and regulations. > [!TIP] > > To bill a business customer on payment terms, such as Net 30, use [Invoice-Based Billing](/features/invoice-based-billing). ## Tax ID Validation for B2B Transactions When a valid Tax ID is provided during checkout: * The invoice includes the customer's Tax ID. * Tax deductions are determined based on applicable regulations for the customer's country. * The invoice includes Dodo Payments' tax details and the tax applied to the transaction. ## Collecting a Business Name for B2B Invoices For B2B purchases, you can have the customer's legal business name rendered on the invoice instead of the buyer's personal name. This is collected alongside the Tax ID via the `customer_business_name` field. When the customer selects **Purchasing as a business** at checkout, they're prompted for both a **Business Name** and a **Tax ID Number**. The Tax ID is validated live as the customer types. For EU member states, Great Britain, and Australia, checkout performs both format and checksum validation and a live registry lookup (VIES, HMRC, and ABR respectively) and autofills the registered legal business name when a match is found. For all other countries, only format and checksum validation is performed. ![Checkout page with the 'Purchasing as a business' toggle enabled, showing Business Name and Tax ID Number fields](https://mintcdn.com/dodopayments/OBU18S2UplPD5yUr/images/b2b-payments-business-name.png?fit=max\&auto=format\&n=OBU18S2UplPD5yUr\&q=85\&s=8874862394939cf83551c9a499448ab3) The business name appears on the invoice only when all three conditions are met: 1. The transaction is B2B (`b2b = true`). 2. A `tax_id` is present. 3. A non-empty `customer_business_name` is supplied. If any condition is not met, the customer's personal name is used instead. ### Setting It at Checkout Pass `customer_business_name` directly, and/or enable `allow_customer_editing_business_name` to let the customer enter or edit it on the checkout page next to their Tax ID: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_abc', quantity: 1 }], customer: { email: 'buyer@acme.com' }, billing_address: { country: 'GB' }, tax_id: 'GB123456789', customer_business_name: 'Acme Corp Ltd', feature_flags: { allow_tax_id: true, allow_customer_editing_business_name: true // optional: let the customer edit it }, return_url: 'https://yoursite.com/return' }); ``` | Surface | Field | Notes | | - | - | - | | Checkout Sessions | `customer_business_name`, `feature_flags.allow_customer_editing_business_name` | Max 250 chars; flag defaults to `false` | | Payments | `customer_business_name` | Max 250 chars | | Subscriptions | `customer_business_name` | Set or clear via `PATCH /subscriptions/{subscription_id}` | > [!WARNING] > > `customer_business_name` cannot be set without a `tax_id` — the request is rejected. Clearing the `tax_id` also clears the business name, since the two are coupled on the invoice. Surrounding whitespace is trimmed, and whitespace-only values are treated as an explicit clear. ## Making the Tax ID Mandatory By default the Tax ID is optional — the customer decides whether to purchase as a business. If you sell exclusively to registered businesses, set the `require_tax_id` feature flag on the checkout session to make it compulsory for customers who purchase as a business: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_abc', quantity: 1 }], customer: { email: 'buyer@acme.com' }, billing_address: { country: 'IN' }, feature_flags: { allow_tax_id: true, // default; must be true require_tax_id: true }, return_url: 'https://yoursite.com/return' }); ``` ### What Changes at Checkout * A customer who selects **Purchasing as a business** must fill in both **Business Name** and **Tax ID Number**. * Checkout doesn't change for a customer who buys as an individual. * **Continue to Payment** stays greyed out while either field is empty, or while the entered Tax ID is rejected by validation. Tax ID validation remains fail-open — a lookup outage or an unsupported country never blocks the customer, so the button stays clickable even when it is greyed out. > [!NOTE] > > Passing `tax_id` and `customer_business_name` on the session pre-fills both fields, which satisfies the requirement before the customer touches the form. Omit them if you want the customer to supply their own. ### Rules and Limits | Rule | Behavior | | - | - | | `require_tax_id: true` with `allow_tax_id: false` | Rejected with a `400` — the flag would demand a field the checkout never renders | | `require_tax_id: true` with `confirm: true` | Rejected with a `422` unless the request includes a non-blank `tax_id`, since `confirm` skips the checkout page | | Flag omitted | Defaults to `false`; existing sessions and integrations are unaffected | > [!NOTE] > > A blank or whitespace-only `tax_id` counts as missing, both on the `confirm: true` guard and when a hosted-page session is confirmed. > [!WARNING] > > On a hosted checkout page (`confirm: false`), the requirement is enforced in the browser. The API rejects a blank Tax ID on confirmation, but it cannot tell an individual buyer apart from a business buyer who omitted the field, so treat `require_tax_id` on hosted sessions as a checkout experience control rather than a guarantee that every payment carries a Tax ID. A `confirm: true` session is a stricter case: it is always treated as a business purchase and is rejected outright without a Tax ID. ## Tax Treatment for B2C Transactions Transactions where a valid Tax ID is not provided are treated as B2C transactions, and tax is deducted as per the applicable tax regulations in the customer's country. The invoice includes Dodo Payments' tax details and the tax applied to the transaction. ## Reverse Charge Mechanism Generally, the supplier of goods or services is liable to pay VAT, Service Tax, or GST. However, in specified cases like imports and other notified supplies, the liability is on the recipient (customer) under the reverse charge mechanism. Reverse Charge means the liability to pay tax is on the recipient of supply of goods or services instead of the supplier in respect of notified categories of supply. ## Reverse Charge Applicability In certain cases, where applicable by law, tax is not deducted at checkout and the transaction is subject to a reverse charge mechanism. The invoice clearly indicates when a reverse charge applies, as per regulatory requirements. # Bring Your Own Processor (BYOP) Source: https://docs.dodopayments.com/features/byop Connect your own Stripe or Adyen account, route payments to it by customer country, and keep Dodo Payments for subscriptions, invoicing, and analytics. **Bring Your Own Processor (BYOP)** connects your own **Stripe** or **Adyen** account to Dodo Payments. Payments from the countries you choose run on your processor account, while Dodo Payments runs everything around the transaction: products, subscriptions, license keys and the entitlement engine, invoicing, the Customer Portal, and analytics. For each customer country, you choose who processes the payment: **your processor**, which makes you the legal seller for that route, or **Dodo Payments** as your full-service Merchant of Record. Payments from countries without a route go to Dodo Payments. > [card] Route by Geography > > Send payments from specific countries to your own processor, and everything else to Dodo Payments. > [card] Keep Your Processor Accounts > > Continue using your existing Stripe or Adyen accounts and relationships. > [card] Stay the Merchant of Record > > On your own routes, you remain the legal seller and control tax, disputes, and payouts. > [card] One Billing Layer > > Dodo Payments runs products, subscriptions, invoices, and analytics across both routes. ## BYOP vs. Dodo as Merchant of Record The two models run side by side. Each payment follows the route set for the customer's country. To see this comparison in the dashboard, select **Show Comparison** under **Settings → BYOP**. | Feature | Dodo as Merchant of Record | Bring Your Own Processor | | - | - | - | | Legal seller of record | Dodo Payments | Your company | | Tax (VAT, GST & sales tax) | Calculated, collected & remitted for you | You register, collect & file | | Chargebacks & fraud | Dodo screens for fraud and provides dispute tools; you bear the chargeback cost | You manage with your processor's own tools | | PCI compliance | Handled by Dodo | You manage | | Payment methods | 40+ global & local, multi-currency | Cards only (credit/debit) | | Payouts | Aggregated global payouts | Direct from your processor | | Setup | Simple, go live in minutes | Moderate, add keys & routing | | Best for | Selling globally, hands-off compliance | Existing processor & regional control | > [!TIP] > > A common setup is **hybrid**: route a country where you already have a registered entity and processor (for example, your home market) to your own processor, and let Dodo Payments handle the rest of the world as Merchant of Record. ## Supported Processors You can connect **Stripe** and **Adyen**. > [card] Stripe > [card] Adyen Payments routed through your own processor support **credit and debit cards only**. > [!WARNING] > > **Stripe** and **Adyen** both require **raw card API access** on your account, so that Dodo Payments can run billing on top of your processor. Each processor enables it on request, so contact the processor's support before you connect. The connection step of the setup wizard shows the same requirement, with a **View documentation** link to the [Stripe](/features/byop/stripe) and [Adyen](/features/byop/adyen) guides. ## Set Up BYOP To start the setup wizard, open **Settings → BYOP** in the dashboard and select **Configure** on the **Bring Your Own Processor** card. > [!NOTE] > > Connections are configured **per environment**. A processor you connect in test mode (shown as **Sandbox**) is separate from one you connect in live mode (shown as **Production**). To test before you go live, set up both. The setup wizard uses the mode set by the **Live Mode** switch in the sidebar. ![BYOP settings showing the Merchant of Record and Bring Your Own Processor options with a feature comparison](https://mintcdn.com/dodopayments/DNTF2guUc26Fj2yI/images/byop/overview.png?fit=max\&auto=format\&n=DNTF2guUc26Fj2yI\&q=85\&s=aeb8dfda155edde6d9084a4a03d7b15f) **1. Choose a Payment Processor** In **Select Payment Processor**, select **Stripe** or **Adyen**, then select **Continue**. ![Select Payment Processor dialog with Stripe and Adyen options](https://mintcdn.com/dodopayments/DNTF2guUc26Fj2yI/images/byop/select-processor.png?fit=max\&auto=format\&n=DNTF2guUc26Fj2yI\&q=85\&s=af477914f52012f9d935da449a70fe25) **2. Connect Your Account** Enter the connection details, then select **Connect processor**: * **Processor Name**: a name for this connection, 2–75 characters. A name helps when you connect several accounts from one processor, for example *Stripe US* and *Stripe UK*. * **Secret Key**: your processor's API key for the current mode. For Stripe, this is your `sk_...` secret key. * **Merchant Account** (Adyen only): your Adyen merchant account identifier. ![Connect Your Stripe Account step showing processor name, secret key, webhook endpoint, and signing secret fields](https://mintcdn.com/dodopayments/DNTF2guUc26Fj2yI/images/byop/connect-account.png?fit=max\&auto=format\&n=DNTF2guUc26Fj2yI\&q=85\&s=1c0288cc586a0ca856de2c11ce48db58) Dodo Payments creates the connection and shows a **Webhook Endpoint** URL unique to it. Add that URL as a webhook destination in your processor's dashboard. Then paste the **Webhook Signing Secret** into Dodo Payments and select **Save & continue**: * **Stripe**: the signing secret of the webhook endpoint you added. * **Adyen**: the **HMAC key** from **Customer Area → Webhooks**. Until you save the signing secret, the connection shows as **Incomplete** under **Edit Configuration**. After you save it, the connection shows as **Connected**. > [!NOTE] > > After you connect, your secret key is stored securely and can't be viewed or changed. The Adyen merchant account can't be changed after setup either. In your processor, you configure only the webhook URL that Dodo Payments generates; you never work with the underlying infrastructure directly. **3. Configure Payment Routing** Add **routing rules** that map customer countries to a processor. Each country routes to exactly one processor: * **Your processor** handles payments from the countries you assign to it. * **Dodo Payments** handles **Rest of the World**, every country you don't route, as Merchant of Record. ![Configure Payment Routing step showing Stripe US routed to United States and Dodo Payments as the Rest of the World default](https://mintcdn.com/dodopayments/DNTF2guUc26Fj2yI/images/byop/routing.png?fit=max\&auto=format\&n=DNTF2guUc26Fj2yI\&q=85\&s=3af203be1fcab91b6952b8c6c3079f32) To assign one or more countries to a processor, select **Add Route**, choose the processor, and select the countries. A country that is already routed to another processor can't be added. ![Add Route panel selecting a processor and countries](https://mintcdn.com/dodopayments/DNTF2guUc26Fj2yI/images/byop/add-route.png?fit=max\&auto=format\&n=DNTF2guUc26Fj2yI\&q=85\&s=cf0972881d7ba092a16e8af0e94d2456) > [!NOTE] > > **Routing Guidelines** > > * **Rest of the World** covers every country without a route. > * Dodo Payments Merchant of Record routes handle compliance and tax automatically. > * Routes on your own payment processor require separate tax configuration if needed. **4. Configure Invoice Information** On payments routed through your own processor, **you** are the seller on the invoice. Enter the business details for those invoices: * **Registered Business Name** (required). * **Tax ID (EIN, SSN, etc.)** (optional): 3–32 letters, numbers, or dashes. Format validation is available for US EINs. * **Statement Descriptor** (required): use 5–22 letters, numbers, spaces, `_`, or `-`. Payments on your processor send your [brand's](/features/multi-brands) statement descriptor to the processor, not this value. * **Registered Business Address** (required): start typing to search for your address, or enter it manually. * **Privacy Policy Link** and **Terms of Service Link** (required). The **Invoice Header Preview** shows how the details appear. These details apply **only** to invoices for routes your own processor handles. Payments routed to Dodo Payments keep the Dodo Payments Merchant of Record details. ![Configure Invoice Information step with business details and a live invoice header preview](https://mintcdn.com/dodopayments/DNTF2guUc26Fj2yI/images/byop/invoice-info.png?fit=max\&auto=format\&n=DNTF2guUc26Fj2yI\&q=85\&s=bcda6d001983283ef73b667085a22e83) **5. Review and Finish** Review your processor connection, routing rules, and invoice details. Select **I confirm that the routing and billing details are correct**, then select **Finish setup**. ![Review Your Configuration step summarising the processor, routing, and invoice details](https://mintcdn.com/dodopayments/DNTF2guUc26Fj2yI/images/byop/review.png?fit=max\&auto=format\&n=DNTF2guUc26Fj2yI\&q=85\&s=b3e0c37922465915ef8f0bb30c3d458c) After setup, the **Bring Your Own Processor** card shows **Edit Configuration**, where you add processors and edit routing and invoice details. To send all payments through Dodo Payments as Merchant of Record again, select **Edit routing rules**, open each route, and turn off **Enable processor**. Disabled processors are skipped during payment routing, and subscriptions on a disabled processor can't renew. ![BYOP settings after configuration showing Edit Configuration and routing options](https://mintcdn.com/dodopayments/DNTF2guUc26Fj2yI/images/byop/configured.png?fit=max\&auto=format\&n=DNTF2guUc26Fj2yI\&q=85\&s=212e6b18c6666d36ce240959e4d85541) ## How Routing Works Dodo Payments picks the route from the customer's billing country when the payment is created. The same rule applies to one-time payments, checkout sessions, and new subscriptions. Renewals reuse the processor the subscription was created on (see [Subscriptions](#subscriptions)). ```mermaid theme={null} flowchart TD A[Customer pays] --> B{Customer country
has a route?} B -->|Yes| C[Your processor
You are the legal seller] B -->|No, Rest of the World| D[Dodo Payments
Dodo is Merchant of Record] C --> E[Dodo powers billing,
invoicing & subscriptions] D --> E ``` On a route that **your processor** handles: * The payment runs on **your** processor account, in the billing currency. * Dodo Payments doesn't calculate or collect tax. You're responsible for tax on that route. * Invoices show the **business details and statement descriptor** you configured, without Dodo Payments' Merchant of Record details. * Your processor pays you **directly**. The payment amount never enters your Dodo Payments balance; only the BYOP billing fee is recorded there. On a route that **Dodo Payments** handles (Rest of the World), Dodo Payments is your full-service [Merchant of Record](/features/mor-introduction). It handles tax, compliance, fraud screening, and aggregated payouts, and gives you tools to prevent and respond to disputes. You bear the cost of disputes on these payments. ## Subscriptions A subscription stays on the processor it was created on. At renewal, Dodo Payments charges that same processor with the payment mandate stored when the customer subscribed, and doesn't re-evaluate routing rules. Payment method updates for the subscription go through the same processor. Whether Dodo Payments calculates tax on a subscription is also fixed when the subscription is created. ## Seeing Which Processor Handled a Payment After you configure BYOP, the **Payments** and **Disputes** tables show a processor icon (Stripe, Adyen, or Dodo Payments) on each row. Payment and dispute detail pages add a **Payment Processor** field, so you can tell which route handled a transaction. ## Refunds, Disputes & Payouts > [tab] Refunds > > Start refunds from the Dodo dashboard as usual. For a payment routed through your own processor, Dodo Payments sends the refund to that processor, which returns the funds; the refund doesn't draw on your Dodo Payments balance. For a Dodo-routed payment, Dodo Payments processes the refund. > [tab] Disputes > > The **Disputes** table lists disputes from both routes. You can respond to a dispute in the Dodo dashboard only when Dodo Payments processed the payment: evidence upload, accept, and challenge are available only for those disputes. When a dispute opens on a Dodo-processed payment, the disputed amount and a dispute fee are deducted from your balance, as with any Merchant of Record payment. > > For a dispute on a payment that your own processor handled, respond with your processor's own tools. The dispute doesn't debit your Dodo Payments balance, and its detail page shows this note: > > > [!NOTE] > > > > You can take actions for this dispute in your connected payment processor (Stripe) > [tab] Payouts > > Your processor pays you **directly** for payments on your own routes, and those payouts don't appear in Dodo Payments. Only Dodo Payments payouts appear in the dashboard. > > Dodo Payments payouts, for Rest of the World Merchant of Record volume, follow the standard [payout structure](/features/payouts/payout-structure). ## Analytics Revenue, tax, and subscription analytics include **both** routes, so you see all of your billing in one place. Disputes and payouts widgets show **Dodo-processed** activity only. Activity on your own processor also appears in that processor's dashboard. ## Billing Fee Dodo Payments charges a **BYOP billing fee** on each payment routed through your own processor, because Dodo Payments still runs your products, subscriptions, invoicing, and analytics on those payments. The default rate is **0.5%** of the payment's USD-equivalent amount, and the exact rate is confirmed when BYOP is enabled for your account. The fee appears as a `byop_fee` entry in your balance ledger. To discuss your rate, [contact the team](mailto:founders@dodopayments.com). ## Frequently Asked Questions > [accordion] Which processors can I connect? > > Stripe and Adyen. Both require **raw card API access** on your account, which you request from the processor's support. See the [Stripe](/features/byop/stripe) and [Adyen](/features/byop/adyen) guides. > [accordion] Can I route only some countries to my processor? > > Yes. Assign specific countries to your processor and leave the rest as **Rest of the World**, which Dodo Payments handles as Merchant of Record. Each country routes to exactly one processor. > [accordion] Who is the Merchant of Record on BYOP routes? > > You are. On routes that your own processor handles, you remain the legal seller and are responsible for tax, chargebacks, PCI compliance, and payouts on those transactions. > [accordion] Does Dodo calculate tax on my processor's routes? > > No. Dodo Payments doesn't calculate or collect tax on routes that your own processor handles; you manage tax for those transactions. Dodo Payments continues to handle tax on payments routed to Dodo Payments as Merchant of Record. > [accordion] What happens to active subscriptions if I disable a processor? > > Renewals on that processor fail while it's disabled, because each subscription renews on the processor it was created on. These renewals appear as failed payments in the dashboard. > Dodo Payments also pauses payment recovery emails for those subscriptions. Re-enable the processor to restore renewals; paused recovery attempts then resume. ## Get Started > [card] [What is Merchant of Record?](/features/mor-introduction) > > Understand how the Dodo Payments full-service Merchant of Record model works. # Adyen - Connect & Raw Card API Access Source: https://docs.dodopayments.com/features/byop/adyen Enable raw card data access on Adyen, then collect the API key, merchant account, and HMAC key to connect Adyen to Bring Your Own Processor (BYOP). This guide prepares your Adyen account for [Bring Your Own Processor (BYOP)](/features/byop): you request raw card data access from Adyen, then collect the API key, merchant account, and HMAC key that Dodo Payments needs. If you need help, [talk to us](mailto:founders@dodopayments.com). ## Enable Raw Card Data Access Before Dodo Payments can route payments through Adyen, your Adyen account needs **raw card data access**. Adyen enables it only for PCI DSS compliant setups. **Dodo Payments handles the raw card data on your behalf** and is **PCI DSS Level 1 compliant**, so you don't need your own card data environment. Adyen still asks for your own PCI DSS Self-Assessment Questionnaire (SAQ) or Attestation of Compliance that names Dodo Payments in Part 2f, together with the **Dodo Payments Attestation of Compliance (AOC)**. > [card] [Dodo Payments PCI DSS Attestation of Compliance (AOC)](https://pub-2a89184e4c954b599464449d23f506bb.r2.dev/dodo-payments-pci-dss-aoc.pdf) > > Download the current Dodo Payments AOC and submit it to Adyen support to enable raw card data access. To request raw card data access for your merchant account, contact Adyen support and attach the AOC. ## What You'll Need To connect Adyen in **Settings → BYOP**, you need three values from your Adyen Customer Area: | Value | Where it comes from | | - | - | | **API key** | **Developers → API credentials** | | **Merchant Account** | Your Adyen merchant account identifier | | **HMAC key** | Generated when you set up the webhook | > [!NOTE] > > Adyen keeps **test** (`ca-test.adyen.com`) and **live** (`ca-live.adyen.com`) credentials separate. Generate credentials in the Customer Area that matches the Dodo Payments mode you're configuring. ## Step 1: Generate an API Key To generate an API key, you need the **Manage API credentials** or **Merchant admin** role in the Customer Area. **1. Open API Credentials** Log in to the Adyen Customer Area, select your **Company** account, and go to **Developers → API credentials**. **2. Select Your Credential** Select the **Payments** tab, then select your credential username. It looks like `ws_123456@Company.YourCompanyAccount`. **3. Generate the Key** Under **Server settings → Authentication**, open the **API key** tab and select **Generate API key**. **4. Copy It Immediately** Select the copy icon and store the key securely. You can't copy it again after you leave the page. Then select **Save changes**. A newly generated key is active immediately, and the previous key keeps working for 24 hours. In Dodo Payments, paste the key into the **Secret Key** field. ## Step 2: Find Your Merchant Account Your **merchant account** is the account identifier that Adyen uses to process your transactions. To find it, go to **Settings → Merchant accounts** in the Customer Area, for example `YourCompany_ECOM`. Paste the identifier into the **Merchant Account** field in Dodo Payments. After setup, the merchant account is stored securely and can't be changed. ## Step 3: Set Up the Webhook and HMAC Key When you save the Adyen connection, Dodo Payments generates a **Webhook Endpoint** URL. Add it as a webhook in Adyen, then generate an HMAC key. You need the **Merchant admin** or **Merchant technical integrator** role. **1. Create a Webhook** In the Customer Area, go to **Developers → Webhooks** and select **Create new webhook**. In the list of webhook types, select **Add** next to **Standard webhook**. **2. Configure the Webhook** * Enter a **Description**. * Turn on the **Enabled** toggle. * Under **Server configuration**, paste the **Webhook Endpoint** URL that Dodo Payments generated into the **URL** field. The URL must be HTTPS and publicly accessible. **3. Generate the HMAC Key** Under **Security**, in the **HMAC Key** section, select **Generate** to create a new HMAC key. Copy the key and store it securely. Then select **Save configuration**. **4. Paste the HMAC Key into Dodo** In **Settings → BYOP**, paste the HMAC key into the **Webhook Signing Secret** field, then select **Save & continue** to finish the connection. > [card] [Set up BYOP](/features/byop) > > Follow the full Bring Your Own Processor setup flow. > [!TIP] > > Until you save the HMAC key, the Adyen connection shows as **Incomplete** under **Edit Configuration** in **Settings → BYOP**. After you save it, the connection shows as **Connected**. ## Frequently Asked Questions > [accordion] What is the HMAC key for? > > Adyen signs every webhook with an HMAC signature, so the receiver can verify the notification's integrity and origin. Dodo Payments uses the HMAC key you provide to validate webhooks from your Adyen account. > [accordion] I lost my API key or HMAC key, what now? > > You can't copy an API key again after you leave the page. To replace the HMAC key, generate a new one in the webhook settings in Adyen. Then open **Settings → BYOP**, select **Edit Configuration**, edit the Adyen connection, paste the key into **Webhook Signing Secret**, and select **Save & continue**. > > The Dodo dashboard doesn't let you change a saved API key. To replace it, generate a new one under **Developers → API credentials**, then contact [support@dodopayments.com](mailto:support@dodopayments.com) to update the connection. > [accordion] Do test and live use the same credentials? > > No. Generate credentials in the matching environment, test (`ca-test.adyen.com`) or live (`ca-live.adyen.com`), and configure them in the matching mode in Dodo Payments. Adyen also requires a new HMAC key when you switch from test to live. ## References * [Adyen: API credentials](https://docs.adyen.com/development-resources/api-credentials/) * [Adyen: Configure and manage webhooks](https://docs.adyen.com/development-resources/webhooks/configure-and-manage) # Stripe - Connect & Raw Card API Access Source: https://docs.dodopayments.com/features/byop/stripe Enable raw card data API access on Stripe with the Dodo Payments PCI DSS AOC, then connect your Stripe account to Bring Your Own Processor (BYOP). This guide prepares your Stripe account for [Bring Your Own Processor (BYOP)](/features/byop): you request raw card data API access from Stripe, then collect the secret key and webhook signing secret that Dodo Payments needs. If you need help, [talk to us](mailto:founders@dodopayments.com). ## Enable Raw Card Data Access To route payments through your Stripe account, Dodo Payments sends card details to Stripe on your behalf through Stripe's **raw card data APIs**. By default, a Stripe account can't send raw card numbers (PANs) to its APIs. Stripe enables this access only after it confirms that the systems handling raw card data are **PCI DSS compliant**. With BYOP, the system that handles card data is **Dodo Payments**, which is PCI DSS Level 1 compliant, so you prove compliance with the Dodo Payments certification rather than your own. You request this access once per account. When you request access, Stripe asks for a short description of how card data is handled. State that **Dodo Payments**, your PCI DSS Level 1 compliant payment provider, processes the raw card data, and that your own systems never store or touch raw card numbers. Because you fully outsource card handling to Dodo Payments, you don't need your own SAQ D if you qualify for SAQ A. Submit your own **SAQ A** that lists Dodo Payments as the third-party service provider in Part 2f, and include the **Dodo Payments Attestation of Compliance (AOC)** as supporting proof: > [card] [Dodo Payments PCI DSS Attestation of Compliance (AOC)](https://pub-2a89184e4c954b599464449d23f506bb.r2.dev/dodo-payments-pci-dss-aoc.pdf) > > Download the current Dodo Payments AOC and submit it to Stripe when you request raw card data access. > [!TIP] > > **Test mode requires no documentation.** If you need the raw card data APIs only for testing and can't use Stripe's pre-tokenized test cards, ask Stripe support to enable them, so you can build and check your BYOP setup. Live mode still requires your SAQ A and the Dodo Payments AOC. To request access, follow Stripe's guide, and submit the Dodo Payments AOC when Stripe asks for PCI documentation: > [card] [Enabling access to raw card data APIs](https://support.stripe.com/questions/enabling-access-to-raw-card-data-apis) > > Stripe's guide to requesting raw card data API access on your account. ## What You'll Need After Stripe confirms raw card data access, connect Stripe in **Settings → BYOP**. You need two values from your Stripe Dashboard: | Value | Where it comes from | | - | - | | **Secret key** | The **API keys** page | | **Webhook signing secret** | The webhook endpoint you add for Dodo Payments | > [!NOTE] > > Stripe keeps sandbox (test) and live mode credentials separate. Use a Stripe sandbox for Dodo Payments test mode, and Stripe live mode for Dodo Payments live mode. ## Step 1: Get Your Secret Key **1. Open API Keys** In the Stripe Dashboard, open the **API keys** page. Switch between sandbox and live mode to match the Dodo Payments mode you're configuring. **2. Copy Your Secret Key** Copy the **Secret key**. It starts with `sk_test_` in a sandbox and `sk_live_` in live mode. Use a standard secret key: restricted keys (`rk_...`) aren't supported. In live mode, Stripe shows a secret key that you create only once, so copy it before you close the dialog. Paste the key into the **Secret Key** field in Dodo Payments. ## Step 2: Set Up the Webhook and Signing Secret When you save the Stripe connection, Dodo Payments generates a **Webhook Endpoint** URL. Add it to Stripe as a webhook endpoint, then copy the endpoint's signing secret. **1. Create an Event Destination** In the Stripe Dashboard, open the **Webhooks** tab in Workbench and select **Create an event destination**. Select **Your account**, then select all events. Dodo Payments needs the endpoint to receive every event type. **2. Add the Endpoint URL** Choose **Webhook endpoint** as the destination type. In **Endpoint URL**, paste the **Webhook Endpoint** URL that Dodo Payments generated. Stripe accepts only publicly accessible HTTPS URLs. **3. Reveal the Signing Secret** On the endpoint's settings page, select **Reveal secret** to view the **Signing secret**. It starts with `whsec_`. Each endpoint has its own secret, so sandbox and live endpoints have different secrets. **4. Paste the Signing Secret into Dodo** In **Settings → BYOP**, paste the signing secret into the **Webhook Signing Secret** field, then select **Save & continue** to finish the connection. > [card] [Set up BYOP](/features/byop) > > Follow the full Bring Your Own Processor setup flow. > [!TIP] > > Until you save the signing secret, the Stripe connection shows as **Incomplete** under **Edit Configuration** in **Settings → BYOP**. After you save it, the connection shows as **Connected**. ## Frequently Asked Questions > [accordion] Do I need my own PCI certification (SAQ D)? > > No, if you qualify for SAQ A. **Dodo Payments handles the raw card data on your behalf** and is **PCI DSS Level 1 compliant**, so you submit your own SAQ A that lists Dodo Payments in Part 2f, together with the **Dodo Payments Attestation of Compliance (AOC)**, instead of completing SAQ D or a separate audit. > [accordion] Why doesn't Stripe enable this by default? > > Sending raw card numbers to an API brings the sending system into PCI DSS scope. Stripe requires proof of PCI compliance before it enables raw card data APIs, so that cardholder data stays protected. Dodo Payments is **PCI DSS Level 1 compliant**, so you provide the Dodo Payments AOC as that proof. > [accordion] Can I test BYOP before getting live approval? > > Yes. Ask Stripe to enable raw card data APIs in test mode, which needs no PCI documentation, and connect Stripe in test mode in Dodo Payments. You need live mode approval before you process real payments. > [accordion] I lost my secret key or signing secret, what now? > > To view the signing secret again, open the webhook endpoint in Stripe and select **Reveal secret**. To update it in Dodo Payments, open **Settings → BYOP**, select **Edit Configuration**, edit the Stripe connection, paste the secret into **Webhook Signing Secret**, and select **Save & continue**. > > If you lose a live secret key that you created, Stripe can't show it again, so rotate it or create a new key on the **API keys** page. The Dodo dashboard doesn't let you change a saved secret key. To replace the secret key on an existing connection, contact [support@dodopayments.com](mailto:support@dodopayments.com). ## References * [Dodo Payments PCI DSS Attestation of Compliance (AOC)](https://pub-2a89184e4c954b599464449d23f506bb.r2.dev/dodo-payments-pci-dss-aoc.pdf) * [Stripe Support: Enabling access to raw card data APIs](https://support.stripe.com/questions/enabling-access-to-raw-card-data-apis) * [Stripe: API keys](https://docs.stripe.com/keys) * [Stripe: Webhook signing secret](https://docs.stripe.com/webhooks/signature) # Cart Value Limit Source: https://docs.dodopayments.com/features/cart-value-limit Understand the maximum cart value a customer can pay in one live checkout, how Dodo Payments enforces it, and how to request a higher limit. The cart value limit is the highest cart value a customer can pay in one live mode checkout. Dodo Payments compares the cart value before tax with your business's limit. It refuses any product price, checkout, add-on, or renewal that goes above the limit. You can see your limit, and request a higher one, in **Settings → Pricing**. ![Cart value limit row in Pricing settings, showing the current limit and a Request increase button](https://mintcdn.com/dodopayments/SFgZRVwKwWVJiW4d/images/cart-value-limit/pricing-settings.png?fit=max\&auto=format\&n=SFgZRVwKwWVJiW4d\&q=85\&s=f15cf43d5490978c85330b4796d79728) ## How the Limit Works A cart value limit may apply to your business. Dodo Payments sets a default limit. The risk team can set a higher limit for a business after it reviews a request. The limit follows these rules: * **Live mode only.** The limit applies to live mode payments. Test mode is not limited. See [Test Mode](#test-mode). * **Before tax.** Tax never counts toward the limit. The amount the customer pays can be higher than the limit by the tax amount. * **In USD.** The limit is a USD amount. Dodo Payments converts a cart in another currency to USD before it compares the cart with the limit. * **Per checkout.** The limit applies to the cart of one checkout, not to the total of all your sales. * **Up to the limit.** A cart equal to the limit is allowed. A cart above the limit is refused. ### What Counts Toward the Limit The cart value is the subtotal of the checkout before tax. This table lists what is in it. | Item | Counts toward the limit | | :- | :- | | Product price × quantity, for every product in the cart | Yes | | [Add-ons](/features/addons) × quantity | Yes | | The amount a customer enters for a [Pay What You Want](/features/pay-what-you-want) product | Yes | | Discounts | Yes, as a reduction. The limit is compared with the subtotal after discounts | | Tax | No | Dodo Payments compares the prices you set, before [Adaptive Currency](/features/adaptive-currency) conversion and [Charm Pricing](/features/charm-pricing) rounding. For example, a business with a limit of 10,000 USD can sell a 4,000 USD product with a quantity of 2. The cart value is 8,000 USD. A quantity of 3 makes the cart value 12,000 USD, so Dodo Payments refuses the checkout. The tax on top of the 8,000 USD does not count. ## Finding Your Limit To see the limit that applies to your business, go to **Settings → Pricing** and find the **Cart value limit** row. It shows your limit in USD. The limit shown is your business's own limit if the risk team set one. Otherwise, it is the default limit. ## Requesting a Higher Limit To sell a product, plan, or cart above your limit, request a higher limit. Your business can have one open request at a time. **1. Open the Request Form** Go to **Settings → Pricing**. In the **Cart value limit** row, click **Request increase**. You can also open the form from a product. When a product price is above your limit, click **Request a higher limit** under the price field. **2. Enter the New Limit** In **New maximum cart value**, enter the limit you need in USD. The amount must be above your current limit. **3. Explain Why You Need It** In **Why do you need a higher limit?**, describe what you sell and why a customer pays more than your current limit in one checkout. The reason can be up to 2,000 characters. **4. Attach Supporting Documents** Optionally, upload files that help the risk team review your request. For example, a paid invoice or emails with your customer. You can upload up to 5 files in PDF, PNG, or JPG format, up to 10 MB each. ![Request higher maximum cart value form with the new maximum cart value, the reason, and the supporting documents upload area](https://mintcdn.com/dodopayments/SFgZRVwKwWVJiW4d/images/cart-value-limit/request-increase-form.png?fit=max\&auto=format\&n=SFgZRVwKwWVJiW4d\&q=85\&s=c89f9879a20dd3efc86272352e334479) **5. Submit the Request** Click **Submit request**. > [!TIP] > > The **Cart value limit** row shows an **Under review** badge with the amount you requested. **Request increase** is unavailable until the risk team reviews the request. ![Cart value limit row with an Under review badge and the requested amount](https://mintcdn.com/dodopayments/SFgZRVwKwWVJiW4d/images/cart-value-limit/request-under-review.png?fit=max\&auto=format\&n=SFgZRVwKwWVJiW4d\&q=85\&s=7ddcdb47b032a7fcab2c7b71576d32db) ### After the Review Dodo Payments sends you an email when the risk team reviews your request. | Result | What happens | | :- | :- | | **Approved** | Your limit changes to the approved amount and applies to new checkouts right away. You do not need to do anything. | | **Denied** | Your current limit stays in place. You can submit a new request later from **Settings → Pricing**. | ## Products Priced Above the Limit In live mode, you cannot create or update a product, an add-on, or a localized price with a price above your limit. This applies to the dashboard and the API. For a [Pay What You Want](/features/pay-what-you-want) product, the check uses the **Minimum Price**. In the dashboard, the price field shows **The price is more than the cart value limit of this business.** and the product is not saved. Click **Request a higher limit** to open the request form. A single product can be priced up to the limit. A product priced at your limit can be sold, but the customer cannot add more units or paid add-ons to that checkout. > [!WARNING] > > Existing products and subscriptions are not changed when a limit applies to them. If their cart value is above your limit, their checkouts and renewals are refused. Request a higher limit before you sell them. ## What Customers See at Checkout Dodo Payments checks the cart when the checkout is created. It checks the cart again each time the customer changes a quantity, an add-on, or a Pay What You Want amount. The message does not show your limit to the customer. | Situation | What the customer sees | | :- | :- | | The cart is above the limit when the checkout is created | This product is currently unavailable for purchase. Please contact the seller. | | A Pay What You Want amount puts the cart above the limit | This amount is above the maximum allowed. Please enter a lower amount. | | One more unit or add-on would put the cart above the limit | The control to increase the quantity is disabled, with the message **Maximum order amount reached.** | ### Subscriptions The limit also applies to subscriptions: * **Subscription checkout.** It follows the same rules as any other checkout. * **Renewals.** Dodo Payments checks each renewal payment before it charges the customer. This includes a renewal that goes above the limit because of more seats or add-ons. See [Seat-Based Billing](/features/seat-based-billing) and [Add-ons](/features/addons). Usage-based meter charges do not count toward the limit. * **Plan changes.** A plan change that goes above the limit is refused. * **On-demand charges.** Dodo Payments checks each [on-demand charge](/api-reference/subscriptions/create-charge) on its own. A charge above the limit is refused with the message: The charge amount is more than the cart value limit of this business. Split it into smaller charges. When a renewal is above the limit, Dodo Payments does not send the payment to the processor: 1. The payment is marked as failed with the error code `CART_AMOUNT_EXCEEDS_LIMIT`. 2. Dodo Payments sends the `payment.failed` webhook and the failed payment email to the customer. 3. Dodo Payments retries the payment on the usual retry schedule. To collect the payment, request a higher limit, then retry the payment. The payment details page in the dashboard shows a **Request a higher limit** link for these payments. ## Handling the Limit in the API When a request goes above the limit, the API returns HTTP `422` with the code `CART_AMOUNT_EXCEEDS_LIMIT`. These endpoints return it: * [Create Product](/api-reference/products/post-products) and [Update Product](/api-reference/products/patch-products), when the price or Pay What You Want minimum price is above the limit. * [Create Add-on](/api-reference/addons/create-addon) and [Update Add-on](/api-reference/addons/update-addon), when the price is above the limit. * [Create Checkout Session](/api-reference/checkout-sessions/create) and [Preview Checkout Session](/api-reference/checkout-sessions/preview), when the cart is above the limit. Create Checkout Session does not create the session. * [Create Charge](/api-reference/subscriptions/create-charge), when the on-demand charge is above the limit. The product and add-on endpoints return this response: ```json theme={null} { "code": "CART_AMOUNT_EXCEEDS_LIMIT", "message": "The price is more than the cart value limit of this business." } ``` Branch on `code`, not on `message`. The checkout endpoints return the customer-facing messages listed in [What Customers See at Checkout](#what-customers-see-at-checkout). ### Building Your Own Quantity Controls To disable a quantity control before the customer reaches the limit, use [Preview Checkout Session](/api-reference/checkout-sessions/preview). Each add-on in the response has a `max_quantity_reached` field: | Value | Meaning | | :- | :- | | `true` | One more unit of this add-on puts the cart above the limit. | | `false` | The limit does not stop one more unit of this add-on. | The response has no matching field for product quantity. To check a product quantity, preview the cart with the new quantity. A cart above the limit returns `CART_AMOUNT_EXCEEDS_LIMIT`. ## Test Mode The limit does not apply in test mode. You can create a test product at any price and test a checkout of any cart value. To test what customers see when a cart is above the limit, use live mode. See [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). ## Frequently Asked Questions > [accordion] Why does the amount charged go above my limit? > > The limit compares the cart value before tax. Tax is added after the check, so the total the customer pays can be above the limit by the tax amount. > [accordion] Does the limit apply to the total of my sales? > > No. The limit applies to the cart of one checkout. Dodo Payments checks each checkout on its own. > [accordion] I sell in EUR. How is my cart compared with a USD limit? > > Dodo Payments converts the cart value to USD, then compares it with your limit. A cart of the same amount in EUR can be above or below the limit as exchange rates change. > [accordion] Can I see the status of my request? > > Yes. While the request is open, the **Cart value limit** row in **Settings → Pricing** shows **Under review** and the amount you requested. Dodo Payments emails you the result. ## Related > [card] [Products](/features/products) > > Create and manage the products in your catalog. > [card] [Pay What You Want](/features/pay-what-you-want) > > Let customers choose their price above a minimum. > [card] [Add-ons](/features/addons) > > Sell extra units and features with a subscription. > [card] [Error Codes](/api-reference/error-codes) > > Every error code the API returns. # Charm Pricing Source: https://docs.dodopayments.com/features/charm-pricing Round converted prices to clean, psychologically-tuned endings like 49.99 automatically, in every currency, without setting a price per market by hand. Charm Pricing rounds the converted price to a clean ending, such as **49.99**, on every checkout. You set the rule once. Dodo Payments applies it in each customer's currency. ## What Is Charm Pricing? [Adaptive Currency](/features/adaptive-currency) converts your base price at live exchange rates. The result is an accurate number, but rarely an attractive one: a \$47.00 product can show as **€43.12** today and **€43.47** tomorrow. Charm Pricing takes that converted amount and moves it to the nearest clean ending. The customer sees **€49.99**, not €43.12. The ending stays stable while exchange rates move. You do not set a price per market. You choose one rounding rule, and it applies to every currency. > [!NOTE] > > Charm Pricing requires [Adaptive Currency](/features/adaptive-currency). Turn on Adaptive Currency first. ## Key Benefits * **Clean prices in every currency** — One rule covers all markets. You do not maintain a price list. * **Stable endings** — The ending does not change when the exchange rate moves a few percent. * **No conversion artifacts** — Customers never see 43.12 or 1043.87. * **Automatic for new markets** — A currency you never priced still gets a clean number. > [!NOTE] > > To set an exact price for one market by hand, use [Localized Pricing](/features/localized-pricing) instead. A localized price always wins over Charm Pricing on that product. ## Enable Charm Pricing **1. Enable Adaptive Currency** Go to **Settings → Pricing** and turn on **Adaptive Currency**. Charm Pricing does nothing without it. ![Adaptive Currency toggle in Pricing settings](https://mintcdn.com/dodopayments/Ovz6j1aDoP1Nl_kB/images/charm-pricing/adaptive-currency-toggle.png?fit=max\&auto=format\&n=Ovz6j1aDoP1Nl_kB\&q=85\&s=a9d847b5ee912ddf416bba76f7f75994) **2. Turn On Charm Pricing** On the same **Settings → Pricing** page, turn on **Charm Pricing** — "Round prices to cleaner, more appealing numbers". The current rounding type appears below the toggle. ![Charm Pricing enabled in Pricing settings](https://mintcdn.com/dodopayments/Ovz6j1aDoP1Nl_kB/images/charm-pricing/charm-toggle.png?fit=max\&auto=format\&n=Ovz6j1aDoP1Nl_kB\&q=85\&s=e8038d1b4c0df6a0ed246af73e83011c) > [!WARNING] > > Changes apply only to future transactions. Existing subscriptions keep the rounding rule they started with. See [Subscriptions](#subscriptions). **3. Set the Rounding Type and Steps** Click **Edit** to open **Set up Charm Pricing**. Choose a **Rounding type**, then adjust the **Rounding step** for any price range. Click **Save Changes**. ![Set up Charm Pricing dialog with the rounding type selector and the Try it preview](https://mintcdn.com/dodopayments/Ovz6j1aDoP1Nl_kB/images/charm-pricing/rounding-type.png?fit=max\&auto=format\&n=Ovz6j1aDoP1Nl_kB\&q=85\&s=52b3cac8b3644aa2e129019cc989b617) Use **Try it** to check a value before you save. Enter an amount and a currency, and the dialog shows the result and the step it used. Dodo Payments ships a default step for each range. See [Rounding types](#rounding-types) and [Rounding steps](#rounding-steps). ![Rounding step table, one step for each price range](https://mintcdn.com/dodopayments/Ovz6j1aDoP1Nl_kB/images/charm-pricing/bands.png?fit=max\&auto=format\&n=Ovz6j1aDoP1Nl_kB\&q=85\&s=49814c0af4e7d120d4ae64c868943a84) **4. Confirm at Checkout** > [!TIP] > > Open a test checkout with a billing country in another currency. Confirm the price shows the ending you expect. ## How the Price Is Calculated Dodo Payments charms the **per-unit list price**, after currency conversion and before any discount, and before tax. A discount is then deducted from the charmed list price — see [Discounts and Charm Pricing](#discounts-and-charm-pricing). 1. **Find the step.** The list price selects a step from the rounding-step table. A \$47 price falls in the 10–99 range, so the step is **10**. The step is chosen by the list price, so a product lands in the same band whatever discount code the customer holds. 2. **Pick the target.** The step gives two candidates, **40** and **50**. The rounding type picks one. With **Nearest**, 47 is closer to 50. 3. **Shave the ending.** Dodo Payments subtracts one thousandth of the step, so 50 becomes **49.99**. The shave is never less than one minor unit. **Whole** skips this step. ### Rounding Types | Type | What it picks | \$47 becomes | | :- | :- | :- | | **Nearest** | The closer of the two candidates. A tie goes up. | \$49.99 | | **Floor** | Always the candidate below the price. | \$39.99 | | **Ceiling** | Always the candidate above the price. | \$49.99 | | **Whole** | The nearest candidate, with no shave. | \$50.00 | > [!WARNING] > > **Floor** can lower a price by almost a full step. A \$47 price becomes \$39.99, a cut of 15%. Check the effect on your price ranges before you choose it. ### Rounding Steps The step depends on the size of the price, in the currency's main unit. These are the defaults. You can change the **Rounding step** for any range. You cannot change the ranges themselves. | Price range | Step | | :- | :- | | 1–9 | 1 | | 10–99 | 10 | | 100–999 | 100 | | 1,000–9,999 | 1,000 | | 10,000–99,999 | 10,000 | | 100,000–999,999 | 10,000 | | 1,000,000–9,999,999 | 10,000 | | 10,000,000 and above | 10,000 | The step stops growing at 10,000. This keeps the change small for large amounts, and it matters for currencies with many units per dollar, such as IDR and VND. > [!NOTE] > > A large step moves a price a long way. With the default step of 1,000, a converted price of **\$1,234** becomes **\$999.00**. Lower the step for that range if the change is too big for your catalogue. ### Worked Examples | Converted price | Currency | Step | Rounding type | Customer pays | | :- | :- | :- | :- | :- | | \$47.00 | USD | 10 | Nearest | **\$49.99** | | \$47.00 | USD | 10 | Whole | **\$50.00** | | \$47.00 | USD | 10 | Floor | **\$39.99** | | \$5.00 | USD | 1 | Nearest | **\$4.99** | | ¥4,700 | JPY | 1,000 | Nearest | **¥4,999** | | ¥5 | JPY | 1 | Nearest | **¥4** | > [!NOTE] > > Currencies with no decimal places, such as JPY, have no fractional endings: the shave is the step divided by 1,000, rounded to whole units, with a minimum of one unit. The ending is ¥4,999, not ¥4,999.99. ### When Charm Does Not Apply Dodo Payments keeps the converted price unchanged in these cases: * The step is wider than the price. The price cannot move by less than one full step. * The result would be zero or less. * No step matches the amount. ## How It Applies at Checkout Charm Pricing sets the price the customer sees before any discount is deducted. For a product with no localized price, the order is: 1. **Base price** — the price you set on the product. 2. **[Purchasing Power Parity](/features/purchasing-power-parity)** — if the product opted in, the country percentage applies. 3. **[Currency conversion](/features/adaptive-currency)** — the amount converts to the customer's currency at the live rate. 4. **Charm rounding** — the converted list price moves to the clean ending. This is the price the customer sees as the subtotal. 5. **Discounts** — any product discount and [discount code](/features/discount-codes) is deducted from the charmed list price. 6. **Tax** — calculated from the amount after the discount. See [Tax-Inclusive Pricing](/features/tax-inclusive-pricing). Each cart line is calculated on its own. Charm rounding runs once, on the list price. Nothing rounds the discounted amount a second time. ### Discounts and Charm Pricing Charm Pricing owns the price tag, and a discount is a deduction from that tag. On a \$199.00/month plan with a step of 100 and **Nearest** rounding: ```text theme={null} list 199.00 → charm → 199.90 (Subtotal) 10% of the charmed list 19.99 (Discount) paid 199.90 − 19.99 = 179.91 (Total) ``` How the discount carries onto the charmed list price depends on its type: | Discount on the line | What carries | Why | | :- | :- | :- | | Percentage codes only, with no maximum | The **rate** | A rate is a proportion of the price, so it follows the price. | | Any flat-amount code, or a percentage code with a maximum | The **amount** | A flat code names an amount, so the amount must not scale with the step. | > [!NOTE] > > A discounted line does not land on a charm ending. The charmed list price carries the `.99` or `.90` ending; a percentage taken off it has no reason to. In the example above the customer is charged **\$179.91**, not a charmed number. A product with a slashed (compare-at) price shows a real discount row, since the slash is carried as a deduction in the same way. A fully discounted line stays free, and a flat code larger than the charmed list price is clamped to free rather than going negative. > [!WARNING] > > **Existing charmed subscriptions that carry a discount can change price at their next renewal.** The renewal prices on the charmed list price rather than on a re-charmed discounted price. Under **Nearest** or **Ceiling** the charmed list sits at or above the list price, so a percentage code usually charges slightly more than before. Under **Floor** it can sit well below, so the same code can charge less. > [!WARNING] > > **A charmed line makes the whole transaction fees-inclusive.** The customer pays exactly the ending they saw, so the Adaptive Currency conversion fee cannot be added on top. You absorb that fee. See [Enable Fees Inclusive](/features/adaptive-currency#enable-fees-inclusive). ## Subscriptions A subscription records its rounding step and rounding type when the customer subscribes. Dodo Payments repeats that same decision at every renewal. **What is frozen:** the rounding step and the rounding type. If you edit a step, or change the rounding type, an existing subscription is not repriced. The customer keeps the rule they agreed to. **What can move:** the amount. Each renewal converts the price at the current exchange rate, then applies the frozen rule. A large rate movement can change the renewal amount, even though the rule did not change. > [!WARNING] > > **A plan change removes charm from that subscription.** When a subscriber [changes plan](/features/subscription#subscription-plan-changes), the new plan bills the amount the plan-change quote showed. Dodo Payments does not charm that amount, and it does not charm later renewals of that subscription. ## Important Behaviors | Behavior | Detail | | :- | :- | | **Requires Adaptive Currency** | Charm Pricing does nothing while Adaptive Currency is off. | | **Localized prices win** | A product with a matching [Localized Pricing](/features/localized-pricing) rule is never charmed. The exact amount you set applies. | | **Applied per unit** | The unit price is charmed, then multiplied by the quantity. | | **Before discounts** | Charm rounds the converted list price. A discount is then deducted from that charmed price. See [Discounts and Charm Pricing](#discounts-and-charm-pricing). | | **Before tax** | Tax is calculated after charm rounding and after any discount, so the totals agree. | | **Forces fees-inclusive** | You absorb the currency conversion fee on a charmed transaction. | | **Not for Pay What You Want** | The customer chooses the amount, so it is never charmed. See [Pay What You Want](/features/pay-what-you-want). | | **Fixed fees only for usage-based** | Metered usage charges are never charmed. | | **No webhook of its own** | The charmed amount appears on the payment or subscription like any other price. | ## Best Practices * **Start with Nearest.** It moves the price the least. Use Floor only when you accept the discount it creates. * **Check your largest and smallest products.** The step changes with the price range, so a \$5 product and a \$1,200 product behave differently. * **Review the step for high-unit currencies.** IDR, VND, and KRW prices land in the top ranges, where the step is fixed at 10,000. * **Price your subscriptions before you launch.** Editing a step later does not reprice existing subscribers. * **Account for the conversion fee.** A charmed line is fees-inclusive, so the fee comes out of your revenue. ## Related > [card] [Adaptive Currency](/features/adaptive-currency) > > The conversion Charm Pricing rounds. Required for Charm Pricing. > [card] [Purchasing Power Parity](/features/purchasing-power-parity) > > Charge less in price-sensitive countries. Runs before charm rounding. > [card] [Localized Pricing](/features/localized-pricing) > > Set an exact price per country or currency. Overrides Charm Pricing. > [card] [Tax-Inclusive Pricing](/features/tax-inclusive-pricing) > > Control whether your prices include tax. # Checkout Features Source: https://docs.dodopayments.com/features/checkout Conversion-optimized, globally compliant checkout with multi-currency, multi-language support, automatic tax calculation, discount codes, add-ons, and smart address collection. ![Checkout page](https://mintcdn.com/dodopayments/Vafy52417ELLVDIx/images/checkout/cover.png?fit=max\&auto=format\&n=Vafy52417ELLVDIx\&q=85\&s=2dc0a0db8e021e39fb17e84fc12eb5f9) Dodo Payments checkout is a hosted payment page designed for digital products and SaaS. It handles currency conversion, tax calculation, discount codes, address collection, and payment method selection. You create a checkout session via API or dashboard, and customers complete payment on a secure, branded page. > [card] [Checkout Sessions API](/api-reference/checkout-sessions/create) > > Create checkout sessions programmatically. > [card] [Preview Checkout](/api-reference/checkout-sessions/preview) > > Calculate pricing and taxes before creating a session. > [card] [Payment Methods](/features/payment-methods) > > Supported payment methods and configuration. > [card] [Integration Guide](/developer-resources/checkout-session) > > Step-by-step guide to integrating checkout. > [!NOTE] > > Checkout links generated through the [Checkout Sessions API](/api-reference/checkout-sessions/create) are not reusable. They expire after 24 hours, or after 15 minutes if `confirm: true` is set. Generate a fresh session for each customer and each payment attempt. ## Adaptive Currency Adaptive Currency lets customers pay in their preferred local currency, improving trust and conversion rates. When enabled, customers see a currency selector on checkout. The price converts to their chosen currency at live FX rates. If the product has [Purchasing Power Parity](/features/purchasing-power-parity) enabled, the PPP-adjusted price converts instead of the base price. If [Charm Pricing](/features/charm-pricing) is enabled, the converted amount rounds to a clean ending like 49.99. ![Currency selector on checkout](https://mintcdn.com/dodopayments/Vafy52417ELLVDIx/images/checkout/c1.png?fit=max\&auto=format\&n=Vafy52417ELLVDIx\&q=85\&s=c2f9ee4b1748448d4ab7ab23954dcc64) To enable Adaptive Currency, go to **Settings → Pricing** and toggle it on. > [card] [Adaptive Currency](/features/adaptive-currency) > > Supported currencies, conversion fees, and refund handling. ## Multi-Language Checkout Checkout supports 24 languages. Customers can switch languages directly on the page, and UI text, labels, and system messages are localized. In Arabic and Hebrew, checkout renders right to left and the whole layout mirrors. Email addresses, codes, and phone numbers keep their natural reading order. ![Language selector on checkout](https://mintcdn.com/dodopayments/Vafy52417ELLVDIx/images/checkout/c2.png?fit=max\&auto=format\&n=Vafy52417ELLVDIx\&q=85\&s=ecc6eb8db604e37433d8797c51768577) ### Supported Languages | Language | Code | | - | - | | Arabic | `ar` | | Catalan | `ca` | | Chinese | `zh` | | Croatian | `hr` | | Dutch | `nl` | | English | `en` | | French | `fr` | | Georgian | `ka` | | German | `de` | | Hebrew | `he` | | Indonesian | `id` | | Italian | `it` | | Japanese | `ja` | | Korean | `ko` | | Malay | `ms` | | Polish | `pl` | | Portuguese | `pt` | | Romanian | `ro` | | Russian | `ru` | | Serbian | `sr` | | Spanish | `es` | | Swedish | `sv` | | Thai | `th` | | Turkish | `tr` | To force a specific language, set `customization.force_language` when creating a checkout session. See the [Checkout Sessions API](/developer-resources/checkout-session) for details. ## Automatic Tax Calculation Taxes are calculated automatically based on the customer's billing location, ensuring compliance with GST, VAT, and sales tax requirements. Tax rules apply based on the customer's country and region where applicable. The tax amount updates automatically when the customer changes their country or updates their address. The final tax breakdown is shown clearly before payment. > [!TIP] > > Tax calculation is fully automated. No manual configuration required for standard digital goods and SaaS products. ## Business Tax ID Support For B2B transactions, checkout allows customers to enter their Business Tax ID (e.g., VAT or GST number). When entered, the tax ID is validated in real-time and applicable tax exemptions or reverse-charge rules are applied automatically. ![Business Tax ID entry on checkout](https://mintcdn.com/dodopayments/Vafy52417ELLVDIx/images/checkout/c3.png?fit=max\&auto=format\&n=Vafy52417ELLVDIx\&q=85\&s=76451fed5636a6ef3e5c3ec7f6a96c9f) ## Discount Codes Customers can apply discount or promo codes you've created in the dashboard. The discount is validated instantly and the updated price is shown. When [Purchasing Power Parity](/features/purchasing-power-parity) is enabled on a product, the discount applies to the PPP-adjusted price, not the base price. ![Discount code entry on checkout](https://mintcdn.com/dodopayments/Vafy52417ELLVDIx/images/checkout/c4.png?fit=max\&auto=format\&n=Vafy52417ELLVDIx\&q=85\&s=639dcc94ddd1b41fdd6ff200c2a28e47) You can pre-apply discount codes or enable the discount input field via the API: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_abc', quantity: 1 } ], discount_codes: ['WELCOME20'], // Pre-apply one or more codes (max 20) feature_flags: { allow_discount_code: true // Shown by default; set to false to hide the field }, return_url: 'https://yoursite.com/return' }); ``` > [!NOTE] > > `discount_codes` accepts an array of up to 20 codes that stack in order. The singular `discount_code` field is deprecated but still works for backward compatibility. > [card] [Discount Codes](/features/discount-codes) > > Create and manage discount codes. > [card] [Validate Discount by Code](/api-reference/discounts/get-discount-by-code) > > Look up and validate discounts using code names. ## Smart Address Collection Checkout supports flexible address entry to balance speed, accuracy, and global coverage. ### Options | Option | Description | | - | - | | **Google Address Autofill** | Quick selection with autocomplete | | **Manual Entry** | Full control for complete addresses | | **Country Selection** | Required for tax and compliance logic | | **Minimal Address Mode** | Collect only country and ZIP where required for tax | ### Minimal Address Mode For maximum conversion, enable minimal address collection to reduce checkout friction. When `minimal_address` is set to `true`, checkout only collects: * **Country** — always required for tax determination * **ZIP/Postal code** — only in regions where it's necessary for sales tax, VAT, or GST calculation All other address fields are skipped. ![Minimal address mode showing only country and ZIP/postal code fields on checkout](https://mintcdn.com/dodopayments/7dyPZdWH7JucnLrT/images/changelog/minimal-address.png?fit=max\&auto=format\&n=7dyPZdWH7JucnLrT\&q=85\&s=cd0e5d6f8c32e052c7ab93a88d841fb8) ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_abc', quantity: 1 } ], minimal_address: true, return_url: 'https://yoursite.com/return' }); ``` > [!NOTE] > > Full address collection is the default, unless [`feature_flags.single_page`](/features/single-page-checkout) is `true`, which turns `minimal_address` on by default. Enable `minimal_address` for digital products and SaaS flows where complete billing details aren't required. ## Phone Number Collection Control whether the phone number field appears on checkout and whether it's required. | Flag | Default | Behavior | | - | - | - | | `allow_phone_number_collection` | `true` | Shows the phone number field | | `require_phone_number` | `false` | Makes the phone number field required | ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_abc', quantity: 1 }], feature_flags: { allow_phone_number_collection: true, require_phone_number: true }, return_url: 'https://yoursite.com/return' }); ``` > [!WARNING] > > `require_phone_number: true` requires `allow_phone_number_collection: true`. The API rejects sessions where phone collection is disabled while phone number is required. ## Custom Fields Collect additional information from customers during checkout by defining custom form fields. This is useful for gathering company name, team size, referral source, or any other business-specific data. ### Available Field Types | Type | Description | | - | - | | `text` | Single-line text input | | `number` | Numeric input | | `email` | Email address with validation | | `url` | URL with validation | | `date` | Date picker | | `dropdown` | Select from predefined options | | `boolean` | Yes/No toggle | ### Example ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_abc', quantity: 1 } ], custom_fields: [ { key: 'company_name', label: 'Company Name', field_type: 'text', required: true }, { key: 'team_size', label: 'Team Size', field_type: 'dropdown', required: true, options: ['1-10', '11-50', '51-200', '200+'] } ], return_url: 'https://yoursite.com/return' }); ``` > [!NOTE] > > Customer responses are automatically included in webhook payloads (`payment.succeeded`, `subscription.active`) and API responses via the `custom_field_responses` array. You can define up to 5 custom fields per checkout session. > [card] [Custom Fields Guide](/developer-resources/checkout-session#collecting-custom-fields) > > Custom field configuration and accessing responses. ## Privacy Policy & Terms Acceptance To ensure legal and compliance transparency: * [Privacy Policy](https://dodopayments.com/privacy-policy) and [Buyer Terms](https://dodopayments.com/buyer-terms) links are clearly displayed on checkout * Customers explicitly acknowledge these before completing payment > [!NOTE] > > This helps meet global consumer protection and data privacy requirements including GDPR compliance. ## Product Collections Product Collections enable a unified checkout experience where customers view and select from multiple related products (e.g., Starter, Pro, Enterprise plans) in a single checkout. When using a collection, all active products in the collection are displayed. The first product is pre-selected, and customers can compare options before choosing. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_collection_id: 'pdc_abc123', product_cart: [], // Required: pass an empty array for collection checkout return_url: 'https://yoursite.com/return' }); ``` > [!WARNING] > > When using `product_collection_id`, pass an empty `product_cart` array. Discount codes cannot be pre-applied at session creation. > [card] [Product Collections](/features/product-collections) > > Create and manage product collections. ## Monthly Price for Yearly Plans Show customers what a yearly plan costs per month. A yearly plan priced at \$677.00 also shows **\$56.42/mo · billed annually** under its price. The customer still pays the yearly price. To turn it on, go to **Settings → Pricing** and turn on **Show yearly prices as monthly**. The change can take up to a minute to appear on checkout. * **Plans it applies to**: Subscriptions billed every year or every 12 months. Other plans and one-time products show no monthly price. * **How it is calculated**: The yearly price of one plan, after discounts, divided by 12 and rounded to the nearest cent or smallest currency unit. Add-ons, tax, and quantity are not included. * **Adaptive Currency**: The monthly price uses the converted price that the customer sees. ## Single Page Checkout Single page checkout collects contact details, billing details, and payment on one page, with no separate payment step. With fewer steps and fewer fields before payment, it is built to reduce drop-off and complete more payments than the two-page checkout. It is off by default. To turn it on for a session, set `feature_flags.single_page` to `true`. For a payment link, add `?singlePage=true`. Overlay and inline checkout follow the flag on the session. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_abc', quantity: 1 } ], feature_flags: { single_page: true }, return_url: 'https://yoursite.com/return' }); ``` > [card] [Single Page Checkout](/features/single-page-checkout) > > How it reduces drop-off, plus layout, address collection, embedded events, and behavior after payment. ## Checkout Session Configuration Control checkout behavior using the Checkout Sessions API: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_abc', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'Jane Doe' }, billing_currency: 'EUR', discount_codes: ['PROMO10'], feature_flags: { allow_discount_code: true }, return_url: 'https://yoursite.com/return', cancel_url: 'https://yoursite.com/pricing', metadata: { order_ref: 'ORD-12345' } }); ``` > [!NOTE] > > After payment, customers are redirected to your `return_url` with query parameters appended automatically -- including `payment_id` or `subscription_id`, `status`, `email`, and `license_key` (if applicable). See the [Checkout Sessions guide](/developer-resources/checkout-session#request-body) for the full list. > [card] [Checkout Sessions API](/api-reference/checkout-sessions/create) > > Complete API reference for checkout sessions. > [card] [Checkout Integration Guide](/developer-resources/checkout-session) > > Step-by-step guide to integrating checkout. ## Theme Customization Customize the checkout page appearance to match your brand using the `customization.theme_config` parameter. Configure colors, fonts, border radius, and button text for both light and dark modes. This section covers the server-side API, which uses property names such as `bg_primary`. A theme set on the session applies to hosted, overlay, and inline checkout. Checkout SDK 2.0.1 removes the client-side `themeConfig` option, which used property names such as `bgPrimary`. See [Overlay Checkout](/developer-resources/overlay-checkout#theme-customization). ![Custom themed checkout page](https://mintcdn.com/dodopayments/rTHkQICkStFgSdh-/images/checkout/theme-example.png?fit=max\&auto=format\&n=rTHkQICkStFgSdh-\&q=85\&s=5277b69d67c90fd87e7c5d9c125fee12) > [card] [Design & Theme Customization](/features/design) > > Configure themes visually from the dashboard with pre-built themes, typography, colors, and live preview. ### Theme Configuration Options | Property | Description | | - | - | | `light` | Color configuration for light mode | | `dark` | Color configuration for dark mode | | `font_primary_url` | URL for the primary font | | `font_secondary_url` | URL for the secondary font | | `font_size` | Font size: `xs`, `sm`, `md`, `lg`, `xl`, `2xl` | | `font_weight` | Font weight: `normal`, `medium`, `bold`, `extraBold` | | `radius` | Border radius for UI elements (e.g., `4px`, `0.5rem`, `8px`) | | `pay_button_text` | Custom text for the pay button (e.g., "Complete Purchase", "Subscribe Now") | ### Color Configuration (Light/Dark Mode) Each mode supports these color properties: | Property | Description | | - | - | | `bg_primary` | Background primary color | | `bg_secondary` | Background secondary color | | `text_primary` | Text primary color | | `text_secondary` | Text secondary color | | `text_placeholder` | Text placeholder color | | `text_error` | Text error color | | `text_success` | Text success color | | `border_primary` | Border primary color | | `border_secondary` | Border secondary color | | `button_primary` | Primary button background color | | `button_primary_hover` | Primary button hover color | | `button_secondary` | Secondary button background color | | `button_secondary_hover` | Secondary button hover color | | `button_text_primary` | Primary button text color | | `button_text_secondary` | Secondary button text color | | `input_focus_border` | Input focus border color | > [!NOTE] > > All color fields accept standard CSS color formats: > > * Hex: `#fff`, `#ffffff`, `#ffffffff` > * RGB/RGBA: `rgb(255, 255, 255)`, `rgba(255, 255, 255, 0.5)` > * HSL/HSLA: `hsl(120, 100%, 50%)`, `hsla(120, 100%, 50%, 0.5)` > * Named colors: `red`, `blue`, `transparent` ### Example ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_abc', quantity: 1 } ], customization: { theme_config: { font_primary_url: 'https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap', font_size: 'md', font_weight: 'medium', radius: '8px', pay_button_text: 'Complete Purchase', light: { bg_primary: '#ffffff', bg_secondary: '#f5f5f5', text_primary: '#1a1a1a', text_secondary: '#666666', button_primary: '#0066ff', button_primary_hover: '#0052cc', button_text_primary: '#ffffff', border_primary: '#e0e0e0' }, dark: { bg_primary: '#1a1a1a', bg_secondary: '#2d2d2d', text_primary: '#ffffff', text_secondary: '#a0a0a0', button_primary: '#3385ff', button_primary_hover: '#4d99ff', button_text_primary: '#ffffff', border_primary: '#404040' } } }, return_url: 'https://yoursite.com/return' }); ``` > [!TIP] > > You don't need to specify all color properties. Unspecified properties use the default theme values. # Communication Preferences Source: https://docs.dodopayments.com/features/communication-preferences Choose which payment, payout, refund, subscription, and dispute notifications your team receives by email, in-app, and push, and which emails your customers get. ![Communication Preferences Overview](https://mintcdn.com/dodopayments/YvuokxDCslyAwOyr/images/communication-preferences/overview.png?fit=max\&auto=format\&n=YvuokxDCslyAwOyr\&q=85\&s=f600972c9d588b5427d250073bf15aac) > [!NOTE] > > Communication Preferences controls how and when you're notified about events in your Dodo Payments account. You configure notifications for yourself, add team email recipients with their own preferences, and choose between the email, in-app, and push channels. The same page controls which transactional emails your customers receive. ## Accessing Communication Preferences To configure your communication preferences: 1. Go to **Settings** in your Dodo Payments dashboard. 2. Click the **Communication** tab. 3. Use the tabs to switch between notification channels: **Email**, **In-App**, and **Push Notifications**. ## Notification Channels Dodo Payments supports three notification channels, each suited to a different use case. You configure each channel independently. ![Notification Channel Selector](https://mintcdn.com/dodopayments/YvuokxDCslyAwOyr/images/communication-preferences/channel-selector.png?fit=max\&auto=format\&n=YvuokxDCslyAwOyr\&q=85\&s=6f9a73554acdb24dc238af64a7c79b39) The channels compare as follows: | Channel | Description | Best For | | - | - | - | | **Email** | Receive detailed notifications by email at one or more addresses | Record-keeping and team distribution | | **In-App** | See notifications in the dashboard notification center | Quick updates while you work in the dashboard | | **Push Notifications** | Get mobile alerts on your registered devices | Time-sensitive alerts when you're away from your desktop | A business can have up to 10 notification channels in total across email, in-app, and push. ### Email Notifications Email is the most flexible channel. You can add several recipient addresses, and each recipient has its own notification preferences. Use this to route specific notifications to different team members. For example, your finance team receives payout notifications and your support team receives dispute notifications. ![Email Notifications Configuration](https://mintcdn.com/dodopayments/YvuokxDCslyAwOyr/images/communication-preferences/email-notifications.png?fit=max\&auto=format\&n=YvuokxDCslyAwOyr\&q=85\&s=a5e71de2b2413f9ee86e28cf3ea59e04) With email notifications, you can: * Add email recipients, up to the 10-channel limit * Configure notification preferences per recipient * Turn every notification on or off at once with **Enable All** or **Disable All** * Remove email addresses when team members change ### In-App Notifications In-app notifications appear in the notification center of your Dodo Payments dashboard. Use them to stay informed while you work in the dashboard without adding to your email inbox. ![In-App Notifications](https://mintcdn.com/dodopayments/YvuokxDCslyAwOyr/images/communication-preferences/in-app-notifications.png?fit=max\&auto=format\&n=YvuokxDCslyAwOyr\&q=85\&s=e931cfc703aefc9b2b029bf75fa71795) To open in-app notifications, click the bell icon in the dashboard header. Each notification gives a short summary of a recent event. Click a notification to mark it as read. ### Push Notifications Push notifications send mobile alerts to your registered devices. Use this channel for events that need immediate attention, such as payment failures or new disputes. ![Push Notifications](https://mintcdn.com/dodopayments/YvuokxDCslyAwOyr/images/communication-preferences/push-notifications.png?fit=max\&auto=format\&n=YvuokxDCslyAwOyr\&q=85\&s=301ab7cbd6d497020fb07ba3969537f7) Push notifications are organized by device, so you can: * Enable or disable notifications for a specific device * Choose which events trigger push notifications on each device * Manage several devices, for example a phone and a tablet > [!TIP] > > Download the [Dodo Payments mobile or desktop app](/features/mobile-app) to receive push notifications on your iOS, Android, macOS, Windows, or Linux device. ## Managing Email Recipients The email channel accepts several recipient addresses, so you can keep your whole team informed about the events that concern them. ### Adding a New Email Recipient 1. In the **Your Emails** section, click **Add Email**. 2. Enter the address in the **Email Address** field of the dialog that opens. 3. Click **Add Email** to confirm. ![Add Email Address Modal](https://mintcdn.com/dodopayments/YvuokxDCslyAwOyr/images/communication-preferences/add-email-modal.png?fit=max\&auto=format\&n=YvuokxDCslyAwOyr\&q=85\&s=66d959b35cab3eb632f605f9e334a255) After you add an address, you can configure which notifications it receives. ### Configuring Email Preferences 1. Click an email address to expand its notification options. 2. Use the toggle next to each event to turn its notification on or off. Dodo Payments saves each change as you make it. For bulk changes, use the quick actions: * **Enable All**: Turns on every notification for this email address. * **Disable All**: Turns off every notification for this email address. ### Removing an Email Recipient To remove an email address, expand the email entry and click **Remove email**. Notifications to that address stop immediately. ## Your Notification Events These notifications keep you and your team informed about events that affect your business. You configure each event separately for each notification channel. ### Payments Payment notifications cover the payment activity for your products. | Event | Description | | - | - | | **Payment Failed** | Notifies when a payment attempt fails, for example because of insufficient funds or a card decline. Helps you spot customers who need help completing a purchase. | | **Payment Received** | Notifies when a payment is processed successfully, which confirms that a customer completed a purchase. | ### Payouts Payout notifications track the movement of funds from your Dodo Payments account to your bank account. ![Payout and Refund Notifications](https://mintcdn.com/dodopayments/YvuokxDCslyAwOyr/images/communication-preferences/payout-refund-notifications.png?fit=max\&auto=format\&n=YvuokxDCslyAwOyr\&q=85\&s=85cd598cba55a25b4a8e6042b03cb5ba) | Event | Description | | - | - | | **Payout Failed** | Notifies when a payout attempt fails. This can point to a problem with your bank account details that needs attention. | | **Payout In Progress** | Notifies when a payout is being processed and the funds are on their way to your bank account. | | **Payout Initiated** | Notifies when a payout to your bank account is initiated. This is the start of the payout process. | | **Payout On Hold** | Notifies if a payout is paused or under review. You may need to provide additional information or documents. | | **Payout Processed** | Notifies when a payout completes successfully and the funds are sent to your bank account. | When a bank holiday moves your next payout date, every team member with in-app notifications also receives a **Payout date moved** notice that names the old and new dates. See [When Your Payout Date Moves](/features/payouts/payout-structure#when-your-payout-date-moves). ### Refunds Refund notifications cover refund activity across your transactions. | Event | Description | | - | - | | **Refund Completed** | Notifies when a refund is processed and the funds have been returned to the customer. | | **Refund Failed** | Notifies when a refund fails. You may need to act to resolve it. | ### Subscriptions Subscription notifications track the subscription lifecycle. The **Default** column shows whether each notification is on before you change it. | Event | Default | Description | | - | - | - | | **Subscription Started** | Enabled | Notifies when a new subscription is created and activated, which confirms a new recurring customer. | | **Subscription Paused** | Disabled | Notifies when a subscription is paused, whether you paused it or the customer did from the Customer Portal (when self-service pause is enabled). Billing stops and access is revoked until the subscription resumes. See [Pausing and Resuming Subscriptions](/features/subscription#pausing-and-resuming-subscriptions). | | **Subscription Resumed** | Disabled | Notifies when a paused subscription is resumed. Billing restarts and access is restored. | All other team notifications on this page are enabled by default. ### Disputes Disputes need a prompt response to protect your business, and these notifications tell you about each change in a dispute. ![Dispute Notifications](https://mintcdn.com/dodopayments/Qlp03Zh608GExznM/images/communication-preferences/subscriptions-disputes.png?fit=max\&auto=format\&n=Qlp03Zh608GExznM\&q=85\&s=b2b66662280ff34f8392bfbfe5097c52) | Event | Description | | - | - | | **Dispute Created** | Notifies when a customer opens a dispute (chargeback) against a payment. Respond before the deadline. | | **Dispute Challenged** | Notifies when a dispute you responded to is challenged or escalated. The dispute is still in progress. | | **Dispute Won** | Notifies when a dispute is resolved in your favor. You keep the funds. | | **Dispute Lost** | Notifies when a dispute is resolved in the customer's favor. The disputed amount is deducted from your account. | > [!WARNING] > > Disputes have strict response deadlines. Keep dispute notifications enabled so you can respond in time. ## Customer Emails Besides notifications for your team, you choose which transactional emails Dodo Payments sends to your customers automatically. Dodo Payments sends these emails on your behalf to keep customers informed about their purchases. ![Customer Emails list, including the Subscription On Hold, No Payment Method email toggle](https://mintcdn.com/dodopayments/qD0RSXoLZULfSVwD/images/communication-preferences/subscription-on-hold-customer-email.png?fit=max\&auto=format\&n=qD0RSXoLZULfSVwD\&q=85\&s=4248876478e9101ac50f9bc1c685cd1b) The customer emails and their defaults are: | Email | Default | Description | | - | - | - | | **Payment Succeeded** | Enabled | Sends customers a confirmation email when their payment is processed successfully, with receipt details, order information, and a **Download invoice** button. | | **Subscription Plan Changed** | Enabled | Sends customers an email when their subscription plan changes through an upgrade, downgrade, or other modification, with the new plan details and pricing. | | **License Key Created** | Enabled | Sends customers an email when a license key is generated for their purchase, with the license key and activation instructions. | | **Refund Successful** | Enabled | Tells customers that their refund was processed and the funds are on their way back to them. | | **Subscription Trial Ending** | Enabled | Reminds customers that their free trial is ending, about 2 days before the trial expires and the first charge occurs. The email shows the amount of the first charge, including tax. It is not sent when the subscription is set to cancel at the end of the trial. | | **Subscription Paused** | Enabled | Tells customers that their subscription is paused, whether they paused it from the Customer Portal (when self-service pause is enabled) or you paused it for them. | | **Subscription Resumed** | Enabled | Tells customers that their paused subscription has resumed and billing restarts. | | **Subscription Cancelled** | Enabled | Tells customers that their subscription was cancelled with immediate effect. | | **Subscription Set to Cancel** | Enabled | Tells customers that their subscription is scheduled to cancel at the end of the current billing period instead of immediately. | | **Payment Failed** | Disabled | Tells customers that a payment attempt on their account failed. Enable it to have Dodo Payments send these emails instead of handling them yourself. | | **Subscription Renewal Failed** | Disabled | Tells customers that a subscription renewal payment failed. It is sent only for failed renewal payments and complements the general **Payment Failed** email. | | **Upcoming Renewal Reminder** | Disabled | Reminds customers about 2 days before their subscription renews, with the renewal amount including tax. Enable it to give customers advance notice of each renewal. A subscription in a trial that requires a payment method gets the **Subscription Trial Ending** email instead, not this reminder. | | **Add Payment Method Reminder** | Enabled | Sent to the customer of a [Card-Optional at Zero Price](/features/subscription#card-optional-at-zero-price) subscription before real billing starts, asking them to add a card. It has no toggle in the Customer Emails list. **Payment Method Reminder** in **Settings → Subscriptions** sets the timing. | | **Subscription On Hold, No Payment Method** | Enabled | Sent when a [Card-Optional at Zero Price](/features/subscription#card-optional-at-zero-price) subscription is put on hold because no payment method was added before real billing was due. | > [!TIP] > > Customer emails that are **enabled by default** are sent unless you turn them off. Emails that are **disabled by default** are sent only if you enable them. These are usually events where you may prefer to contact customers through your own systems. > [!NOTE] > > Customer emails are separate from the notification emails sent to your team. Turning off a customer email doesn't affect your team's notifications about the same event. ### Test Mode Emails The **Test Mode Emails** switch, below the **Customer Emails** list on the **Email** tab, controls whether customer emails are sent in test mode. It is on by default. * **On**: Customer emails are sent in test mode to the real recipient, with `[TEST MODE]` at the start of each subject. A business can send up to 100 test mode emails per week. * **Off**: No customer emails are sent in test mode. Emails that are not sent don't count toward the weekly allowance, and the dashboard refuses a resend from a customer's [Sent Emails](/features/email-logs) tab. The switch has no effect on live mode emails. ## Best Practices These recommendations help you configure communication preferences effectively: 1. **Route notifications by role**: Add team addresses for different notification types. For example: * `finance@yourcompany.com` for payout notifications * `support@yourcompany.com` for dispute notifications * `sales@yourcompany.com` for payment notifications 2. **Enable critical notifications on several channels**: For time-sensitive events such as disputes, turn on both email and push notifications so you don't miss them. 3. **Review preferences regularly**: When your team grows or changes, check that the right people receive the right notifications. 4. **Keep customer emails enabled**: Unless you have a specific reason to turn them off, customer emails give customers a better experience and reduce support requests. # Connected Apps Source: https://docs.dodopayments.com/features/connected-apps See and revoke the AI assistants, MCP clients, and Dodo CLI sessions connected to your business with OAuth, and control MCP and CLI access per mode. When you sign in to the [Dodo Payments MCP Server](/developer-resources/mcp-server) or the [Dodo CLI](/developer-resources/sdks/cli) with your account, the sign-in creates a connection. Go to **Settings → Connected Apps** in the dashboard to see and manage these connections. ## Connections ![Connected Apps page with the MCP and CLI access switch for test mode and one Dodo CLI connection with its device name in the Session column](https://mintcdn.com/dodopayments/qcWXQ3CCdewP7gKI/images/features/connected-apps-session.png?fit=max\&auto=format\&n=qcWXQ3CCdewP7gKI\&q=85\&s=acd1c4f1d8d6a6f05c767a6556652a38) The page lists each connection with these columns: | Column | Description | | - | - | | **App** | The client that signed in, for example Claude, Cursor, or the Dodo CLI. | | **Modes** | The mode of the connection: test mode or live mode. | | **Access** | The permissions approved on the consent page: Read, Write, or custom. | | **Session name** | The name of the session, to tell connections from the same app apart. For the Dodo CLI, the session name is the device name, for example `you@laptop`. You can change it on the last step of the consent page. | | **Connected** | When the connection was approved. | | **Last used** | When the connection last made a request. | Click a connection to open its **Details** sheet. It shows the full permissions for each resource. ## Revoke a Connection Click **Revoke** on a connection, then confirm. Revoke does this: * The refresh token of the connection is revoked, and no new tokens are issued. * An access token already issued stops working within about a minute. The API caches token checks for 60 seconds. * For MCP calls, the next exchange for a 5-minute API token is refused. To use the app again, sign in from the app again. > [!NOTE] > > `dodo logout all` in the CLI also revokes the CLI connections on the server. `dodo logout test` and `dodo logout live` revoke the connection of that mode. ## Admin Controls Admins with **Write** permission on API keys see extra controls: * **MCP and CLI access**: one switch for each mode, test and live. When you turn a switch off, all MCP and CLI connections in that mode are revoked, and no new connection can be approved in that mode. Turn it on again to allow new connections. * **Revoke all**: revokes every connection for the business in that mode. ![Revoke all connections confirmation dialog for test mode](https://mintcdn.com/dodopayments/zrp7H1V8foAnJyAy/images/features/connected-apps-revoke-all.png?fit=max\&auto=format\&n=zrp7H1V8foAnJyAy\&q=85\&s=6b5fe91cac6e2e58ab72cd4662cb31ed) When MCP and CLI access is off, the list is empty and the page shows that MCP clients and the Dodo CLI cannot connect in that mode. ![Connected Apps page with MCP and CLI access turned off for test mode and no connected apps](https://mintcdn.com/dodopayments/zrp7H1V8foAnJyAy/images/features/connected-apps-access-off.png?fit=max\&auto=format\&n=zrp7H1V8foAnJyAy\&q=85\&s=d59db2fdc8d83ca084a162a8702df7ae) > [!WARNING] > > Turning off MCP and CLI access for live mode stops every AI assistant and CLI session that uses live mode. API keys are not affected. ## Related > [card] [MCP Server](/developer-resources/mcp-server) > > Connect AI assistants with OAuth. > [card] [Dodo CLI](/developer-resources/sdks/cli) > > Sign in from your terminal. # Credit-Based Billing Source: https://docs.dodopayments.com/features/credit-based-billing Issue, manage, and track credit entitlements across subscriptions, one-time products, and usage-based billing with rollover, overage, and expiration controls. [Credit-Based Billing Tutorial](https://www.youtube.com/embed/4RR3Yj3Qeuw) > [!NOTE] > > Credit-Based Billing lets you grant customers a balance of credits—API calls, tokens, compute units, or any custom metric—and deduct from that balance as they consume your service. Credits work across all product types: subscriptions, one-time purchases, and usage-based billing. ## What Is Credit-Based Billing? Credit-Based Billing gives you a flexible system to issue credit entitlements to customers as part of your products. Instead of charging per-use or limiting access through feature flags, you allocate a pool of credits that customers draw from as they use your service. Credits work well for: * **AI and LLM platforms**: Grant tokens or generation credits per plan tier * **API services**: Allocate API call credits with overage pricing * **Infrastructure platforms**: Issue compute hours or storage credits * **Communication services**: Provide message or minute credits per subscription * **SaaS with consumption tiers**: Bundle included usage into credit pools ![Checkout showing included credits with the product purchase](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Checkout.png?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=21880df0e4b0b1a3cb8593dbeb8ae343) Credits appear as entitlements on your products and show in checkout, customer portal, and subscription details. ## Core Concepts ### Credit Types When creating a credit, you choose between two types: > [tab] Custom Unit > > Define credits in your own unit—tokens, API calls, compute hours, or any metric meaningful to your product. Custom units use the precision you set (0 to 10 decimal places). > > **Best for**: API calls, AI tokens, compute hours, storage units, messages > [tab] Fiat Credits > > Credits represent actual currency value (for example, USD or EUR). Customers receive a monetary credit balance that depletes as they use your service at your defined pricing. > > **Best for**: Prepaid balances, promotional credits, service compensation ### Credit Lifecycle Credits follow a clear lifecycle from issuance through consumption: **1. Credits Issued** Credits are granted when a customer purchases a product (subscription or one-time) with attached credit entitlements. For subscriptions, credits are reissued each billing cycle. **2. Credits Consumed** As customers use your service, credits are deducted. For usage-based products, meters automatically deduct credits based on real-time events. You can also deduct credits manually via the dashboard or API. **3. Credits Expire or Roll Over** At the end of the billing cycle (or after the configured expiry period), unused credits either expire or roll over to the next period based on your settings. **4. Overage Handling** If credits run out mid-cycle, you can allow overage (continued usage beyond the balance) and choose how overage is handled: forgive it, bill it, or carry the deficit forward. ### Grant Sources Credits can be granted from multiple sources: | Source | Description | | - | - | | **Subscription** | Credits issued with subscription purchase, re-issued each billing cycle | | **One-Time** | Credits issued with a one-time payment product | | **Add-on** | Credits issued with an add-on attached to a subscription | | **API** | Credits granted manually via API or dashboard | | **Rollover** | Credits carried over from a previous billing cycle | *** ## Creating Credits Create credit entitlements in the **Products → Credits** section of your dashboard. Each credit defines the unit, precision, expiry rules, and lifecycle behavior. ![Credits listing page showing created credit entitlements](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Entitlements%20%20-%20Credits.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=f9f30f473d342657d3f0f857e53b2e85) The Credits tab under Products shows all your credit entitlements. **1. Navigate to Credits** Go to **Products** in your dashboard and select the **Credits** tab. Click **Create Credit** to start. **2. Configure Basic Information** Enter a **Credit Name**—this is your internal identifier for the credit. ![Credit creation form showing basic info, general settings, and subscription settings](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Create%20Credit.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=0c59e6b6eb4cfd76a545b39fb1f5c19e) The credit creation form with all configuration sections. **3. Set General Settings** Configure the credit type and display properties: **Credit Type** `string` *required* Choose **Custom Unit** or **Fiat Credits**. * **Custom Unit**: Define your own metric (tokens, API calls, compute hours). Requires a **Unit Name** (for example, "Platform tokens") and a **Precision** setting. * **Fiat Credits**: Credits represent real currency value. Requires a **Unit Currency** selection (USD, EUR, GBP, INR, etc.). **Unit Name** `string` Only for Custom Unit credits. The label customers see for this credit (for example, "AI Tokens" or "API Calls"). Shown in checkout and the customer portal. **Precision** `number` Only for Custom Unit credits. Number of decimal places allowed, from `0` to `10`: * `0`: Whole numbers (best for countable items like API calls) * `1`: One decimal (0.0) * `2`: Two decimals (0.00)—default * `3`: Three decimals (0.000) * Up to `10`: For high-precision units (for example, fractional tokens or micro-usage) > [!WARNING] > > Precision cannot be changed after the credit is created. **Credit Expiry** `string` How long credits remain valid after issuance: * **7 days**, **30 days** (default), **60 days**, **90 days**, **Custom**, or **Never** Select **Custom** to specify a custom number of days (minimum 1). **4. Configure Subscription Settings (Optional)** These settings control credit behavior within recurring subscriptions: **Rollover** `boolean` Allow unused credits to carry forward to the next billing cycle. When enabled, configure: * **Max Rollover Percentage** (0–100%): Limit how much carries over * **Rollover Timeframe**: How long rolled-over credits remain valid (for example, 1 Month) * **Max Rollover Count**: Maximum consecutive rollovers before credits are forfeited **When Credits Run Out or Subscription Expires:** **Allow Overage** `boolean` Let customers continue using your service after their credit balance reaches zero. When enabled, configure: * **Overage Limit**: Maximum credits customers can consume beyond their balance * **Price Per Unit**: Cost per additional credit when overage is enabled (with currency selector) **Overage Behavior** `string` *required* Controls how overage is handled at the end of the billing cycle: * **Forgive overage at reset** (default): Usage beyond the credit limit is tracked but not billed. Balance resets each cycle. * **Bill overage at billing**: Usage beyond the credit limit is charged on the next invoice, then the balance resets. * **Carry over deficit**: Usage beyond the credit limit carries forward as a negative balance into the next cycle. * **Carry over deficit (auto-repay)**: Deficit carries forward and is automatically repaid from new credits in the next cycle. **5. Create Credit** Click **Create Credit** to save. The credit is now available to attach to any product. > [!TIP] > > Your credit entitlement is ready. Attach it to products to start issuing credits to customers. > [!TIP] > > Start with simple settings - no rollover, no overage - and add complexity as you learn how customers use credits. Most settings can be updated at any time without affecting existing grants. Note that **precision cannot be changed** after a credit is created. *** ## Attaching Credits to Products Credits are attached to products as **entitlements** in the product creation or editing flow. You can attach up to **5 credits per product**. Credits work with all three pricing types. ### Subscription Products For subscriptions, credits are issued **per billing cycle** and can be configured with proration, trial credits, and cycle-specific settings. **1. Create or Edit a Subscription Product** Go to **Products → Create Product** or edit an existing product. Select **Subscription** as the pricing type and configure your recurring price. **2. Open Entitlements Section** Expand the **Entitlements** section and click the **Attach** button next to **Credits**. ![Product entitlements section showing Credits attach button](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20Subscription.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=fb404b5c706ae200079742965a176605) The Entitlements section in the product form with Credits, License Key, and Digital Product Delivery options. **3. Select Credits to Attach** An **Add Credits** panel opens. You can select an existing credit from the dropdown or click **Create new credit** to define one on the spot. ![Add Credits panel with credit selection dropdown](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20Subscription-2.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=d67a2a18c7a550c8cf1e8378bd5514dc) The Add Credits panel lets you select existing credits or create new ones. > [!NOTE] > > You can attach up to 5 credits per product. Each credit can have its own configuration. **4. Configure Credit Settings** For each attached credit, configure: **Credits issued per billing cycle** `number` *required* The number of credits granted to the customer each billing period. **Low Balance Threshold** `number` Notify when the balance falls below this percentage (0–100). Useful for alerting customers before they run out. **Credits During Free Trial** `number` Set a different credit amount for trial periods. Enable **Expire trial credits after trial ends** to revoke unused trial credits when the trial converts to a paid subscription. **Allow Proration** `boolean` Prorate remaining credits when a customer upgrades or downgrades their subscription plan. **Import Default Credit Settings** `boolean` Use the default rollover, overage, and expiry settings from the credit entitlement. Turn this off to customize settings specifically for this product. ![Credit configuration form with billing cycle, trial, and proration settings](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20Subscription-4.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=68e212dddbec73131cf9f75bf5b55408) Credit configuration showing per-cycle amount, trial credits, proration, and custom settings. **5. Review and Add** Review the attached credit showing name, amount, and expiration. Click **Add to Subscription** to confirm. ![Add Credits panel showing selected credit with details](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20Subscription-5.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=7d8a21560061c15cc8544831a59793e2) Review attached credits before adding them to the subscription. ### One-Time Payment Products For one-time payments, credits are issued **once** at the time of purchase. **1. Create a One-Time Product** Create a product with **Single Payment** pricing type. ![Product pricing section with Single Payment selected](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20OTP.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=1743cb3e515952f9d4b1b2782cebac8b) Single Payment pricing selected for a one-time credit product. **2. Attach Credits** Open the **Entitlements** section and attach credits. Configure the **number of credits issued** (total one-time grant) on purchase. > [!TIP] > > One-time credit products are ideal for credit top-up packs, promotional bundles, or prepaid credit purchases. ### Usage-Based Billing Products For usage-based products, credits are **linked to meters** and automatically deducted based on real-time consumption events. **1. Create a Usage-Based Product** Select **Usage Based Billing** as the pricing type. Configure the base price and billing frequency. ![Usage Based Billing pricing configuration](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20UBB.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=41b2862c12d126e7843098307e27e137) Usage Based Billing pricing type with meter configuration. **2. Add a Meter** Click the **+** button in the **Select meter** section to add a meter. A subscription can have up to **50 meters**. ![Select Meter panel showing free threshold and credit toggle](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20UBB-3.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=3f677352783684107eaa7e568d9352e2) The Select Meter panel with meter configuration and credit toggle. **3. Enable Credit Billing on the Meter** Toggle **Bill usage in Credits** to attach a credit to the meter. Select the credit entitlement from the dropdown. **Free Threshold** `number` Applies only when the meter bills in money. When the meter bills in credits, every unit is deducted from the credit balance. **Bill usage in Credits** `boolean` When enabled, meter usage deducts from the customer's credit balance instead of charging per-unit. **Meter units per credit** `number` *required* The number of usage units required to deduct 1 credit. For example, if set to `1000`, then 1,000 API calls consume 1 credit. ![Meter configuration with credit selection and meter units per credit](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20UBB-5.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=b4ef2fe5079cbf3bb39eb3814f101cbd) Credit attached to a meter with per-unit conversion rate. **4. Configure Credit Issuance** Set the number of credits issued and optionally customize the credit settings for this product. ![Credit configuration for UBB product](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20UBB-6.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=22e99c54f11305a24d63c77e09a4650c) Configure how many credits to issue and whether to use default settings. **5. Verify Attachment** Once configured, the meter shows the attached credit name, unit price, and free threshold. ![Configured meter showing credit attachment details](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20UBB-1.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=d1a68ef9f07872b1dc9d2b2a655df0a4) Meter with credit attached showing price, threshold, and credit name. > [!NOTE] > > When credits are linked to meters, the system automatically deducts credits based on ingested usage events. A background worker processes events every minute, aggregates them according to the meter's configuration, and applies FIFO (first-in, first-out) deduction from the customer's non-expired grants, starting with the grant that expires first. *** ## Credit Settings ### Rollover Rollover lets unused credits carry forward to the next billing cycle instead of expiring. | Setting | Description | | - | - | | **Rollover Enabled** | Toggle to allow unused credits to carry forward | | **Max Rollover Percentage** | Limit how much carries over (0–100%). At 50%, only half of unused credits roll over | | **Rollover Timeframe** | How long rolled-over credits remain valid (day, week, month, year) | | **Max Rollover Count** | Maximum number of times credits can be consecutively rolled over. After this limit, remaining credits are forfeited | **Example**: A customer has 200 unused credits at cycle end. With 75% rollover, 150 credits carry forward and 50 are forfeited. ### Overage Overage controls what happens when a customer's credit balance reaches zero mid-cycle. | Setting | Description | | - | - | | **Allow Overage** | Toggle to let customers continue using the service beyond their credit balance | | **Overage Limit** | Maximum credits customers can consume beyond their balance | | **Price Per Unit** | Cost per additional credit consumed as overage (with currency) | | **Overage Behavior** | Controls what happens to overage at the end of the billing cycle (see below) | **Overage Behavior options:** | Behavior | Description | | - | - | | **Forgive overage at reset** | Usage beyond the credit limit is tracked but not billed. Balance resets each cycle | | **Bill overage at billing** | Usage beyond the credit limit is charged on the next invoice, then the balance resets | | **Carry over deficit** | Overage carries forward as a negative balance into the next cycle | | **Carry over deficit (auto-repay)** | Deficit carries forward and is automatically repaid from new credits in the next cycle | > [!NOTE] > > Dodo Payments doesn't block usage when a balance reaches zero. If you don't want customers to keep using the service without credits, check the balance in your application before serving the request. Choose an overage behavior that matches your billing model. **Forgive at reset** is the default and simplest option. ### Expiration | Setting | Description | | - | - | | **Credit Expiry** | Duration after issuance before credits expire (7, 30, 60, 90, custom days, or never) | | **Trial Credits Expire After Trial** | Whether trial-specific credits expire when the trial period ends | > [!NOTE] > > Expired credits create a `credit_expired` ledger entry. If rollover is enabled, the rollover percentage is applied before expiration, and only the remainder expires. *** ## Usage Billing with Credits When credits are linked to usage meters, the system creates a powerful consumption-based billing model. Customers receive a credit allocation, and usage events automatically deduct from their balance. ![Usage Billing dashboard showing events table with credits consumed](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Usage%20Billing.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=de8c5992d0ae59e74bbb8a840e07454f) The Usage Billing dashboard shows meter events with units consumed, credits consumed, and customer details. ### How Meter-Based Credit Deduction Works 1. **Your application sends usage events**: Each event includes a customer ID, event name, and metadata 2. **Meters aggregate events**: Using Count, Sum, Max, or Last aggregation 3. **Credits are deducted automatically**: A background worker processes events every minute, converts meter units to credits using your configured rate, and deducts from the customer's balance using FIFO ordering (earliest-expiring grants first) 4. **Overage is tracked**: If the credit balance reaches zero and overage is enabled, the system tracks overage usage for end-of-cycle billing ### Meters Panel The Usage Billing dashboard includes a **Meters** panel listing all defined meters with their aggregation type: | Aggregation | Description | Example | | - | - | - | | **Count** | Total number of events | API calls | | **Sum** | Sum of a value field | Total bytes transferred | | **Max** | Highest value recorded | Peak concurrent users | | **Last** | Most recent value | Current storage used | *** ## Customer Experience ### Checkout When a customer purchases a product with attached credits, the checkout page displays the included credits as part of the product offering. ![Checkout page showing product with included API call credits](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Checkout.png?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=21880df0e4b0b1a3cb8593dbeb8ae343) Checkout shows included credits with the product, making the value proposition clear. Credits appear in an **Includes** section below the product description, showing the credit amount and type (for example, "\$1000 API calls"). ### Customer Portal Customers can view and manage their credit balances in the Customer Portal under the **Credits** section. ![Customer Portal credits view with balance and transaction history](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Customer%20Portal.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=b8afe1f89242f9e347b26b990dd00fe8) The Customer Portal shows available balance and full transaction history. The portal displays: * **Available Balance**: Current credit balance displayed prominently * **Credit Tabs**: Switch between different credit types (for example, "OpenAI Credits" or "Usage Tokens") * **Recent Transactions**: Full history with date, transaction ID, type, amount, and running balance Transaction types shown to customers include: | Type | Description | Amount | | - | - | - | | **Credits with Subscription** | Credits issued with subscription purchase or renewal | Green (+) | | **One-Time Credits** | Credits from one-time purchases or manual grants | Green (+) | | **Usage Deduction** | Credits consumed through service usage | Red (−) | | **Overage** | Usage beyond credit balance | Red (−) | ### Subscription Details The subscription detail page shows credit entitlements alongside other plan information. ![Subscription details page showing entitlements and usage history](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Subscription%20Details.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=059f57f8996c1f514b9d7eba1ef6e33a) Subscription details show credit allocation, remaining balance, and renewal date. Key information displayed: * **Credit allocation** per billing cycle (for example, "1000 credits each cycle") * **Remaining balance** (for example, "7500 credits remaining") * **Renewal date** for next credit issuance * **Usage History** tab with meter-level breakdown showing units consumed, thresholds, unit prices, and total costs ### Transaction Details Payment transaction pages include an **Entitlements** section showing all entitlements delivered with the payment, including credits. ![Transaction details page showing credit entitlements](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Transactions%20-%20Payment%20Summary.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=dccb0ada7682ead4493baf71199a86fb) Transaction details show credits alongside other entitlements like license keys and digital downloads. *** ## Managing Credits ### Dashboard Views #### Credit Entitlements List View all your credit entitlements in **Products → Credits**. The table shows credit name, expiry settings, and provides quick actions for editing or archiving. ![Credits listing page in the Products section](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Entitlements%20%20-%20Credits.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=f9f30f473d342657d3f0f857e53b2e85) Credits listing with total count, creation button, and management actions. #### Customer Credit Details View a specific customer's credit balances and transaction history from **Customers → \[Customer Name] → Credits**. ![Customer details page with Credits tab showing balance and transactions](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Customer%20Details.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=a52e7e914338d698bf72498821f6a8b6) Customer detail page showing credit balance and full transaction ledger. The customer credit view includes: * **Credit Selector** - Switch between different credit entitlements * **Available Balance** - Current balance in large, prominent display * **Apply Credit/Debit** - Button to manually adjust the customer's balance * **Recent Transactions** - Full ledger with date, transaction ID, type, amount, and running balance ### Manual Adjustments You can manually credit or debit a customer's balance directly from the dashboard: **1. Navigate to Customer** Go to **Customers** and select the customer. **2. Open Credits Tab** Click the **Credits** tab and select the appropriate credit entitlement from the wallet selector. **3. Apply Credit or Debit** Click **Apply Credit/Debit** to open the adjustment interface. **Transaction Type** `string` *required* Select **Credit** to add credits or **Debit** to remove credits from the customer's balance. **Amount** `number` *required* The number of credits to add or remove. **Reason** `string` Optional explanation for the adjustment (for example, "Service compensation" or "Promotional bonus"). **4. Confirm** Review and apply the adjustment. The change is reflected immediately in the customer's balance and recorded in the credit ledger. > [!TIP] > > Manual adjustments create a `manual_adjustment` ledger entry with full audit trail. ### Credit Ledger Every credit operation is recorded in the credit ledger, providing a complete audit trail: | Transaction Type | Description | | - | - | | **Credit Added** | Credits granted (subscription, one-time, or API) | | **Credit Deducted** | Credits consumed through usage or manual debit | | **Credit Expired** | Credits expired without rollover | | **Credit Rolled Over** | Credits carried forward to the next period | | **Rollover Forfeited** | Rolled credits forfeited after max rollover count reached | | **Overage Charged** | Usage beyond credit balance with overage enabled | | **Overage Reset** | Tracked overage cleared at the billing-cycle reset | | **Auto Top-Up** | Automatic credit replenishment at low balance | | **Manual Adjustment** | Credit or debit applied manually by merchant | | **Refund** | Credits refunded | Each ledger entry records the balance before and after the transaction, overage before and after, a description, and reference to the source (payment, subscription, etc.). *** ## Webhooks Credit-Based Billing fires webhook events for every credit lifecycle change. Use these to keep your application in sync with credit balances, trigger notifications, or build custom billing workflows. | Event | Description | | - | - | | `credit.added` | Credits are granted to a customer (via subscription, one-time purchase, add-on, or API) | | `credit.deducted` | Credits are consumed through usage or manual debit | | `credit.expired` | Unused credits expired after the configured expiry period | | `credit.rolled_over` | Unused credits are carried forward to a new grant at cycle end | | `credit.rollover_forfeited` | Credits forfeited because the max rollover count was reached | | `credit.overage_charged` | Overage charges applied when usage continues beyond zero balance | | `credit.overage_reset` | Accumulated overage charges are reset (for example, at the start of a new billing cycle) | | `credit.manual_adjustment` | Manual credit or debit adjustment made via dashboard or API | | `credit.balance_low` | Credit balance drops below the configured low balance threshold | All ledger events (every `credit.*` event except `credit.balance_low`) include the full `CreditLedgerEntry` payload with balance before/after, overage before/after, source reference, and the `metadata` of the grant's source subscription or payment (empty for grants created directly via the API). The `credit.balance_low` event includes the threshold configuration and current balance. > [card] [Credit Webhook Payloads](/developer-resources/webhooks/intents/credit) > > View full payload schemas, field descriptions, and integration examples for all credit webhook events. *** ## API Management > [accordion] Create Credit Entitlements > > Use the API to create credit entitlements programmatically with full control over rollover, overage, and expiration settings. > > > [card] [Create Credit Entitlement](/api-reference/credit-entitlements/create-credit-entitlement) > > > > Create a new credit entitlement with rollover, overage, and expiry configuration. > > > [card] [List Credit Entitlements](/api-reference/credit-entitlements/list-credit-entitlements) > > > > Retrieve all credit entitlements for your business. > [accordion] Manage Credit Entitlements > > Retrieve, update, or delete credit entitlements. Deleted entitlements can be restored. > > > [card] [Get Credit Entitlement](/api-reference/credit-entitlements/get-credit-entitlement) > > > > Retrieve a specific credit entitlement by ID. > > > [card] [Update Credit Entitlement](/api-reference/credit-entitlements/update-credit-entitlement) > > > > Update rollover, overage, expiry, or other settings. > > > [card] [Delete Credit Entitlement](/api-reference/credit-entitlements/delete-credit-entitlement) > > > > Soft-delete a credit entitlement. > > > [card] [Undelete Credit Entitlement](/api-reference/credit-entitlements/undelete-credit-entitlement) > > > > Restore a previously deleted credit entitlement. > [accordion] Grant and Adjust Credits > > Grant credits directly to a customer's balance without requiring a purchase, or create manual debit entries for billing adjustments. > > > [card] [Create Ledger Entry](/api-reference/credit-entitlements/create-ledger-entry) > > > > Credit or debit a customer's balance with full audit trail and idempotency support. > [accordion] Query Balances and Ledger > > Retrieve a customer's current credit balance, grant history, and full ledger of transactions for any credit entitlement. > > > [card] [List Balances](/api-reference/credit-entitlements/list-balances) > > > > List all customer balances for a credit entitlement. > > > [card] [Get Customer Balance](/api-reference/credit-entitlements/get-customer-balance) > > > > Get a specific customer's balance. > > > [card] [List Customer Grants](/api-reference/credit-entitlements/list-customer-grants) > > > > View all credit grants for a customer. > > > [card] [List Customer Ledger](/api-reference/credit-entitlements/list-customer-ledger) > > > > Full transaction history for a customer. ### Integration Example Initialize the Dodo Payments client: ```typescript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], environment: 'test_mode', // defaults to 'live_mode' }); ``` Attach credits to a subscription product during checkout: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_ai_pro_plan', quantity: 1, } ], customer: { email: 'customer@example.com' }, return_url: 'https://yourapp.com/success' }); ``` Send usage events that deduct credits automatically: ```typescript theme={null} await client.usageEvents.ingest({ events: [{ event_id: `gen_${Date.now()}`, customer_id: 'cus_abc123', event_name: 'ai.generation', timestamp: new Date().toISOString(), metadata: { model: 'gpt-4', tokens: 1500 } }] }); ``` *** ## Real-World Examples > [accordion] AI SaaS Platform > > **Pricing Structure:** > > | Plan | Price | Credits/Month | Overage | > | - | - | - | - | > | Starter | \$29/mo | 10,000 tokens | \$0.003/token | > | Pro | \$99/mo | 100,000 tokens | \$0.002/token | > | Enterprise | \$499/mo | 1,000,000 tokens | \$0.001/token | > > **Configuration:** > > * Credit Type: Custom Unit ("AI Tokens") > * Precision: 0 (whole tokens) > * Rollover: 25% max, 1-month timeframe > * Overage: Enabled, bill overage at billing > * Meter: `ai.generation` with Sum aggregation on `tokens` field > [accordion] API Gateway > > **Pricing Structure:** > > | Plan | Price | Credits/Month | Overage | > | - | - | - | - | > | Free | \$0/mo | 1,000 calls | Blocked | > | Developer | \$19/mo | 50,000 calls | \$0.001/call | > | Business | \$99/mo | 500,000 calls | \$0.0005/call | > > **Configuration:** > > * Credit Type: Custom Unit ("API Calls") > * Precision: 0 (whole calls) > * Rollover: Disabled > * Overage: Developer+ plans allow overage (forgive at reset), Free plan disables overage > * Meter: `api.request` with Count aggregation > [accordion] Cloud Storage Service > > **Pricing Structure:** > > | Plan | Price | Credits/Month | Overage | > | - | - | - | - | > | Personal | \$9/mo | 100 GB-hours | \$0.05/GB-hour | > | Team | \$49/mo | 1,000 GB-hours | \$0.03/GB-hour | > > **Configuration:** > > * Credit Type: Custom Unit ("GB-hours") > * Precision: 2 (two decimal places) > * Rollover: 50% max, carries over once > * Overage: Enabled, with an overage limit set in GB-hours > * Meter: `storage.usage` with Sum aggregation *** ## Best Practices * **Start simple**: Begin with a single credit type and no rollover. Add complexity based on customer feedback and usage patterns. * **Set clear expectations**: Display credit allocations, remaining balances, and overage pricing prominently in your product pages and customer portal. * **Use meaningful units**: Name credits after what they represent (for example, "API Calls" or "AI Tokens") rather than generic terms. This helps customers understand value. * **Configure expiry thoughtfully**: Short expiry windows (7 days) drive urgency but may frustrate customers. Longer windows (30–90 days) are more customer-friendly for most SaaS products. * **Monitor low balances**: Set low balance thresholds to alert customers before they run out, reducing surprise overage charges. * **Test in test mode**: Create credits, attach them to test products, and simulate the full purchase → usage → deduction → expiration cycle before going live. * **Keep the setup in code**: Define credit entitlements, meters, and the products that grant credits with the [Terraform provider](/developer-resources/terraform-provider). Then the same setup builds in test mode and in live mode, and each change gets a review. > [!NOTE] > > Credit-Based Billing works with all other Dodo Payments features: subscriptions with trials, plan changes with proration, and the customer portal. Start with a basic setup and expand as your pricing model evolves. # Customer Blocklist Source: https://docs.dodopayments.com/features/customer-blocklist Block a customer to stop future checkouts, cancel their live subscriptions, and make their Customer Portal read-only. Manage the blocklist from Settings or the API. The Customer Blocklist stops a known bad actor from buying from you again. A blocked customer cannot pay, loses their live subscriptions, and can view their account in the [Customer Portal](/features/customer-portal) but cannot change their subscriptions. Manage the blocklist from **Settings → Blocklist** or through the Blocklist API. ![Blocklist settings page showing the total number of blocked customers, a table of blocked entries with identifier, blocked by, and blocked on columns, and an Add to Blocklist button](https://mintcdn.com/dodopayments/c1t35qHSH45TR4GO/images/blocklist/blocklist-settings.png?fit=max\&auto=format\&n=c1t35qHSH45TR4GO\&q=85\&s=771eb4a5654fbd22e6a5110cfb1a2e9d) The Blocklist tab under Settings ## What Happens When You Block a Customer A block takes effect as soon as you add it, in each of these areas: | Area | Effect | | - | - | | **Checkout** | Every payment attempt from the blocked email is refused: payment links, checkout sessions, and payments or subscriptions created through the API. | | **Live subscriptions** | Subscriptions in `pending`, `active`, `on_hold`, or `paused` status are cancelled with the reason `cancelled_by_merchant`. The usual `subscription.cancelled` webhook fires for each one. | | **Renewals and retries** | Automatic renewals and [payment retries](/features/recovery/payment-retries) skip a blocked customer, so no further charge is made even if a cancellation is still pending. | | **Manual retry** | A [manual retry](/features/recovery/manual-retry) of a blocked customer's payment is refused. | | **Customer Portal** | The customer can still log in and view invoices, subscriptions, and license keys. They cannot cancel, pause, or resume a subscription, change plans, update a payment method, or edit their invoice address. They can still remove a saved payment method. | > [!NOTE] > > Blocking does not refund past payments, and it does not affect open disputes. Issue any refund separately from the [Refunds](/features/transactions/refunds) page. ## How Blocking Matches Customers You can block by **customer ID** or by **email**. Either way, the block is keyed on the customer's email, not on the customer record: * **Every record with that email is covered.** Checkout can create a new customer record for a returning email, so a block on a single customer ID could be bypassed. A block on the email cannot. * **Aliases are covered.** Emails are compared in lowercase with any `+alias` removed, so `buyer+promo@example.com` and `Buyer@example.com` count as the same customer. Dots in the address are kept as they are. * **Scoped to your business.** A block applies to your business only. The same email can still buy from other businesses on Dodo Payments. * **The email must belong to an existing customer.** You cannot block an email that matches none of your customers, and you cannot block a customer record that has no email. ## Blocking a Customer You can block a customer from the Blocklist page or from the customer's own page. > [tab] From Settings > > **1. Open the Blocklist** > > Go to **Settings → Blocklist** in your dashboard. > > **2. Add to Blocklist** > > Click **Add to Blocklist**, then enter the customer's email or customer ID in **Customer ID or email**. The panel shows the matching customer. > > **3. Confirm** > > Click **Add to Blocklist** in the panel. The customer's live subscriptions are cancelled immediately, and the entry appears in the **Blocked entries** table. If some subscriptions are still being cancelled, the dashboard shows a notice. Refresh the page in a moment to check. > [tab] From the customer's page > > **1. Open the Customer** > > Go to **Sales → Customers** and open the customer you want to block. > > **2. Block the Customer** > > Open the menu with the three-dot icon and select **Block this Customer**. > > **3. Confirm** > > Click **Block**. Once the block is in force, the page shows a **Blocked** badge next to the customer's name. The dashboard does not ask for a reason. To record why you blocked the customer, add a note on the customer's page, or send `reason` when you block through the API. ## Managing Blocked Customers The **Blocklist** page lists every active block: * **Total Customers Blocked**: How many customers are currently blocked. * **Blocked entries**: One row per block, with the **Identifier** you entered (email or customer ID), **Blocked By**, and **Blocked On**. **Blocked By** shows the team member who added the block, or **API** for a block added with an API key. * **Search Identifier** and **Filters**: Find an entry by email or customer ID, or filter by **Blocked By** and **Blocked Between**. * **Action**: **See Details** opens the blocked customer's page, and **Unblock** removes the block. Team members without **Write** access to **Customers**, such as the **Viewer** or **Analyst** role, cannot unblock. ### The Blocked Customer's Page ![Customer Information page for a blocked customer showing the Blocked badge, an Unblock Customer button, an Activity Log with a note and the Added to blocklist event, and a Reference IDs panel with the customer ID](https://mintcdn.com/dodopayments/c1t35qHSH45TR4GO/images/blocklist/blocked-customer-details.png?fit=max\&auto=format\&n=c1t35qHSH45TR4GO\&q=85\&s=83e1225a8e71c003d2bf660f0eea9c08) A blocked customer's details page Open a blocked customer from **Sales → Customers** or from the Blocklist page to see: * A **Blocked** badge next to the customer's name, and an **Unblock Customer** button. * **Activity Log**: When the customer was added to the blocklist, the reason, and any notes your team has added since. Click **Add Note** to record new context, such as the outcome of a chargeback. You can edit a note later through the API. * **Reference IDs**: The customer ID linked to this block, ready to copy. ## Unblocking a Customer To unblock a customer, click **Unblock Customer** on the customer's page, or select **Unblock** in the **Action** column of the Blocklist page. Then confirm with **Unblock**. * Checkout and Customer Portal changes are restored immediately. * **Cancelled subscriptions are not reactivated.** The customer has to purchase again. * The entry is kept as an audit record together with its notes, but it no longer appears in the active list. * You can block the same customer again later. That creates a new entry. ## What the Customer Sees A blocked customer is never told that they were blocked. * **At checkout**, the payment fails with a generic decline: "This payment cannot be processed." The API returns HTTP `403` with the error code `PAYMENT_NOT_PERMITTED`, which names no cause. The real reason is written to Dodo Payments' logs only. * **In the Customer Portal**, everything is visible, but every action that changes the account is refused. A refused action returns HTTP `403` with `PORTAL_ACTION_NOT_PERMITTED` and the message "This action is not available." The portal profile carries `read_only: true`, so a custom portal integration can disable its own controls. The portal never exposes the blocklist entry or its notes. > [!WARNING] > > If you render checkout or portal errors in your own product, keep this behavior. Show a generic message for `PAYMENT_NOT_PERMITTED` and `PORTAL_ACTION_NOT_PERMITTED`. Revealing the block tells a bad actor to try a different email. ## Using the API The Blocklist API lets you block from your own tooling, for example when a chargeback arrives. It requires your secret [API key](/api-reference/introduction). The Blocklist API uses the **Customers** permission. A key with **Read** access to Customers can list entries and read notes. A key with **Write** access to Customers can block, unblock, and manage notes. The dashboard applies the same split to [team roles](/features/team): a role with **Read** access to Customers reads the list, and a role with **Write** access makes changes. The Blocklist API has six endpoints: | Method | Endpoint | Purpose | | - | - | - | | `GET` | `/blocklist/customers` | List blocked customers, with filters and a `total` count | | `POST` | `/blocklist/customers` | Block a customer by customer ID or email | | `GET` | `/blocklist/customers/{entry_id}` | Get an entry together with its notes | | `DELETE` | `/blocklist/customers/{entry_id}` | Unblock a customer | | `POST` | `/blocklist/customers/{entry_id}/notes` | Add a note | | `PATCH` | `/blocklist/customers/{entry_id}/notes/{note_id}` | Update a note | The list returns active blocks only. To filter it, pass `identifier` (a partial, case-insensitive match on the email or the customer ID), `blocked_by_email`, `created_at_gte`, or `created_at_lte`. It returns 10 entries per page by default: set `page_size` to return up to 100, and `page_number` to page through. ### Block a Customer Send either `customer_id` or `email` at the top level of the body. If you send both, the block uses `customer_id`. `reason` is optional and shows on the entry's page. A new block returns HTTP `201`. ```typescript Node.js expandable theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); // Block by customer ID const entry = await client.blocklist.customers.create({ customer_id: 'cus_0NmichXWP8JYBB9Dw1Unj', reason: 'Chargeback on pay_0NmichXuYoNoapmr', }); // Or block by email const byEmail = await client.blocklist.customers.create({ email: 'buyer@example.com', reason: 'Repeated refund abuse', }); console.log(entry.id, entry.cancelled_subscription_ids); ``` ```python Python expandable theme={null} import os from dodopayments import DodoPayments client = DodoPayments(bearer_token=os.environ["DODO_PAYMENTS_API_KEY"]) # Block by customer ID entry = client.blocklist.customers.create( customer_id="cus_0NmichXWP8JYBB9Dw1Unj", reason="Chargeback on pay_0NmichXuYoNoapmr", ) # Or block by email by_email = client.blocklist.customers.create( email="buyer@example.com", reason="Repeated refund abuse", ) print(entry.id, entry.cancelled_subscription_ids) ``` ```bash cURL theme={null} curl -X POST https://live.dodopayments.com/blocklist/customers \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "customer_id": "cus_0NmichXWP8JYBB9Dw1Unj", "reason": "Chargeback on pay_0NmichXuYoNoapmr" }' ``` The response describes the entry and the subscriptions the call cancelled: ```json Response theme={null} { "id": "bcu_7Hq2mV9kRt4LxYw3Pz", "customer_id": "cus_0NmichXWP8JYBB9Dw1Unj", "customer_name": "wow guy", "customer_email": "wowguy@example.com", "identifier": "cus_0NmichXWP8JYBB9Dw1Unj", "reason": "Chargeback on pay_0NmichXuYoNoapmr", "source": "api", "blocked_by_email": null, "created_at": "2026-09-02T12:09:41Z", "unblocked_at": null, "cancelled_subscription_ids": ["sub_3Fk8pW2nQs6MzXc1"], "subscriptions_swept": true } ``` These fields need the most attention: | Field | Description | | - | - | | `identifier` | The customer ID or email you sent. | | `source` | Where the block came from: `blocklist_page`, `customer_page`, `payment_page`, `dispute_page`, or `api`. An API key always records `api`, whatever `source` you send. | | `blocked_by_email` | The dashboard user who added the block. `null` for an API key. | | `cancelled_subscription_ids` | Subscriptions this call cancelled. Present on the create response only. | | `remaining_subscription_ids` | Subscriptions still live, because a cancellation failed or the call reached its limit of 25 cancellations. | | `subscriptions_swept` | `false` when live subscriptions remain, or when Dodo Payments could not list them. Repeat the call until it is `true`. The block itself is already in force. | > [!NOTE] > > Blocking a customer who is already blocked returns HTTP `409` with `CUSTOMER_ALREADY_BLOCKED`, unless subscriptions are still waiting to be cancelled. In that case, the call continues the cancellation instead and returns HTTP `200`. ### Check Whether a Customer Is Blocked [Get Customer Detail](/api-reference/customers/get-customers-1) returns two extra fields: `blocked_at`, the time the active block was added (`null` when the customer is not blocked), and `blocklist_entry_id`, the entry behind it. The [List Customers](/api-reference/customers/get-customers) endpoint leaves both empty. ### Unblock a Customer ```typescript Node.js theme={null} await client.blocklist.customers.delete('bcu_7Hq2mV9kRt4LxYw3Pz'); ``` ```python Python theme={null} client.blocklist.customers.delete("bcu_7Hq2mV9kRt4LxYw3Pz") ``` ```bash cURL theme={null} curl -X DELETE https://live.dodopayments.com/blocklist/customers/bcu_7Hq2mV9kRt4LxYw3Pz \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" ``` The endpoint returns HTTP `204` on success, and HTTP `404` when the ID matches no active block. Unblocking restores checkout and portal writes, and reactivates no subscription. ## Best Practices * **Record the reason.** A short reason on the block, plus notes for anything that happens later, gives your support team the full story without leaving the dashboard. * **Block after a chargeback.** Open the customer's page from the dispute or the payment and block them there, or automate it from the `dispute.opened` webhook with `POST /blocklist/customers`. See [Disputes](/features/transactions/disputes). * **Check `subscriptions_swept`.** When you block through the API, repeat the call until the response reports `true`, so no live subscription is left behind. * **Refund separately.** A block stops future purchases only. If you owe the customer money, refund the payment as usual. * **Review the list.** Unblock customers whose issue is resolved. Unblocking is immediate and keeps the history. ## Related > [card] [Customer Management](/features/customers) > > Find a customer, open their details page, and manage their subscriptions. > [card] [Customer Portal](/features/customer-portal) > > What a blocked customer can and cannot do in the portal. > [card] [Disputes](/features/transactions/disputes) > > Respond to chargebacks and decide when a block is warranted. > [card] [Error Codes](/api-reference/error-codes) > > What `PAYMENT_NOT_PERMITTED` and `PORTAL_ACTION_NOT_PERMITTED` mean. # Customer Portal Source: https://docs.dodopayments.com/features/customer-portal Let customers manage their subscriptions, payment methods, invoices, and license keys in a hosted portal, without contacting your support team. > [!NOTE] > > The Customer Portal is a hosted site where your customers manage their subscriptions, view and download invoices, and retrieve license keys without contacting support. > [card] [Create Portal Session (API)](/api-reference/customers/create-customer-portal-session) > > Create a portal link for one customer, valid for 24 hours. > [card] [Subscriptions](/features/subscription) > > Recurring plans, upgrades, downgrades, and add-ons. ![Revamped Customer Portal showing active subscriptions, payment methods, and billing history](https://mintcdn.com/dodopayments/kCngKZVrb0rZMS1f/images/customer-portal/new-portal.png?fit=max\&auto=format\&n=kCngKZVrb0rZMS1f\&q=85\&s=9431b2e24142e47cb39dc84c1a0303fe) ## What Is the Customer Portal? The portal is a self-service site, branded with your business name, where customers can: * **Access billing history**: View past payments and download invoices. * **Manage subscriptions**: View subscription details, pause and resume, and cancel immediately or at the next billing date, as your settings allow. * **Update payment methods**: Change the payment method on a subscription, or reactivate a subscription that is on hold. * **Retry failed payments**: Retry a failed renewal with the saved payment method, when you turn on [Payment Retries](/features/recovery/payment-retries). * **Retrieve license keys**: See the license keys tied to their purchases. * **Return to your app**: When you pass a `return_url`, the portal shows a back link to your business. On mobile, a back arrow in the header returns to the portal overview. > [!NOTE] > > If you [block a customer](/features/customer-blocklist), their portal becomes **read-only**. They can still sign in and view invoices, subscriptions, and license keys, but they can't cancel, pause, or resume a subscription, change plans, or update a payment method. The portal profile returns `read_only: true` so a custom integration can disable its own controls. ## Key Benefits * **Lower support volume**: Customers handle common billing requests themselves. * **Faster access**: Customers get invoices and license keys as soon as they sign in. * **Lower churn risk**: Customers see renewal dates and plan details before they are charged. * **Signed, expiring links**: Every sign-in link is signed and expires after 24 hours. * **Localized experience**: The portal is available in 23 languages and picks one from the customer's browser settings. ## Access Methods Customers reach the portal through a static link or a dynamic link. ### Static Link (Email-Based Access) The static link never expires. A customer opens it, enters their email address, and receives a sign-in link by email. The static link depends on the environment: **Test Mode** (for testing and development): ```bash theme={null} https://test.customer.dodopayments.com/login/{business_id} ``` **Live Mode** (for production with real transactions): ```bash theme={null} https://customer.dodopayments.com/login/{business_id} ``` Replace `{business_id}` with your business ID, then share the link with your customers. The **Static Link** in the **Share Invite** dialog already contains it. ![Email-based login screen](https://mintcdn.com/dodopayments/kIuKVjhdOQFWlzSx/images/customer-portal/email-login.png?fit=max\&auto=format\&n=kIuKVjhdOQFWlzSx\&q=85\&s=bd8ee54177bc23e12e3657c87f487bae) **1. Merchant Flow** 1. Go to **Sales → Customers** and open a customer, or use the **Invite** column in the list. 2. Click **Share Invite**. 3. Copy the **Static Link** and share it with your customer. **2. Customer Flow** 1. Open the static link. 2. Enter the email address used at purchase and click **Get Access Link**. 3. Open the emailed sign-in link. It is valid for 24 hours. If the email doesn't arrive, click **Resend link** under **Didn't get it?**. The button is available again 30 seconds after each send. > [!TIP] > > The page always shows the same confirmation. Dodo Payments emails a link only when the address belongs to a customer of your business, so the page doesn't reveal who your customers are. > [!NOTE] > > Sign-in emails are not sent in test mode. To open a test mode portal, use the **Dynamic Link** or create a session through the API. ### Dynamic Link (Magic Link) A dynamic link signs one customer straight into the portal, without an email step. It expires 24 hours after it is created. > [!WARNING] > > A dynamic link stops working after 24 hours. When it expires, the customer sees an expiry page. Generate a new link and send it again. ![Magic link direct access](https://mintcdn.com/dodopayments/kIuKVjhdOQFWlzSx/images/customer-portal/magic-link.png?fit=max\&auto=format\&n=kIuKVjhdOQFWlzSx\&q=85\&s=8e63714f40468bd6e42c811e194f2698) **1. Merchant Flow** 1. Go to **Sales → Customers** and open the customer. 2. Click **Share Invite**. 3. Copy the **Dynamic Link** and share it with your customer. **2. Customer Flow** 1. Open the dynamic link. 2. The Customer Portal opens directly, without an email address. ## Portal Features The portal overview is a single page. On desktop, a panel on the left describes the portal. The main area lists the customer's subscriptions, payment methods, and billing history. > [card] Active Subscriptions > > Each subscription shows its plan name, price, renewal date, validity, payment method, and the number of add-ons if it has any. If a paid plan has no payment method, the card shows **Link Payment Method**. **Manage subscription** opens its details, where the customer can edit billing details, change plan, pause, or cancel. > [card] Payment Methods > > Saved payment methods, such as cards with their network and last four digits, UPI, wallets, and bank methods. A saved Apple Pay or Google Pay method shows the card behind the wallet. Change a subscription's payment method from its details page. > [card] Billing History > > Every payment in a table with **Payment ID**, **Date**, **Amount**, **Status**, **Payment Method**, and **Invoice** download. The payment method shows its logo and last four digits, for example the card behind an Apple Pay or Google Pay payment. > [card] Billing Information > > Name, email, phone number, and billing address, shown on the subscription details page. Customers can edit the name and billing address. ### Portal Overview The overview page shows active subscriptions, saved payment methods, and billing history in one scrollable view. ![Customer Portal main page showing active subscriptions and payment methods](https://mintcdn.com/dodopayments/kCngKZVrb0rZMS1f/images/customer-portal/new-portal.png?fit=max\&auto=format\&n=kCngKZVrb0rZMS1f\&q=85\&s=9431b2e24142e47cb39dc84c1a0303fe) ### Payment Methods & Billing History Further down the page are the saved payment methods and the billing history, with a status for each payment and a download link for each invoice. ![Payment methods and billing history with invoice downloads](https://mintcdn.com/dodopayments/kCngKZVrb0rZMS1f/images/customer-portal/payment-methods-invoices.png?fit=max\&auto=format\&n=kCngKZVrb0rZMS1f\&q=85\&s=1aed6644dbb338cda755798eda99a6f2) ## Language Support The Customer Portal is available in **23 languages**, so customers can manage subscriptions, payment methods, and billing history in their own language. ### How Language Selection Works * **Automatic detection**: On the first visit, the portal reads the preferred language from the browser and loads it if it is supported. Otherwise it uses English. * **Manual override**: Customers can change the language at any time with the language selector in the bottom-right corner of the page, on desktop and mobile. * **Persisted preference**: The portal stores the choice in the `NEXT_LOCALE` cookie for one year, so it remembers the language across visits. ### Supported Languages | Language | Code | Language | Code | | - | - | - | - | | English (default) | `en` | Korean | `ko` | | Arabic | `ar` | Malay | `ms` | | Catalan | `ca` | Polish | `pl` | | Chinese | `zh` | Portuguese | `pt` | | Croatian | `hr` | Romanian | `ro` | | Dutch | `nl` | Russian | `ru` | | French | `fr` | Serbian | `sr` | | German | `de` | Spanish | `es` | | Hebrew | `he` | Swedish | `sv` | | Indonesian | `id` | Thai | `th` | | Italian | `it` | Turkish | `tr` | | Japanese | `ja` | | | ## Plan Changes (Upgrade/Downgrade) Customers can upgrade or downgrade from the portal between products in the same **Product Collection**. > [!TIP] > > To let customers on existing subscriptions switch plans, add your subscription products to a Product Collection and turn on **Allow Subscription Updates**. Customers can then switch between plans in that collection from the portal. ### Available Actions | Action | Description | When Available | | - | - | - | | **Upgrade** | Move to a higher-tier plan in the same collection | **Allow Subscription Updates** is on | | **Downgrade** | Move to a lower-tier plan in the same collection | **Allow Subscription Updates** is on | ### How Plan Changes Work 1. The customer clicks **Change Plan** on the subscription details page. 2. The portal lists the other plans in the product collection. 3. The customer selects a plan. A **Confirm Plan Change** panel shows the current and updated plan, a line-item breakdown (a credit for the old plan and a charge for the new one), tax, and the amount due now. The customer can also enter a discount code here. 4. The customer confirms with the **Pay** button, which shows the amount due. 5. Dodo Payments calculates proration and collects the charge, either from the saved payment method or on a hosted checkout page if you collect plan-change payments by payment link (see [Collecting Plan Change Payments by Payment Link](#collecting-plan-change-payments-by-payment-link)). 6. The subscription moves to the new plan. Whether this happens immediately or only after the charge succeeds depends on your [payment failure handling](/developer-resources/subscription-upgrade-downgrade#handling-payment-failures). A plan change paid by payment link always waits for the payment. ![Subscription details page with Change Plan, Pause Subscription, and Cancel Subscription buttons](https://mintcdn.com/dodopayments/LwHMYe4qXgVFVIvC/images/customer-portal/change-plan-button.png?fit=max\&auto=format\&n=LwHMYe4qXgVFVIvC\&q=85\&s=22e54df49c79e7c9a85a98f735d8fe32) ![Confirm Plan Change panel showing current vs. updated plan, a line-item breakdown, discount code entry, and the Pay button](https://mintcdn.com/dodopayments/LwHMYe4qXgVFVIvC/images/customer-portal/confirm-plan-change.png?fit=max\&auto=format\&n=LwHMYe4qXgVFVIvC\&q=85\&s=421a8cd43d25264fce712d49d3a16a43) > [!NOTE] > > Plan changes work only between products in the same collection, and the target product must be a subscription or usage-based product. One-time products are rejected. ### Collecting Plan Change Payments by Payment Link By default, an immediate plan change charges the customer's saved payment method. With **Collect Plan Change Payments by Payment Link** turned on, the portal opens a hosted Dodo Payments checkout page in a new tab instead, and the customer pays there. This applies to upgrades and downgrades that result in a charge. ![Settings → Subscriptions page with the Collect Plan Change Payments by Payment Link toggle enabled and its tooltip explaining the behavior](https://mintcdn.com/dodopayments/LwHMYe4qXgVFVIvC/images/customer-portal/plan-change-payment-link-setting.png?fit=max\&auto=format\&n=LwHMYe4qXgVFVIvC\&q=85\&s=2f41719102abcbdadbe5cfb6a12fdfd1) ![Hosted Dodo Checkout page from a separate example, where the customer pays for a plan change](https://mintcdn.com/dodopayments/LwHMYe4qXgVFVIvC/images/customer-portal/plan-change-checkout.png?fit=max\&auto=format\&n=LwHMYe4qXgVFVIvC\&q=85\&s=91bbe7cab1c13809fa9dc240d851015e) > [!NOTE] > > The subscription stays on its **current plan** until the checkout payment succeeds. A failed or abandoned payment leaves the subscription unchanged. After a declined payment, the customer starts the plan change again from the Customer Portal to get a new checkout link. Scheduled downgrades (`effective_at: next_billing_date`) don't go through checkout; they apply on the next billing date as usual. This setting applies to **immediate** plan changes only. While a plan-change payment link is unpaid and unexpired, the portal rejects further plan-change requests on that subscription. > [card] [Plan Change via Payment Link (API)](/developer-resources/subscription-upgrade-downgrade#collecting-payment-via-a-checkout-link) > > How to request a payment link with `collect_via_payment_link` and handle the response. ### Business Controls Configure what customers can do with their subscriptions under **Settings → Subscriptions**. These settings are in the **Customer Portal** section, except **Collect Plan Change Payments by Payment Link**, which is in the **Billing and Renewals** section: * **Allow Subscription Updates**: Lets customers upgrade or downgrade. Off by default. * **Allow Immediate Cancellation**: Lets customers end their subscription and lose access at once. On by default. * **Allow Cancellation at Next Billing Date**: Lets customers cancel at the end of the period they have paid for. On by default. * **Offer a Discount When a Customer Cancels**: Offers a discount on the next billing cycle to a customer who starts to cancel. Off by default. See [Retention Offer](#retention-offer). * **Allow Subscription Pause**: Lets customers pause and resume their own subscriptions. Off by default. * **Collect Plan Change Payments by Payment Link**: Sends customers to a checkout page to pay for an immediate plan change, instead of charging their saved payment method. Off by default. > [card] [Product Collections](/features/product-collections) > > Set up product collections and configure upgrade and downgrade paths. ## Subscription Details **Manage subscription** on any active subscription opens its details page, which shows: * **Plan details**: The subscription name, price, renewal date, and validity period. * **Payment method**: The payment method on the subscription, with an **Edit** button. * **Billing information**: The name, email, phone number, and billing address, with an **Edit** button for the name and billing address. * **Billing history**: A table of all payments for this subscription. * **Pause Subscription**: Shown when you allow self-service pause. * **Cancel subscription**: Opens the cancellation dialog. ![Subscription details page showing plan info, payment method, billing information, and cancel option](https://mintcdn.com/dodopayments/kCngKZVrb0rZMS1f/images/customer-portal/subscription-details.png?fit=max\&auto=format\&n=kCngKZVrb0rZMS1f\&q=85\&s=4ae46f6878c9343b2e963c516952c9d3) ## Cancelling a Subscription Customers cancel from the subscription details page. **Cancel subscription** opens a dialog with two options: * **Cancel at next billing date**: The subscription stays active until the current billing period ends, then cancels. * **Cancel now**: The subscription is cancelled immediately. If you turn on the [Retention Offer](#retention-offer) and the subscription qualifies, the customer sees a discount offer before these options. > [!NOTE] > > Two settings under **Settings → Subscriptions** control these options separately: **Allow Immediate Cancellation** and **Allow Cancellation at Next Billing Date**. Both are on by default. Turning one off removes only that option, so you can offer one without the other. With both off, **Cancel subscription** is disabled, and its tooltip asks the customer to contact you. A customer with a cancellation already scheduled sees **Revoke Cancellation**, so they can stay, and **Cancel immediately**, which is the same action as **Cancel now**. These settings don't affect cancellations you make yourself. ![Cancel subscription dialog with options to cancel at next billing date or cancel immediately](https://mintcdn.com/dodopayments/kCngKZVrb0rZMS1f/images/customer-portal/cance-sub.png?fit=max\&auto=format\&n=kCngKZVrb0rZMS1f\&q=85\&s=66eb6e380c991826c431fd0c563cbfa6) ### Cancellation Reasons Before confirming, the customer must answer **Why are you cancelling?** by choosing a reason from a fixed list. They can also add an optional comment of up to 500 characters under **Additional comments**. Dodo Payments stores both on the subscription and returns them in webhook payloads and the API, so you can analyze why customers leave and tailor win-back messages. ![Cancellation modal with the 'Why are you cancelling?' dropdown showing reasons like Too expensive, Missing features, and Other](https://mintcdn.com/dodopayments/RlXcM7JO-E_w40Np/images/customer-portal/cancellation-reasons.png?fit=max\&auto=format\&n=RlXcM7JO-E_w40Np\&q=85\&s=979394da2a9aa3907cbf9f4e225f9a4b) | Value | Customer-facing label | | - | - | | `too_expensive` | Too expensive | | `missing_features` | Missing features | | `switched_service` | Switched to another service | | `unused` | Not using it enough | | `customer_service` | Poor customer service | | `low_quality` | Low quality | | `too_complex` | Too complex | | `other` | Other | The reason is stored in the subscription's `cancellation_feedback` field, and the comment in `cancellation_comment`. ```typescript theme={null} // `client` is a DodoPayments client, created as in the Integration Guide. // Read the captured feedback after a customer cancels. const subscription = await client.subscriptions.retrieve('sub_123'); console.log(subscription.cancellation_feedback); // e.g., "too_expensive" console.log(subscription.cancellation_comment); // e.g., "Switching to a competitor" ``` Both fields are also in the `subscription.cancelled` webhook payload. To set them yourself, pass them to `PATCH /subscriptions/{subscription_id}` when you cancel or schedule a cancellation through the API. > [!TIP] > > Use `cancellation_feedback` alongside [Subscription Dunning](/features/recovery/subscription-dunning) to tailor win-back emails. For example, send a discount code to customers who chose `too_expensive` and a feedback survey to those who chose `missing_features`. ## Retention Offer The retention offer gives a customer who starts to cancel a discount on their next billing cycle, so they can keep the subscription at a lower price. Each customer can accept the offer once for your business. ### Turning On the Offer To turn on the retention offer: **1. Open Subscription Settings** Go to **Settings → Subscriptions**. The setting is in the **Customer Portal** section. **2. Turn On the Offer** Turn on **Offer a Discount When a Customer Cancels**. The setting is off by default. **3. Set the Discount** Enter a percentage in **Discount on the next billing cycle**. You can enter a value from 1 to 100, with up to 2 decimal places. The default is 10%. The dashboard saves each change as you make it. ![Settings → Subscriptions page with the Offer a Discount When a Customer Cancels toggle turned on and a percentage entered in Discount on the next billing cycle](https://mintcdn.com/dodopayments/TB6T3Cjt2AWqcBhK/images/customer-portal/retention-offer-setting.png?fit=max\&auto=format\&n=TB6T3Cjt2AWqcBhK\&q=85\&s=9a2206d77e883620cc09c1d035e6cc1c) ### What the Customer Sees When the offer is on and the subscription qualifies, **Cancel subscription** opens a **Before you cancel** sheet. Under **Special offer for you**, the sheet shows the percentage off the next invoice. If the subscription has no other discount, the sheet also shows the current price and the discounted price. The customer then picks one of two buttons: * **Redeem Offer**: Applies the discount and keeps the subscription. The sheet changes to **Offer accepted** and shows the next billing date with the new amount next to the old amount. * **Continue to Cancel**: Opens the cancellation options, without the discount. A customer who has already scheduled a cancellation sees the offer when they click **Revoke Cancellation**. The sheet shows the date the subscription ends. **Redeem Offer** removes the scheduled cancellation and applies the discount. **Keep the cancellation** opens the usual options and leaves the scheduled cancellation in place. ![Before you cancel sheet in the Customer Portal showing a special offer of a percentage off the next invoice, with Continue to Cancel and Redeem Offer buttons](https://mintcdn.com/dodopayments/TB6T3Cjt2AWqcBhK/images/customer-portal/retention-offer.png?fit=max\&auto=format\&n=TB6T3Cjt2AWqcBhK\&q=85\&s=e5c6e675809879aab3339083ec55f8d9) ### Who Sees the Offer The customer sees the offer only when all of these conditions are true: * At least one of the two cancellation settings is on, or the customer has already scheduled a cancellation. * The subscription is `active`, `on_hold`, or `past_due`. A paused subscription doesn't qualify. * The subscription has a recurring amount above zero, before tax. * The subscription has no scheduled or pending plan change. * The customer hasn't accepted the offer before, on any of their subscriptions with your business. Turning the offer off and on again doesn't reset this. ### What Happens When the Customer Accepts Accepting the offer discounts the next renewal and keeps the subscription. * **One billing cycle**: The discount applies to the next renewal only. After that renewal, the price returns to what it was before the customer accepted. * **Other discounts**: If the subscription already has discount codes, the retention discount applies after them, to the already discounted price. * **Scheduled cancellation**: Accepting removes a scheduled cancellation, and the subscription's [`cancelled_by`](/features/subscription#see-who-cancelled-a-subscription) is cleared. * **Webhook**: The subscription's price and discounts change, so Dodo Payments sends `subscription.updated`. The status of the subscription doesn't change. * **Plan changes**: The retention discount doesn't carry over to a new plan. A plan change removes it. * **Percentage changes**: A new percentage applies to later acceptances only. Subscriptions that already accepted the offer keep the discount they accepted. The retention discount's ID appears in the subscription's `discounts` array (as `discounts[].discount_id`) while the discount applies. The discount isn't listed with your discount codes, you can't edit or delete it, and customers can't enter its code at checkout. ## Pausing a Subscription Pausing gives customers an option between keeping a subscription and cancelling it. A paused subscription stops billing but keeps its plan and history, so the customer can resume it later instead of buying again. Customers open the **Pause your subscription** dialog from the subscription details page. The dialog shows the current plan, warns that access ends immediately, and explains how billing dates move. The customer confirms with **Pause subscription**. ![Pause your subscription dialog showing the current plan, a warning that access is revoked immediately, and the pause confirmation button](https://mintcdn.com/dodopayments/JB6sccx0km6wps_z/images/customer-portal/pause-subscription.png?fit=max\&auto=format\&n=JB6sccx0km6wps_z\&q=85\&s=144a4f6ebd8f8dc8a40d210b134e3a65) The dialog tells the customer what happens, and the system behaves as described: * **Access stops immediately.** Features, downloads, and license keys included with the subscription stop working until the subscription is resumed. * **The pause has no end date.** The subscription stays paused until the customer resumes it. * **No paid time is lost.** The next billing date and the renewal date both move forward by the length of the pause. Resuming uses the same flow, confirmed with **Resume subscription**. The subscription returns to `active` and access is restored. > [!NOTE] > > The **Allow Subscription Pause** setting under **Settings → Subscriptions** controls self-service pause, and it is **off by default**. While it is off, customers can't start a new pause, but a customer can still resume a pause they started themselves. Pauses you start from the dashboard are not affected. > [card] [How Pausing Works](/features/subscription#pausing-and-resuming-subscriptions) > > Full pause behavior, including billing effects, usage settlement, and webhooks. ## Updating Payment Methods Customers change a subscription's payment method with **Edit** next to the payment method on the subscription details page. This is also how a customer reactivates a subscription that is on hold after a failed payment. ### Reactivating Subscriptions on Hold A subscription moves to `on_hold` when a payment fails. The portal shows **Your subscription is currently on hold** and asks the customer to update their payment method. When they do, Dodo Payments: 1. **Creates a charge** for the remaining dues 2. **Generates an invoice** for the charge 3. **Collects the payment** with the new payment method 4. **Reactivates the subscription** to `active` when the payment succeeds > [!WARNING] > > A subscription in `on_hold` doesn't renew. The customer must update their payment method to clear the dues and reactivate it. > [!NOTE] > > When the dues for an `on_hold` subscription are paid, the subscription becomes `active` again. ### Reactivating Subscriptions in a Grace Period If you set a [grace period](/features/subscription#grace-period), a failed renewal moves the subscription to `past_due` instead of `on_hold`. The customer keeps access until the deadline. Recovery works the same way: the customer updates the payment method, and the subscription returns to `active`. If they do nothing, at the deadline the subscription moves to `on_hold` or `cancelled`, as you configured, and access ends. ### Retrying a Failed Payment If you turned on [Payment Retries](/features/recovery/payment-retries), a subscription that is `on_hold` or `past_due` after a failed renewal shows a **Retry Payment** button. It charges the open renewal invoice again with the saved payment method, so a customer whose card is still valid can pay without entering new details. When the payment succeeds, the subscription returns to `active`. The portal also tells the customer when the next automatic retry runs. Each renewal invoice allows 3 retries, shared with the manual retries you send from the dashboard, with a cooldown between them. When the bank declines the card for good, or the payment needs the customer to authenticate, the portal asks the customer to update their payment method instead. See [Customer Retries from the Portal](/features/recovery/manual-retry#customer-retries-from-the-portal). ### Payment Method Update Flow **1. Access Subscription Details** Click **Manage subscription** on the subscription from the portal overview. **2. Click Edit on Payment Method** Click **Edit** next to the payment method. **3. Select or Add Payment Method** Choose a saved payment method, or click **Add Payment Method** and enter the new details. **4. Confirm Changes** Confirm the update. For an `on_hold` subscription, this creates a charge for the remaining dues. **5. Complete Payment (If On Hold)** If the subscription is on hold, the customer is redirected to pay the remaining dues. When the payment succeeds, the subscription is reactivated. **6. Confirmation** The portal confirms that the payment method was updated and, for an on-hold subscription, that it is active again. > [!NOTE] > > When no dues are owed, changing the card creates a zero-amount payment to verify the new card. The customer gets no payment receipt email for it, but the `payment.succeeded` webhook still fires. A card update that also pays outstanding dues sends the usual receipt. ## Integration Examples To send a customer from your app to the portal, create a portal session on your server and redirect the customer to the returned `link`. The link is valid for 24 hours. ```typescript Node.js theme={null} // Server: `client` is a DodoPayments client, created as in the Integration Guide. const session = await client.customers.customerPortal.create('cus_123', { return_url: 'https://yourapp.com/account', // optional: shown as a back link in the portal }); // Send session.link to the browser, then redirect the customer: // window.location.href = session.link; ``` To have Dodo Payments also email the link to the customer, pass `send_email: true`. ## Unified Customer Portal Besides your business's portal, Dodo Payments runs a **Unified Customer Portal** at [customer.dodopayments.com](https://customer.dodopayments.com). There, customers see and manage their purchases and subscriptions from every business that sells through Dodo Payments. ![Unified Customer Portal](https://mintcdn.com/dodopayments/eNGWg9ca-WxQ9nMf/images/changelog/unified-customer-portal.png?fit=max\&auto=format\&n=eNGWg9ca-WxQ9nMf\&q=85\&s=bceabb06ca0f00aa2a458f4af95a5cda) ### Unified Portal Features * **Cross-business visibility**: See purchases and subscriptions from every Dodo Payments merchant in one place. * **Centralized management**: Manage subscriptions with different businesses from one site. * **Unified billing history**: Access invoices and payment history for all purchases. * **Single sign-in**: Sign in once with an email address to reach purchases from all Dodo Payments merchants. > [!TIP] > > The Unified Customer Portal works alongside your business's portal. Customers can use either one. ## Troubleshooting * **Link expired**: Generate a new dynamic link and send it to the customer. * **Email not recognized**: Ask the customer to use the email address from their purchase. No sign-in email is sent for an address that isn't a customer of your business. * **Subscription on hold**: The customer updates their payment method in the portal, or clicks **Retry Payment** when you turn on Payment Retries. Dodo Payments charges the remaining dues and reactivates the subscription when the payment succeeds. * **Payment method update failed**: If the payment fails while updating an `on_hold` subscription, the subscription stays on hold. The customer can try again with a different payment method. > [card] [Design & Theme Customization](/features/design) > > Customize the portal with pre-built themes, typography, and colors, with a live preview, from the Design page. # Customer Wallets Source: https://docs.dodopayments.com/features/customer-wallet Give customers a credit balance. Issue promotional or goodwill credit, refund as credit, and apply balances to future charges. > [card] [Get Customer Wallets](/api-reference/customers/get-customer-wallets) > > Get a customer's balance in each currency. > [card] [Create Ledger Entry](/api-reference/customers/post-customer-wallets-ledger-entries) > > Add funds to or deduct funds from a wallet. > [card] [List Ledger Entries](/api-reference/customers/get-customer-wallets-ledger-entries) > > Page through every wallet transaction. ## What Are Customer Wallets? A customer wallet is a merchant-issued credit balance, with one balance per currency. Credit reduces the amount due on the customer's future charges. It can't be withdrawn or refunded to a card or bank account. Use wallets to: * **Issue goodwill credit**, such as compensation for service downtime * **Handle refunds** as wallet balance instead of a refund to the card * **Issue promotional balances**, such as welcome bonuses or loyalty rewards * **Apply wallet funds to subscription charges** automatically at billing time * **Track every transaction** in a ledger with the balance before and after > [!NOTE] > > You don't create wallets yourself. A customer's wallet for a currency is created, with a zero balance, the first time you add a ledger entry in that currency. Until then, [Get Customer Wallets](/api-reference/customers/get-customer-wallets) returns no entry for that currency. > [!WARNING] > > **Customer Wallets ≠ Credit-Based Billing** > > Customer Wallets hold currency-denominated credit that Dodo Payments applies to subscription charges. To track usage units such as API calls, tokens, or compute hours, use [Credit-Based Billing](/features/credit-based-billing) instead. ![Customer Wallets](https://mintcdn.com/dodopayments/9oQrV7vsGpxeyDkL/images/customer/customer-wallet.png?fit=max\&auto=format\&n=9oQrV7vsGpxeyDkL\&q=85\&s=a4a7ff3c89f4074f37e19b8d99d49ef5) ## How It Works When a subscription renews or a plan change creates a charge, Dodo Payments first applies the customer's wallet balance in that currency, then charges the payment method for the rest. If the balance covers only part of the charge, the wallet pays that part. ### Automatic Setup You don't need to set anything up. Add a ledger entry through the API, or click **Apply Credit/Debit** on the customer's **Wallets** tab in the dashboard, and the wallet for that currency is ready to use. ### Multi-Currency Support Each currency has its own balance. Each wallet in the [Get Customer Wallets](/api-reference/customers/get-customer-wallets) response has a `currency` and a `balance` in the smallest currency unit, and the response adds `total_balance_usd`, the sum of all balances converted to USD. Customer wallets support all currencies Dodo Payments supports, with a separate balance per currency. ## Working with Wallets ### Check Customer Balances Get a customer's balance in every currency, for example to confirm the balance before a purchase or to show it in your app. > [card] [Get Customer Wallet Balances](/api-reference/customers/get-customer-wallets) > > Get a customer's wallet balances in all currencies. ### Add or Deduct Funds Add funds, such as a welcome bonus or a refund balance, or deduct funds, such as a manual charge. `entry_type`, `currency`, and `amount` are required. `amount` is a positive integer in the smallest currency unit. Add a `reason` (up to 500 characters) for your audit trail, and an `idempotency_key` to prevent duplicates. The response is the updated wallet. > [!NOTE] > > `entry_type` is `'credit'` to add funds to the wallet and `'debit'` to subtract funds from it. A debit larger than the balance fails with `400`. > [card] [Create Customer Wallet Ledger Entry](/api-reference/customers/post-customer-wallets-ledger-entries) > > Add funds to or deduct funds from a customer's wallet. ### View Transaction History List every credit and debit for a customer, with pagination and an optional `currency` filter. Each entry has an `event_type` (`payment`, `payment_reversal`, `refund`, `refund_reversal`, `dispute`, `dispute_reversal`, or `merchant_adjustment`), the `amount`, and the `before_balance` and `after_balance`. Use the ledger to reconcile accounts and to answer customer questions. > [card] [List Customer Wallet Ledger Entries](/api-reference/customers/get-customer-wallets-ledger-entries) > > List every wallet transaction for a customer. ## Real-World Examples The examples use the TypeScript SDK. `client` is a `DodoPayments` client, created as in the [Integration Guide](/developer-resources/integration-guide). ### Refund to Wallet To refund a customer as wallet balance instead of back to their card, add the amount with a credit entry. The funds stay with your business for the customer's next purchase. ```javascript theme={null} async function refundToWallet(customerId, refundAmount, originalPaymentId) { await client.customers.wallets.ledgerEntries.create(customerId, { amount: refundAmount, // Amount in cents currency: 'USD', entry_type: 'credit', reason: `Refund for payment ${originalPaymentId}`, idempotency_key: `refund_${originalPaymentId}` }); } ``` > [!NOTE] > > A ledger credit doesn't refund the original payment. When you refund a payment through the Refunds API, Dodo Payments returns any part of it that the wallet paid to the wallet automatically. ### Welcome Bonus / Promotional Balance Give new customers a welcome bonus to encourage their first purchase. ```javascript theme={null} async function addWelcomeBonus(customerId) { await client.customers.wallets.ledgerEntries.create(customerId, { amount: 1000, // $10.00 promotional balance currency: 'USD', entry_type: 'credit', reason: 'Welcome bonus - $10 promotional balance', idempotency_key: `welcome_${customerId}` }); } ``` ### Subscription Payment from Wallet Deduct funds from a wallet to pay for a charge you bill yourself. Renewals don't need this step, because Dodo Payments applies the balance to them automatically. ```javascript theme={null} async function deductForPurchase(customerId, purchaseAmount, purchaseId) { try { await client.customers.wallets.ledgerEntries.create(customerId, { amount: purchaseAmount, currency: 'USD', entry_type: 'debit', reason: `Manual charge for purchase ${purchaseId}`, idempotency_key: `charge_${purchaseId}` }); } catch (error) { if (error.status === 400) { console.log('Insufficient wallet balance'); } } } ``` ### Multi-Currency Support Keep separate balances for customers in different regions. > [accordion] US Customers > > Manage USD funds for US-based customers. > > ```javascript theme={null} > await client.customers.wallets.ledgerEntries.create(customerId, { > amount: 20000, // $200.00 in cents > currency: 'USD', > entry_type: 'credit', > reason: 'USD goodwill credit', > idempotency_key: `usd_deposit_${paymentId}` > }); > ``` > [accordion] European Customers > > Manage EUR funds for Europe-based customers. > > ```javascript theme={null} > await client.customers.wallets.ledgerEntries.create(customerId, { > amount: 18000, // €180.00 in cents > currency: 'EUR', > entry_type: 'credit', > reason: 'EUR goodwill credit', > idempotency_key: `eur_deposit_${paymentId}` > }); > ``` > [accordion] UK Customers > > Manage GBP funds for UK-based customers. > > ```javascript theme={null} > await client.customers.wallets.ledgerEntries.create(customerId, { > amount: 15000, // £150.00 in pence > currency: 'GBP', > entry_type: 'credit', > reason: 'GBP goodwill credit', > idempotency_key: `gbp_deposit_${paymentId}` > }); > ``` ## Best Practices ### Prevent Duplicate Transactions Pass an `idempotency_key` derived from the event that caused the entry, such as an order or payment ID, so a retry can't add or deduct the funds twice. If you repeat a request with the same key, Dodo Payments creates no new entry and returns the current wallet. ```javascript theme={null} async function addFundsSafely(customerId, amount, reason, eventId) { // Derive the key from the event, not from the time, so retries reuse it. const idempotencyKey = `credit_${customerId}_${eventId}`; try { const result = await client.customers.wallets.ledgerEntries.create(customerId, { amount: amount, currency: 'USD', entry_type: 'credit', reason: reason, idempotency_key: idempotencyKey }); // Replaying the same idempotency_key creates no duplicate entry and // returns the wallet, so no special duplicate handling is required. return { success: true, wallet: result }; } catch (error) { if (error.status === 400) { // e.g. insufficient balance on a debit return { success: false, reason: 'insufficient_balance' }; } throw error; } } ``` ### Check Balances Before Charging Before you deduct a large amount from a wallet, confirm that the balance covers it. ```javascript theme={null} async function checkBalanceBeforeOperation(customerId, requiredAmount) { const wallets = await client.customers.wallets.list(customerId); const usdWallet = wallets.items.find(w => w.currency === 'USD'); if (!usdWallet || usdWallet.balance < requiredAmount) { throw new Error('Insufficient funds for this operation'); } return usdWallet.balance; } ``` ## What's Coming Next Customer wallets don't support these features: * **Balance Expiration**: Wallet funds don't expire. * **Analytics**: There are no spending reports or balance trends. Use the ledger to build your own. * **Webhooks**: No webhook fires when a balance changes, and there are no low-balance alerts. To track changes, list the ledger entries. > [!TIP] > > Start with basic funding and deduction, then automate more of your billing workflow as your business grows. # Customer Management Source: https://docs.dodopayments.com/features/customers View every customer, their payments, subscriptions, and wallet balances in the Dodo Payments dashboard, and manage customer records through the API. ## Overview The **Customers** page lists everyone who has bought from your business. From a customer's page you can review their payments and subscriptions, check and adjust their wallet balances, send them a Customer Portal link, and block them. The same customer records are available through the API. > [card] [Customer Dashboard](#accessing-the-customers-page) > > View all customers in one list, filter by name or email, and open any customer's details. > [card] [Customer Wallets](/features/customer-wallet) > > Hold prepaid balances that Dodo Payments applies to subscription charges. > [card] [Customer Portal](/features/customer-portal) > > Let customers manage their subscriptions, invoices, and license keys themselves. > [card] [API Management](#api-management) > > Create, update, and retrieve customers through the API. ## Accessing the Customers Page **1. Navigate to Customers** In the dashboard, go to **Sales → Customers**. **2. View Customer List** The page lists every current and past customer of your business. ![Customers list page showing all customers with their details](https://mintcdn.com/dodopayments/IKECEhkZu9f1KFmK/images/customer/customers-list.png?fit=max\&auto=format\&n=IKECEhkZu9f1KFmK\&q=85\&s=d110d27ad8c3fa8e623241b62d47601c) ## Customer Information The customer table shows one row per customer, with the columns below. ### Customer List Columns * **Customer Name**: The customer's full name, with an avatar. * **Customer Id**: The unique identifier, starting with `cus_`. Use it in API calls. * **Email**: The customer's email address. The customer uses it to sign in to the Customer Portal. * **Phone Number**: The customer's phone number, if one was provided. * **Created At**: When the customer record was created. Hover over the value to see the time in UTC. * **Invite**: A **Share Invite** button that opens the Customer Portal links for this customer. ### Page Features * **Column visibility**: Choose which columns the table shows. * **Filters**: Find customers by **Name** or **Email Address**. * **Pagination**: Move through the list and set the number of **Rows per page**. > [!TIP] > > Hide the columns you don't use so the table shows only what matters to your workflow. ## Customer Details Page Click a customer to open their **Customer Information** page: ![Customer details page showing customer information and transaction history](https://mintcdn.com/dodopayments/IKECEhkZu9f1KFmK/images/customer/customer-details.png?fit=max\&auto=format\&n=IKECEhkZu9f1KFmK\&q=85\&s=4f1d97a2d31f5e64fb4a075dde6239ff) ### About Section The top of the page shows the customer's core details: * **Name**: The customer's full name. * **Email**: The customer's email address. * **Customer ID**: The identifier to use in the API and in support requests. * **Created At**: When the customer record was created. Below the details, the **Customer Portal** card has a **Share Invite** button. It shows a static link and a 24-hour dynamic link to the customer's portal. See [Access Methods](/features/customer-portal#access-methods). ### Side Panel A side panel next to the details shows more about the customer. A section with nothing to show is hidden. * **Payment methods**: The customer's saved payment methods by type, such as cards, Apple Pay, and UPI. A card shows its network, last four digits, expiry, issuing country, and card holder, and an expired card is marked. * **Discounts**: The discounts on the customer's active subscriptions. * **License keys**: The customer's license keys, with status and created date. Each key links to its page. * **Metadata**: The metadata on the customer record. ### Customer Activity Tabs Tabs below the details show the customer's activity. The main ones are described here. The page also has **Credits**, **Entitlements**, and **Sent Emails** tabs; see [Customer Email Logs](/features/email-logs) for **Sent Emails**. > [tab] Transactions History > > The customer's payments, refunds, and disputes. The payments table shows: > > * **Payment ID**: The payment's identifier, starting with `pay_`. > * **Status**: The payment status, for example **Successful**, **Failed**, or **Refunded**. > * **Amount**: The payment amount. > * **Date**: When the payment was created. > * **Pricing Type**: One-time or subscription. > * **Payment Method**: The payment method used, such as card or UPI. > * **Customer Email**: The email address on the payment. > * **Refund**: An **Initiate Refund** button. > * **Actions**: More options for the payment. > [tab] Active Subscriptions > > The customer's subscriptions, shown when the customer has at least one: > > * Product name and subscription ID > * Next billing date and next billing amount > * Subscription status > * Click a row to open the subscription and manage or cancel it > [tab] Wallets > > The customer's wallet balances and wallet ledger: > > * A **Total Balance**, with a per-currency breakdown under **View Breakdown** > * Every fund addition and deduction, with the balance before and after each entry > * The event type and reason for each entry > * An **Apply Credit/Debit** button to add or deduct funds from the dashboard > > Use the ledger to reconcile a customer's balance. > [!NOTE] > > The **Wallets** tab shows every change to a customer's wallet, so you can trace how the current balance was reached. ## Blocking a Customer Block a customer who commits fraud or abuses refunds so they can't check out with you again. Blocking cancels the customer's live subscriptions and makes their Customer Portal read-only. A blocked customer's page shows a **Blocked** badge, an **Unblock Customer** button, and an **Activity Log** of notes explaining the block. Manage all blocks from **Settings → Blocklist**. > [card] [Customer Blocklist](/features/customer-blocklist) > > What a block does, how emails are matched, and how to block from the dashboard or the API. ## Customer Portal The Customer Portal is a hosted self-service site where your customers manage their subscriptions, view billing history, and retrieve license keys without contacting support. ### Portal Capabilities In the portal, customers can: * **View Billing History**: See past payments and download invoices. * **Manage Subscriptions**: View details, change plan, pause, or cancel, depending on your settings. * **Retrieve License Keys**: See the license keys tied to their purchases. * **Update Billing Details**: Change the name, billing address, and payment method on a subscription. Email address and phone number are shown but can't be edited in the portal. > [card] [Learn More About Customer Portal](/features/customer-portal) > > Portal features, access methods, and integration examples. ## Customer Wallets Customer Wallets hold prepaid money for a customer, one balance per currency. Dodo Payments applies a wallet balance to the customer's subscription charges before it charges their payment method. You add or deduct funds with a ledger entry, for example to issue a refund as wallet balance or a promotional bonus. ### Key Features * **Multi-Currency Support**: Each currency has its own balance. * **Prepaid Balances**: Funds are applied to future subscription renewals and plan-change charges. * **Transaction History**: The ledger records every fund addition and deduction. * **API-First Design**: Check balances and add or deduct funds through the API, or from the **Wallets** tab. > [card] [Learn More About Customer Wallets](/features/customer-wallet) > > Supported currencies, code examples, and best practices for customer wallet balances. ## API Management The Customers API lets you create, retrieve, and update customers, list them with filters, and manage their saved payment methods. ### Available API Endpoints > [card] [Create Customer](/api-reference/customers/create-customer) > > Create a customer. `name` and `email` are required. `phone_number` and `metadata` are optional. > [card] [List Customers](/api-reference/customers/get-customers) > > List customers page by page. Filter by `email`, by `name` (partial match), or by creation date. > [card] [Get Customer Details](/api-reference/customers/get-customers-1) > > Retrieve one customer by their ID. > [card] [Update Customer](/api-reference/customers/patch-customer) > > Update a customer's `name`, `email`, `phone_number`, or `metadata`. > [card] [Delete Payment Method](/api-reference/customers/delete-payment-method) > > Remove a saved payment method. The request fails with `409` if an active subscription uses it. > [card] [Create Portal Session](/api-reference/customers/create-customer-portal-session) > > Create a Customer Portal link for one customer, valid for 24 hours. ### Email Address Rules Dodo Payments accepts only customer email addresses that can receive mail. These rules apply when you create or update a customer, and to the new-customer details on payments and checkout sessions. An address is rejected if it: * Has no top-level domain, for example `dev@localhost`. * Ends with a top-level domain that is shorter than two characters or starts with a digit. * Uses an IP address as the domain, for example `user@[192.168.0.1]`. * Contains non-ASCII characters. To use an internationalized domain, convert the domain to its ASCII form, which starts with `xn--`, first. * Has a misplaced dot, for example `.user@example.com`, `user.@example.com`, or `us..er@example.com`. A customer created before these rules can still have such an address on file. Creating a payment or subscription for that customer can fail with `422` until you [update the customer's email](/api-reference/customers/patch-customer). > [!NOTE] > > Every endpoint requires your API key. Call the API from your server and never expose the key in client-side code. # Design & Theme Customization Source: https://docs.dodopayments.com/features/design Customize the look and feel of your checkout, storefront, and customer portal from one place. Choose pre-built themes, configure typography and colors, and apply per-section overrides, all with live preview. ![Design settings page with live preview of checkout, customer portal, and storefront](https://mintcdn.com/dodopayments/vsqWNGxzquCPMqJB/images/design/general-overview.jpg?fit=max\&auto=format\&n=vsqWNGxzquCPMqJB\&q=85\&s=89f19bfb791cb903fccb3ea7127246ba) The Design page is your central hub for branding every customer-facing surface: checkout, storefront, and customer portal. Changes apply instantly across all three and are previewed in real time before you save. Test mode and live mode hold separate designs — see [Copy Design From Test to Live Mode](#copy-design-from-test-to-live-mode). ## Key Highlights * **Unified Design Hub** — Configure checkout, storefront, and customer portal appearance from a single page * **Pre-Built Themes** — Start with a curated theme and customize from there * **Light & Dark Mode** — Define separate color palettes for each mode * **Live Preview** — See how your changes look across all surfaces before saving * **Per-Section Overrides** — Fine-tune individual sections without affecting the others * **Programmatic Control** — Override themes at checkout time via the Checkout Sessions API (`customization.theme_config`). A session's `theme_config` takes precedence over the dashboard design. Checkout SDK 2.0.1 removes the client-side `themeConfig` option * **Copy Test Design to Live** — Move a design you perfected in test mode into live mode in one step ## Getting Started Navigate to **Settings → Design** in your Merchant Dashboard. The Design page has four tabs: | Tab | Purpose | | :- | :- | | **General** | Business name, logo, theme selection, and global advanced settings | | **Checkout** | Override theme settings specifically for the checkout page | | **Storefront** | Override theme settings and configure storefront layout | | **Customer Portal** | Override theme settings for the customer portal | ## General Settings The **General** tab controls your baseline brand identity and global theme. ![General tab showing advanced settings with typography, colors, and border configuration](https://mintcdn.com/dodopayments/vsqWNGxzquCPMqJB/images/design/general-advanced-settings.jpg?fit=max\&auto=format\&n=vsqWNGxzquCPMqJB\&q=85\&s=00131c2a9d74d4c120bf85f588e358d8) ### Basic Configuration | Setting | Description | | :- | :- | | **Business Name** | The name displayed on checkout, storefront, and customer portal | | **Business Logo** | Your brand logo shown across all customer-facing pages | | **Theme** | Select a pre-built theme as your starting point | ### Advanced Settings Expand **Advanced Settings** to access granular controls: ![Advanced settings expanded showing full color configuration for light and dark modes](https://mintcdn.com/dodopayments/vsqWNGxzquCPMqJB/images/design/general-color-settings.jpg?fit=max\&auto=format\&n=vsqWNGxzquCPMqJB\&q=85\&s=c09ecc738beb79cff0d130f46bb72b0a) #### Typography | Setting | Options | Description | | :- | :- | :- | | **Primary Font** | Any Google Font | Main font for headings and body text | | **Secondary Font** | Any Google Font | Accent font for labels and secondary text | | **Font Size** | `xs`, `sm`, `md`, `lg`, `xl`, `2xl` | Global base font size | | **Font Weight** | `normal`, `medium`, `bold`, `extraBold` | Default font weight | #### Color Configuration Define separate color palettes for **Light Mode** and **Dark Mode**. Each mode supports: | Property | Description | | :- | :- | | **Background Primary** | Main background color | | **Background Secondary** | Secondary background (tabs, cards) | | **Text Primary** | Main text color | | **Text Secondary** | Muted text color | | **Button Primary** | Primary button background | | **Button Primary Text** | Text color on primary buttons | | **Button Secondary** | Secondary button background | | **Button Secondary Text** | Text color on secondary buttons | | **Border Primary** | Main border color | | **Border Secondary** | Accent border color | #### Border | Setting | Description | | :- | :- | | **Border Radius** | Controls the roundness of inputs, buttons, tabs, and cards (e.g., `0` for sharp corners, `8px` for rounded, `16px` for pill-shaped) | ## Pre-Built Themes Dodo Payments ships with four curated themes. Select one from the **Theme** dropdown on the General tab to instantly apply a cohesive design across checkout, storefront, and customer portal. ### Dodo Pulses The default Dodo Payments theme. Lime green accents give it an energetic, fresh feel. Clean sans-serif typography with generous spacing. > [tab] Light Mode > > ![Dodo Pulses theme in light mode showing checkout, customer portal, and storefront](https://mintcdn.com/dodopayments/fsVpks_kbNisjAe1/images/design/theme-dodo-pulses-light.png?fit=max\&auto=format\&n=fsVpks_kbNisjAe1\&q=85\&s=f081086300770146c0df373b6304ea12) > > Dodo Pulses in light mode > [tab] Dark Mode > > ![Dodo Pulses theme in dark mode showing checkout, customer portal, and storefront](https://mintcdn.com/dodopayments/fsVpks_kbNisjAe1/images/design/theme-dodo-pulses-dark.png?fit=max\&auto=format\&n=fsVpks_kbNisjAe1\&q=85\&s=d2fe47c69734ccb419471609095627fe) > > Dodo Pulses in dark mode ### Terminal A developer-oriented theme with monospaced typography and royal blue accents. Sharp corners and a technical aesthetic that pairs well with dev-tool and API-first products. > [tab] Light Mode > > ![Terminal theme in light mode showing checkout with blue accents and monospaced font](https://mintcdn.com/dodopayments/fsVpks_kbNisjAe1/images/design/theme-terminal-light.png?fit=max\&auto=format\&n=fsVpks_kbNisjAe1\&q=85\&s=3e3320fc9c073ed9bf3ebe7b03bf7a3f) > > Terminal in light mode > [tab] Dark Mode > > ![Terminal theme in dark mode showing checkout with blue accents and monospaced font](https://mintcdn.com/dodopayments/fsVpks_kbNisjAe1/images/design/theme-terminal-dark.png?fit=max\&auto=format\&n=fsVpks_kbNisjAe1\&q=85\&s=dea087e1c0fad9cf7a66fc37cfbda8ac) > > Terminal in dark mode ### Bumblebee Warm amber and gold accents with rounded, modern styling. Bold and high-contrast, well-suited for consumer-facing products that want to feel premium. > [tab] Light Mode > > ![Bumblebee theme in light mode showing checkout with amber accents](https://mintcdn.com/dodopayments/fsVpks_kbNisjAe1/images/design/theme-bumblebee-light.png?fit=max\&auto=format\&n=fsVpks_kbNisjAe1\&q=85\&s=e276288fe683a831d10add3f8af4eae0) > > Bumblebee in light mode > [tab] Dark Mode > > ![Bumblebee theme in dark mode showing checkout with gold accents](https://mintcdn.com/dodopayments/vsqWNGxzquCPMqJB/images/design/theme-bumblebee-dark.png?fit=max\&auto=format\&n=vsqWNGxzquCPMqJB\&q=85\&s=a35df24ccd45a9acb717652ce5b5fd19) > > Bumblebee in dark mode ### Bubblegum Playful pink and magenta accents with fully rounded corners. A modern, approachable look that works great for creative tools, design products, and lifestyle brands. > [tab] Light Mode > > ![Bubblegum theme in light mode showing checkout, customer portal, and storefront with pink accents](https://mintcdn.com/dodopayments/vsqWNGxzquCPMqJB/images/design/theme-bubblegum-light.png?fit=max\&auto=format\&n=vsqWNGxzquCPMqJB\&q=85\&s=3b53c9d3c6d07ef0ff44d4c613520789) > > Bubblegum in light mode > [tab] Dark Mode > > ![Bubblegum theme in dark mode showing checkout, customer portal, and storefront with pink accents](https://mintcdn.com/dodopayments/vsqWNGxzquCPMqJB/images/design/theme-bubblegum-dark.png?fit=max\&auto=format\&n=vsqWNGxzquCPMqJB\&q=85\&s=ef4a70ff8f289715628377b0631adf25) > > Bubblegum in dark mode > [!TIP] > > After selecting a pre-built theme, customize individual properties in Advanced Settings. Any unspecified properties fall back to the theme defaults. ## Per-Section Overrides Each section tab (Checkout, Storefront, Customer Portal) includes an **Override Theme** toggle. When enabled, you can customize that section's appearance independently from the global theme. ### Checkout Tab ![Checkout tab showing full checkout preview with product details and payment form](https://mintcdn.com/dodopayments/vsqWNGxzquCPMqJB/images/design/checkout-tab.jpg?fit=max\&auto=format\&n=vsqWNGxzquCPMqJB\&q=85\&s=a17880492490e6abe2f6b8b9e9f4680e) Override typography, colors, and border settings specifically for the checkout experience. The live preview shows: * Product information and pricing * Express checkout options (Apple Pay, Google Pay) * Payment method selection and card form * Discount code input and price breakdown ### Storefront Tab ![Storefront tab showing store URL, branding controls, and storefront preview](https://mintcdn.com/dodopayments/vsqWNGxzquCPMqJB/images/design/storefront-tab.jpg?fit=max\&auto=format\&n=vsqWNGxzquCPMqJB\&q=85\&s=3b45fc842eb771be573ae1a5744d82c5) Configure storefront-specific settings: | Setting | Description | | :- | :- | | **Store URL** | Your storefront address (e.g., `store.dodopayments.com/your-store`) | | **Store Name** | Toggle and set the name displayed on your storefront | | **Store Logo** | Toggle and upload a logo for the storefront header | | **Store Banner** | Toggle and upload a banner image | | **Product Description** | Toggle to show or hide product descriptions on cards | | **Override Theme** | Enable to customize typography, colors, and borders for the storefront only | ### Customer Portal Tab ![Customer portal tab showing subscription management, billing history, and payment methods preview](https://mintcdn.com/dodopayments/vsqWNGxzquCPMqJB/images/design/customer-portal-tab.jpg?fit=max\&auto=format\&n=vsqWNGxzquCPMqJB\&q=85\&s=38c16ef9ed1648f0f5d3851d7c91f17c) Override the theme for the customer portal, which includes: * Subscription management * Billing history * Payment methods * Wallet and credits ## Copy Design From Test to Live Mode Test mode and live mode keep separate design configurations. A theme you build while testing does not automatically appear to real customers. Instead of re-creating it by hand, copy your design from test mode to live mode in one step. **1. Open Design in Test Mode** Switch to test mode and go to **Settings → Design**. Save any pending changes first: only the saved test design is copied. **2. Start the Copy** Click **Copy to Live Mode**. The button appears once you have a saved theme or a published test storefront, and live mode must be activated. **3. Choose What to Copy** Select **Theme & customizations** (the general theme plus checkout, storefront, and Customer Portal overrides) and **Storefront details** (store name, logo, and banner). Storefront details is unavailable if no storefront is published in test mode. **4. Confirm** Click **Copy to Live Mode** in the dialog. > [!WARNING] > > Copying overwrites the existing live mode design. Review your live checkout and storefront after copying to confirm everything looks the way you expect. ## Related Pages > [card] [Checkout Features](/features/checkout) > > Checkout features including currency, language, tax, discounts, and more. > [card] [Overlay Checkout SDK](/developer-resources/overlay-checkout) > > Embed checkout as a modal overlay on your page. > [card] [Inline Checkout SDK](/developer-resources/inline-checkout) > > Embed checkout directly into your page layout. > [card] [Storefront](/features/storefront) > > Set up and manage your branded storefront. > [card] [Customer Portal](/features/customer-portal) > > Customer self-service portal for subscriptions and billing. > [card] [Multi-Brand Setup](/features/multi-brands) > > Run multiple brands under one account with separate branding. # Digital Product Delivery Source: https://docs.dodopayments.com/features/digital-product-delivery Deliver downloadable files, an external link, and instructions automatically after purchase with the Digital Files entitlement and short-lived presigned URLs. ## Overview Digital Product Delivery is the **Digital Files** entitlement type. You upload your files once to a Digital Files entitlement and attach the entitlement to a product. Dodo Payments then delivers presigned download links to every paying customer by email and in the Customer Portal. A Digital Files entitlement supports: * **Hosted file uploads**: Dodo Payments stores your files and serves them through short-lived presigned URLs. * **External download link**: one URL per entitlement that points to files hosted elsewhere, such as Dropbox, Google Drive, or S3. * **Download instructions**: free-form text shown to the customer on their order page and in the delivery email. You can combine all three on one entitlement. In the dashboard, add at least one file or an external download link. ## Key Features > [card] File Upload > > Upload files such as PDFs, ZIP archives, images, and videos, up to 500 MiB each. Dodo Payments streams each upload to storage. > [card] Multiple Files > > Attach as many files as you need to one entitlement. > [card] External Links > > Add an external download link, such as a Dropbox, Google Drive, or signed S3 URL, instead of or in addition to hosted files. > [card] Presigned URLs > > Dodo Payments serves hosted files through presigned URLs. Each download URL expires 15 minutes after it's generated. *** ## Set Up Digital Product Delivery **1. Open Entitlements** Go to **Entitlements** in the dashboard and click **+** to create an entitlement. **2. Choose Digital Files** Select **Digital Files** and enter a **Name** for the entitlement. **3. Add Files, Links, and Instructions** Configure any combination of these fields: * **Upload files**: upload one or more files. Each upload returns a `file_id` and adds the file to the entitlement's `digital_file_ids`. * **External Download Link**: a URL, starting with `http://` or `https://`, that customers can reach. Dodo Payments delivers it alongside the hosted files. * **Instructions**: free-form text shown to the customer, for example "Unzip and run setup.sh." ![Digital Files entitlement with file upload, external URL, and instructions fields](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/digital-files/create.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=33ad03277809d14585d247442c191462) **4. Save the Entitlement** Click **Create Entitlement**. You can now attach the entitlement to any product. ## Attach to Products Open a product, go to its **Entitlements** section, and select your Digital Files entitlement. Dodo Payments delivers the entitlement on every successful purchase or active subscription for that product. ![Product entitlements panel showing Digital Product Delivery selected](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/attach-to-product.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=965ad78262791fa8dbb712b4fdf89538) Attaching the Digital Files entitlement to a product alongside other entitlements. *** ## How Delivery Works Digital Files delivery follows the standard [grant lifecycle](/features/entitlements/introduction#how-grants-work). Each event affects a Digital Files grant as follows: | Event | Behavior | | - | - | | `payment.succeeded` (one-time) | Issues a grant. The grant carries presigned download URLs that expire after 15 minutes. Customers get fresh URLs by reopening the email link or the Customer Portal page. | | `subscription.active` | Issues a grant. Files stay accessible while the subscription is active. | | `subscription.renewed` | No change. The same grant continues, and every fetch generates new presigned URLs. | | `subscription.past_due` | No change. Downloads stay available for the whole [grace period](/features/subscription#grace-period). | | `subscription.on_hold` / `cancelled` / `expired` | Revokes the grant. Dodo Payments stops issuing new presigned URLs. | | `subscription.paused` | Revokes the grant. Dodo Payments stops issuing new presigned URLs until the subscription is resumed. | | `subscription.plan_changed` | Revokes the old grant and issues a new one for the new plan's entitlement. | | `refund.succeeded` (one-time) | Revokes the grant. | | Manual revoke | Revokes the grant with `revocation_reason: manual`. | > [!WARNING] > > Revocation stops Dodo Payments from issuing new download URLs, but it does **not** invalidate copies a customer has already downloaded. Treat a hosted file as delivered once the customer downloads it. *** ## Customer Experience ### Purchase Confirmation After a successful payment, the customer receives an email with download links and any instructions you configured. ![Purchase confirmation email showing download links for digital products](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/digital-product-delivery/2.png?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=54f5247f6d67fe5bb48736682995e23e) ### Customer Portal Access Customers can get download links again from the [Customer Portal](/features/customer-portal) while their grant is active. The portal generates fresh presigned URLs on demand, so the purchase keeps working after the links in the email expire. ![Customer portal interface showing available digital products for download](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/digital-product-delivery/3.png?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=490c6755474c1f00a93f7adde7dabb63) > [!TIP] > > Customers can download files from the confirmation email or open them at any time from the Customer Portal. *** ## Manage Files Programmatically ### Upload a File to an Entitlement To upload a file, send it as `multipart/form-data` in a `file` field. The optional `filename` field must come before the `file` part, because Dodo Payments ignores fields sent after it. Without `filename`, Dodo Payments uses the name of the uploaded file. The response returns the new `file_id`. ```typescript TypeScript expandable theme={null} import DodoPayments from 'dodopayments'; import { openAsBlob } from 'node:fs'; // Node.js 20 or later const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], environment: 'test_mode', }); // The SDK sends a FormData body as multipart/form-data. Append `filename` before `file`. const form = new FormData(); form.append('filename', 'pro-bundle.zip'); form.append('file', await openAsBlob('./pro-bundle.zip'), 'pro-bundle.zip'); const { file_id } = await client.entitlements.files.upload('ent_files_abc', { body: form }); console.log(file_id); ``` ```bash cURL theme={null} curl -X POST "https://test.dodopayments.com/entitlements/ent_files_abc/files" \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -F "filename=pro-bundle.zip" \ -F "file=@./pro-bundle.zip" ``` ### List Grants and Resolve Download URLs Each Digital Files grant has a `digital_product_delivery` object with a fresh presigned URL for every file. To read the URLs, list the entitlement's grants: ```typescript expandable theme={null} const grants = await client.entitlements.grants.list('ent_files_abc', { customer_id: 'cus_abc123', }); for (const grant of grants.items) { for (const file of grant.digital_product_delivery?.files ?? []) { console.log(file.filename, file.download_url, `expires in ${file.expires_in}s`); } } ``` ### Remove a File from an Entitlement To detach a file, pass its `file_id` and the entitlement ID: ```typescript theme={null} await client.entitlements.files.delete('YOUR_FILE_ID', { id: 'ent_files_abc' }); ``` *** ## Important Considerations * **Presigned URLs expire quickly.** Download URLs in grant payloads and webhook events are valid for 15 minutes. Don't store them. Fetch new URLs when the customer needs to download again. * **Updating files affects future purchases only.** Replacing or removing a file doesn't change downloads already issued. Each grant keeps the entitlement configuration from when it was created, so past customers can still get the version that was current then. * **Refunds don't invalidate downloaded copies.** A customer who already downloaded a file keeps that copy. For revocable content, such as license-restricted media or time-limited access, pair Digital Files with [License Keys](/features/license-keys) and validate the key at runtime. * **For sensitive content, prefer external URLs with their own authentication.** Presigned URLs from Dodo Payments are short-lived, but anyone with the URL can download the file until it expires. Externally hosted content behind an account login gives you more control. *** ## API Management > [card] [Create Entitlement](/api-reference/entitlements/create-entitlement) > > Create a Digital Files entitlement with an optional external URL and instructions. > [card] [Upload File](/api-reference/entitlements/upload-file) > > Upload a file of up to 500 MiB and attach it to the entitlement. > [card] [Delete File](/api-reference/entitlements/delete-file) > > Detach a file from the entitlement. > [card] [List Grants](/api-reference/entitlements/list-grants) > > List grants and read the resolved download URLs. > [card] [Update Entitlement](/api-reference/entitlements/update-entitlement) > > Update the instructions or external URL, or replace the files. > [card] [Revoke Grant](/api-reference/entitlements/revoke-grant) > > Revoke a customer's access manually. *** ## Webhooks Digital file delivery and revocation send the four [`entitlement_grant.*` webhook events](/developer-resources/webhooks/intents/entitlement-grant). For Digital Files grants, the payload includes a `digital_product_delivery` object with the resolved file list, the optional `instructions`, and the optional `external_url`. Each file carries a presigned `download_url`, the `filename`, the `content_type`, the `file_size` in bytes, and `expires_in`, the number of seconds until the URL expires: ```json expandable theme={null} "digital_product_delivery": { "files": [ { "file_id": "YOUR_FILE_ID", "download_url": "https://files.dodopayments.com/.../pro-bundle.zip?Signature=...", "filename": "pro-bundle.zip", "content_type": "application/zip", "file_size": 18742390, "expires_in": 900 } ], "instructions": "Unzip and run setup.sh from the project root.", "external_url": null } ``` *** ## Legacy Digital Product Delivery > [!NOTE] > > Products configured with the older `digital_product_delivery` block on the product itself have been **automatically migrated** to a Digital Files entitlement. Files uploaded through the legacy product file API are preserved: they stay downloadable and appear in grant payloads alongside newly uploaded files. The entitlement's `digital_files` configuration tracks them in the `legacy_file_ids` list. To add files, change instructions, or replace the external URL, edit the migrated Digital Files entitlement under **Entitlements**. > > Product responses still include the legacy product-level fields (`digital_product_delivery.external_url`, `digital_product_delivery.instructions`) for backward compatibility, but the entitlement is the source of truth. *** ## Best Practices * **Treat downloads as one-time deliveries.** Customers can share or lose links, so design your product on the assumption that anything they download is theirs to keep. * **Use instructions to set expectations.** For multi-file bundles, add an `instructions` line that explains what to install first or how to combine the files. * **Watch the 500 MiB cap.** Host larger artifacts, such as multi-GB datasets or video courses, externally, and link them with `external_url` instead of uploading them. * **Combine with License Keys for revocable access.** To revoke access to in-product features after a refund, pair the Digital Files entitlement with a License Key entitlement and validate the key at runtime. * **Test the Customer Portal refresh flow.** Confirm that a customer can return to the portal a week later and still get a working download link. The portal is the main recovery path when email links expire. # Discounts Source: https://docs.dodopayments.com/features/discount-codes Create promotional codes to drive conversions, run campaigns, and reward customers with percentage or flat-amount discounts across one‑time and subscription purchases. ![Discount codes overview cover](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/discount-codes/discount-code-cover.png?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=57f1a644801ddc5efc506b50541eaaba) Discount codes let you run targeted promotions and incentives. Create percentage or flat-amount discounts, set limits and expirations, restrict to products, and apply them at checkout. > [card] [Checkout Sessions](/developer-resources/checkout-session) > > Apply one or more stacked codes during hosted checkout with `discount_codes` and UI controls. > [card] [Get Discount](/api-reference/discounts/validate-discount) > > Retrieve a discount by its ID to inspect its status and restrictions. > [card] [Get Discount by Code](/api-reference/discounts/get-discount-by-code) > > Look up and validate a discount using its code name (e.g., "SAVE20"). > [card] [Create Discount (API)](/api-reference/discounts/create-discount) > > Programmatically create new discount codes. > [card] [List & Update Discounts](/api-reference/discounts/list-discounts) > > Browse and manage existing discounts; update or delete as needed. > [card] [Plan Change Discounts](/api-reference/subscriptions/change-plan) > > Apply discount codes when upgrading or downgrading subscription plans. ## What Are Discount Codes? Discount codes are promotional tokens that reduce order totals at checkout. Use them for seasonal campaigns, first-purchase incentives, win-back offers, or negotiated B2B pricing. Codes are percentage-based (e.g., 15% off) or flat-amount (e.g., \$5 off). You can stack up to 20 codes per checkout, payment, or subscription, so a customer can redeem both a welcome offer and a campaign code in the same transaction. Restrict codes to specific products, limit how many times each customer can use them, set expiration dates, and control who's eligible to redeem. ## Key Benefits * **Flexible discounts**: Percentage-based or flat-amount discounts * **Stackable codes**: Apply up to 20 codes per checkout, payment, or subscription * **Targeted control**: Restrict by product, subscription cycles, and customer eligibility * **Campaign governance**: Scheduled start dates, expiration dates, overall and per-customer usage limits * **Per-currency pricing**: Set the flat deduction, amount cap, and minimum subtotal per currency ## Creating Discount Codes Create discount codes in your Dodo Payments dashboard, then apply them in hosted checkout or via API. ![Discounts list in the Dodo Payments dashboard showing existing discount codes](https://mintcdn.com/dodopayments/Rh05LkBeJE32G3qq/images/discount-codes/discount-details.png?fit=max\&auto=format\&n=Rh05LkBeJE32G3qq\&q=85\&s=895a9dbe429c2ae57ecc1b317dd2b10d) ### Dashboard Setup * **Discount Name** (required): Internal label for the dashboard. * **Code** (required): The string customers enter at checkout. Generate a random code or enter your own (minimum 3 characters, uppercased automatically). Over the API, omit `code` to generate a random 16-character uppercase code. * **Type** (required): **Percentage** (a percent off) or **Amount** (a flat deduction). * **Amount** (required): For percentage, the percent off in the dashboard (e.g., `15` for 15%). Over the API, the same value is in basis points (`1500`). For amount, the flat deduction in the code's default currency. * **Start Date** (optional): Schedule the code to activate on a future date. Leave empty to activate immediately. * **Expiration Date** (optional): Date after which the code is no longer redeemable. * **Usage Limit** (optional, under **Advanced**): Maximum total redemptions across all customers. A [multi-subscription cart](/developer-resources/checkout-session#multi-subscription-cart) counts as one redemption. * **Per-Customer Usage Limit** (optional, under **Advanced**): Maximum redemptions by any single customer. Must be less than or equal to the overall usage limit when both are set. * **Customer Eligibility** (optional): Restrict who may redeem — all customers, first-time customers, existing customers, or a hand-picked list. * **Currency Options** (optional): The discount amount for each currency you sell in. See [Per-Currency Options](#per-currency-options). * **Product Restriction** (optional): Limit the code to specific products. * **Subscription Cycle Limit** (optional, under **Advanced**): Number of billing cycles the discount applies to. Leave empty for indefinite. A renewal that the discount makes free still uses up a cycle, so a 100% code with a cycle limit lapses, and the subscription then bills the full price. * **Preserve on Plan Change** (optional): Keep the discount active when a subscription changes plans (`preserve_on_plan_change`). * **Metadata** (optional): Attach custom key–value pairs for internal tracking. * **Require a minimum order value** (optional, under **Advanced**): Minimum cart subtotal (per currency) for the code to apply. > [!NOTE] > > When a code has a usage limit, an unpaid payment that uses the code holds one redemption. The hold counts toward both limits until the payment succeeds, fails, or is cancelled, or until its payment session expires. A failed, cancelled, or expired payment releases the redemption. So when the last redemption is held by an unpaid payment, a new payment with the code fails the usage limit check until that payment closes. The form shows a running **Summary** of the code you're building in a side panel. Switch to **Preview** to see how the discount appears at checkout: ![New Discount Code form with the Summary and Preview side panel beside the discount details](https://mintcdn.com/dodopayments/28D42lhMYyiRjtpN/images/discount-codes/discount-form-summary.png?fit=max\&auto=format\&n=28D42lhMYyiRjtpN\&q=85\&s=1f2c1d04fbbbac53f67d789d81e0a382) Further down the form — eligibility, restrictions, and advanced options: ![Eligibility, restrictions, and advanced options for a discount code](https://mintcdn.com/dodopayments/Rh05LkBeJE32G3qq/images/discount-codes/discount-create-eligibility.png?fit=max\&auto=format\&n=Rh05LkBeJE32G3qq\&q=85\&s=26e5e6971ac541336c16cec478672a0d) > [!TIP] > > Use cycle limits for introductory pricing on subscriptions (e.g., "50% off for 3 months"). > [!NOTE] > > A percentage `amount` is expressed in **basis points** over the API — `1500` means 15%. A flat `amount` is a money value and is denominated by the code's currency options. ## Discount Types | Type | API value | Behavior | | - | - | - | | Percentage | `percentage` | Reduces the price by a percent. Optionally capped per currency with a maximum discount. | | Amount | `flat` | Deducts a fixed amount. The deduction is pooled across the whole cart rather than applied per line item. | Both types can be stacked in the same `discount_codes` array and are applied in array order. ![Discount code editor with the Amount type selected, showing a flat 500 INR deduction](https://mintcdn.com/dodopayments/Rh05LkBeJE32G3qq/images/discount-codes/discount-flat-discount-option.png?fit=max\&auto=format\&n=Rh05LkBeJE32G3qq\&q=85\&s=38ce7f39a1ccbd26c61718f685fc4e71) ## Customer Eligibility Set `customer_eligibility` to control who may redeem a code: | Value | Who can redeem | | - | - | | `any` | Any customer. This is the default. | | `first_time` | Customers who have not purchased from you before. | | `existing` | Customers who have purchased from you before. | | `specific` | Only customers you attach to the code's allow list. | ![Customer eligibility dropdown showing Any, First-time, Existing, and Specific customer options](https://mintcdn.com/dodopayments/Rh05LkBeJE32G3qq/images/discount-codes/discount-restriction.png?fit=max\&auto=format\&n=Rh05LkBeJE32G3qq\&q=85\&s=3c01240807a7ca2f13b33a9f4cf4ce43) > [!WARNING] > > A `specific` code starts with **zero** eligible customers and rejects every redemption until you attach customers to it. Attach them in the dashboard, or with the discount customers API. Pair eligibility with **Per-Customer Usage Limit** to cap how often each individual customer can redeem the code, independently of the overall usage limit. ## Per-Currency Options When you sell in multiple currencies, set per-currency behavior for each code. Under **Currency options**, each entry specifies: * **Amount** — for an Amount discount, the flat deduction in that currency; for a Percentage discount, the maximum discount cap. Maps to `max_amount_possible` in the API. * **Default** — mark one currency as the default. Unconfigured currencies convert from this default. Set the per-currency minimum separately under **Require a minimum order value** in **Advanced**: * **Minimum subtotal** — the code applies only when the cart reaches this subtotal in that currency. `0` means no minimum. ![Currency options panel with per-currency amount and minimum subtotal for INR and USD](https://mintcdn.com/dodopayments/Rh05LkBeJE32G3qq/images/discount-codes/discount-currency-options.png?fit=max\&auto=format\&n=Rh05LkBeJE32G3qq\&q=85\&s=8e4d0db1a3cfdd256d285a576c9eed34) Amount discounts require at least one currency option with a resolvable default, since a flat deduction has no meaning without a currency. Percentage discounts don't require currency options. > [!NOTE] > > The minimum subtotal is always measured against the cart's original prices, not the running total after earlier discounts in the stack. Stacking order never changes whether a minimum is met. > > For a subscription, the minimum is checked once against the product and its add-ons together. For example, a \$0 product with a \$5 add-on meets a \$4 minimum. An Amount (`flat`) code still applies only to the subscription product, not to its add-ons. ## Checkout Experience Customers enter discount codes in the checkout field. Eligible codes are applied immediately and totals update. ![Checkout page showing a discount applied to the order total](https://mintcdn.com/dodopayments/Rh05LkBeJE32G3qq/images/discount-codes/discount-on-checkout.png?fit=max\&auto=format\&n=Rh05LkBeJE32G3qq\&q=85\&s=ac92cb27be2e2e7dd5364f941e709966) > [!NOTE] > > In Checkout Sessions, pass `discount_codes` (an array) to pre-apply one or more codes. The discount input field is shown by default. Set `feature_flags.allow_discount_code` to `false` to hide it. Pre-applied codes still apply when the field is hidden, so the customer can't change them. Codes are applied in array order, up to a maximum of 20. ## Stacking Discount Codes Checkout sessions, payments, and subscriptions accept up to 20 stacked codes via the `discount_codes` array. Codes are applied in array order: the first eligible code reduces the starting price, the next reduces the already-discounted price, and so on. When [Purchasing Power Parity](/features/purchasing-power-parity) is enabled, the starting price is the PPP-adjusted amount. The response includes `discount_ids` (on payments/subscriptions) and `discounts` (richer per-discount detail, including position and remaining subscription cycles). ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_abc', quantity: 1 }], discount_codes: ['WELCOME10', 'BLACKFRIDAY20'], // applied in this order customer: { email: 'user@example.com' }, return_url: 'https://yoursite.com/return' }); ``` > [!NOTE] > > The singular `discount_code` field is deprecated but fully supported for backward compatibility. It cannot be combined with `discount_codes` in the same request. Migrate to `discount_codes` (the array form) to take advantage of stacking and the richer response. > [!NOTE] > > On a subscription price with [Card-Optional at Zero Price](/features/subscription#card-optional-at-zero-price) enabled, a stack of codes that reduces the amount due today all the way to `0` skips the card requirement too — the customer checks out with no payment method on file, the same as a native `0` price. ## API Management > [accordion] Create discounts > > Create discount codes programmatically with type and amount. > > > [card] [API Reference](/api-reference/discounts/create-discount) > > > > View the create discount API. > [accordion] List and retrieve > > List all discounts or retrieve details for management and auditing. > > > [card] [API Reference](/api-reference/discounts/list-discounts) > > > > Browse listing and retrieval APIs. > [accordion] Get discount by code > > Look up a discount using its human-readable code (e.g., "SAVE20") instead of the internal ID. > > > [card] [API Reference](/api-reference/discounts/get-discount-by-code) > > > > Retrieve discount by code name. > [accordion] Update discounts > > Modify discount configuration such as amount, expiration, or restrictions. > > > [card] [API Reference](/api-reference/discounts/update-discount) > > > > Learn how to update discount details. > [accordion] Retrieve a discount > > Fetch a discount by its ID to inspect its status, usage count, and restrictions before applying it. > > > [card] [API Reference](/api-reference/discounts/validate-discount) > > > > Get a discount by ID. > [accordion] Delete discounts > > Deactivate or remove discounts that are no longer needed. > > > [card] [API Reference](/api-reference/discounts/delete-discount) > > > > Delete a discount. > [accordion] Manage the customer allow list > > For a discount with `customer_eligibility` set to `specific`, manage the customers that may redeem it: > > * `GET /discounts/{discount_id}/customers` — list the attached customers (paginated, up to 100 per page). > * `POST /discounts/{discount_id}/customers` — attach customers by ID. The call is idempotent and accepts up to 1000 IDs, all of which must already exist in your business. The response echoes only the IDs submitted in that request, so list the endpoint to read the full allow list. > * `DELETE /discounts/{discount_id}/customers/{customer_id}` — detach a single customer. ## Common Use Cases * **Intro offers**: Limited‑time launch promotions for new products * **Bulk or B2B**: Contracted discounts for select product sets * **Retention plays**: Win‑back codes in churn‑prevention workflows * **Seasonal campaigns**: Holiday or event‑based promotions ## Integration Examples ### Create a Discount with Metadata Attach custom key–value pairs for internal tracking. ```typescript theme={null} const discount = await client.discounts.create({ type: 'percentage', amount: 1500, // 15% code: 'SUMMER2025', metadata: { campaign: 'summer_promo', source: 'email_blast' } }); ``` > [!TIP] > > Use metadata to tag discounts by campaign, source, or internal reference ID so you can reconcile usage and measure ROI later. ### Apply Discounts in Checkout Sessions Pre‑apply one or more stacked discounts and show the code input UI. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_abc', quantity: 1 } ], discount_codes: ['BLACKFRIDAY2024', 'NEWUSER5'], // stacked in array order customer: { email: 'user@example.com', name: 'Jane Doe' }, return_url: 'https://yoursite.com/return' }); ``` ### Apply Discounts During Plan Changes Offer promotional pricing when customers upgrade or downgrade their subscription. ```typescript theme={null} await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_pro', quantity: 1, proration_billing_mode: 'prorated_immediately', discount_codes: ['UPGRADE20'] }); ``` The `discount_codes` parameter controls how discounts are handled: | Value | Behavior | | - | - | | Not provided (`undefined` / `null`) | Existing discounts with `preserve_on_plan_change=true` are preserved if applicable to the new product. | | `[]` (empty array) | All existing discounts are removed. | | `['CODE_A', 'CODE_B', ...]` | Replaces existing discounts with this stacked set, applied in array order. | > [!NOTE] > > Read all applied discounts from the subscription's `discounts` array in the response. Each entry includes `discount_id`, `position`, `cycles_remaining`, and the original code. ### Hide the Discount Code Field The discount input is shown by default. Set `allow_discount_code` to `false` to hide it. To lock in a discount, pass the codes in `discount_codes` as well: they still apply, and the customer can't remove or change them. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_abc', quantity: 1 }], discount_codes: ['LAUNCH20'], // optional: applied, and the customer can't change it feature_flags: { allow_discount_code: false }, return_url: 'https://yoursite.com/return' }); ``` ## Best Practices * **Name clearly**: Use recognizable codes that match campaign names. * **Time-box**: Add expirations to drive urgency and prevent misuse. * **Scope wisely**: Limit to specific products to avoid margin leakage. * **Validate early**: Check code applicability before confirming checkout. * **Monitor impact**: Track usage and conversion by campaign. # Customer Email Logs Source: https://docs.dodopayments.com/features/email-logs See every transactional email Dodo Payments sent to a customer, check whether it arrived, read the email exactly as it was sent, and send it again. > [card] [List Customer Emails](/api-reference/customers/list-customer-emails) > > Read a customer's sent emails and their delivery outcome. > [card] [Get Email Content](/api-reference/customers/get-customer-email-body) > > Read one email exactly as it was sent. ## Overview Dodo Payments sends transactional email to your customers on your behalf: receipts, refund notices, subscription notices, dunning and recovery emails, entitlement grants, and Customer Portal login links. The **Sent Emails** tab on a customer records each one. For every email, you see what was sent, how far it got, and why it did not arrive when it failed. You can open the email your customer received, and you can send it again. ![The Sent Emails tab on a customer, listing each email with its delivery status](https://mintcdn.com/dodopayments/9G2eOufWVa-OvQvG/images/email-logs/sent-emails-tab.png?fit=max\&auto=format\&n=9G2eOufWVa-OvQvG\&q=85\&s=6c7fa235800cee5c32eb286312f2a52b) > [!NOTE] > > Emails are kept for **180 days**. Delivery status comes from the email provider and typically updates within seconds of each delivery event. ## Viewing a Customer's Emails **1. Open the Customer** Go to **Sales → Customers** in the dashboard and select the customer. **2. Open the Sent Emails Tab** The tab lists every email sent to this customer in the last 180 days, newest first. **3. Read a Row** Each row shows the subject, with the sender and the recipient address below it. The other columns show the **Category**, the **Date & Time**, the **Delivery Status**, and the **Actions** you can take. The category is one of **Payments**, **Refunds**, **Subscriptions**, **Dunning & Recovery**, **Entitlements**, or **Auth**. Customer Portal login emails belong to **Auth**. ## Delivery Status Each email has one of five statuses. The API returns the status value, and the dashboard shows its label: | Status | Dashboard label | Meaning | | - | - | - | | `sent` | **Sent** | Dodo Payments handed the email to the provider. It is on its way, or the receiving server has not answered yet. | | `delivered` | **Delivered** | The receiving mail server accepted the email. | | `failed` | **Failed** | The email did not arrive. A failure reason is shown. | | `complained` | **Marked as spam** | The recipient marked the email as spam. | | `blocked` | **Not sent** | Nothing was sent, because the weekly test-mode allowance is spent. | ### Failure Reasons When an email does not arrive, the row carries a reason so you know whether to act. Point at the status on the row to read it. The API returns the same reason in `failure_reason` and a stable code in `failure_code`: | Reason | `failure_code` | What it means | What to do | | - | - | - | - | | Mailbox does not exist | `mailbox_not_found` | The address does not exist. | Correct the customer's email address. | | Address rejected by the mail server | `address_rejected` | The receiving server refused the address. | Use a different address. | | Address blocked after earlier failures | `address_suppressed` | The provider suppressed this address after an earlier hard bounce or complaint. | Use a different address. | | Mailbox is full | `mailbox_full` | The recipient's mailbox is out of space. | Send again later. | | Temporary delivery failure | `temporary_failure` | A transient problem at the receiving server. | Send again later. | | Message rejected as too large | `message_too_large` | The receiving server refused the size. | Contact support. | | Recipient marked the email as spam | `marked_as_spam` | The recipient reported the email. | Do not send it again. | | Email could not be sent | `send_failed` | The provider refused the send, or the failure matches no other code. | Send again. | | Not sent: the test-mode email allowance for this week is spent | `test_mode_quota_spent` | The weekly [test-mode allowance](#test-mode) is spent. | Wait for the allowance to reset. | Five of these reasons need a different address on a resend, because the same address would fail again: mailbox does not exist, address rejected, address blocked after earlier failures, message rejected as too large, and recipient marked the email as spam. ## Reading an Email To read an email, select **Resend** on its row, or **Retry** on a failed row. The panel that opens shows the stored copy under **Email Preview**, exactly as it was sent. Recovery and dunning emails that you wrote carry a **Written by you** label. ![The stored email content, shown as the customer received it](https://mintcdn.com/dodopayments/9G2eOufWVa-OvQvG/images/email-logs/email-preview.png?fit=max\&auto=format\&n=9G2eOufWVa-OvQvG\&q=85\&s=b0d00b4b6fe62c6ace0b8a2b4419619b) Some emails have no content to show: * **Customer Portal login emails.** They carry a live login link, so the content is never displayed. * **Blocked emails.** They never reached the provider, so no copy exists. * **Emails that could not be handed to the provider.** No copy was stored. * **Emails older than 180 days.** The provider clears the content at that point. ## Sending an Email Again To send an email again, select **Resend** on its row, or **Retry** on a failed row, and confirm in the panel. The button shows how many resends the email has left. Dodo Payments rebuilds the email from the original event, not from the stored copy, so a receipt shows the current state of the payment. The email keeps the date of the original event. ![The resend control on an email row, with the option to send to a different address](https://mintcdn.com/dodopayments/9G2eOufWVa-OvQvG/images/email-logs/resend-email.png?fit=max\&auto=format\&n=9G2eOufWVa-OvQvG\&q=85\&s=8751c05df35b14f116c8d487eaae7b70) The **To** field in the panel holds the original address. To send the email elsewhere, change it. After a permanent failure, the **To** field starts empty and you must enter a different address, because the original one would fail again. > [!WARNING] > > A resend is a new email. The customer receives another copy, and the resend appears as its own row in the tab. ### Limits These limits apply to every resend: * Each email may be sent again **three times**. * Resends of one email to the same address wait between attempts: five minutes after the latest send before the first resend, ten before the second, and fifteen before the third. * A resend to any address waits until five minutes have passed since that address last received an email from you. * A send that never reached the provider does not count against the three. It still adds to the wait. * Resend is available in the dashboard only. The API is read-only. ### When Resend Is Not Available The dashboard does not offer a resend, or refuses it, in these cases: | Case | Reason | | - | - | | The recipient marked the email as spam | The recipient asked for these emails to stop. | | The address is suppressed | The provider accepts a send to that address and then drops it. Enter a different address. | | A later send of the same email already went out | This row is history, marked **Sent on a later attempt**. Sending it again would deliver a second copy. | | The customer is blocked | A [blocked customer](/features/customer-blocklist) receives no further email from you. | | The three resends are used | The limit is per email. | | The original data is gone | Dodo Payments cannot rebuild the email. | | Your team role is **Viewer** | Viewers see no resend action on the row. | | **Test Mode Emails** is off, in test mode | Test-mode customer emails are turned off for your business. See [Test Mode](#test-mode). | > [!NOTE] > > A Customer Portal login email always goes to the address that asked for it, and each resend creates a fresh login link. ## Test Mode Test mode sends real email, so it carries an allowance: **100 emails per business per week**. Resends draw from the same allowance. Each test-mode email goes to the real recipient, with `[TEST MODE]` at the start of the subject. To stop test-mode customer emails, turn off **Test Mode Emails** in **Settings → Communication → Email** (see [Test Mode Emails](/features/communication-preferences#test-mode-emails)). While it is off, no customer email is sent in test mode, no row is added to the tab, no allowance is spent, and the dashboard refuses a resend. Live mode emails are not affected. When the allowance is spent, nothing more is sent in test mode that week. The first email refused that week is recorded as one `blocked` row, which reads "Not sent: the test-mode email allowance for this week is spent". Later refusals in the same week add no rows. The allowance resets at the start of each week, on Monday. Live mode has no such limit. > [!NOTE] > > Customer Portal login emails never send in test mode, and they do not spend the allowance. ## Reading Emails Through the API The list and the content are also available with your API key, so you can show delivery state in your own support tools. The list returns 10 emails per page by default. Set `page_size` to return up to 100, and `page_number` to page through, starting at 0. ```bash cURL theme={null} curl "https://live.dodopayments.com/customers/cus_123/emails?page_size=10" \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" ``` ```typescript Node.js expandable theme={null} const customerId = 'cus_123'; // the customer whose emails you want to read const res = await fetch( `https://live.dodopayments.com/customers/${customerId}/emails?page_size=10`, { headers: { Authorization: `Bearer ${process.env.DODO_PAYMENTS_API_KEY}` } }, ); const { items, total_count } = await res.json(); ``` ```python Python expandable theme={null} import os, requests customer_id = "cus_123" # the customer whose emails you want to read res = requests.get( f"https://live.dodopayments.com/customers/{customer_id}/emails", params={"page_size": 10}, headers={"Authorization": f"Bearer {os.environ['DODO_PAYMENTS_API_KEY']}"}, ) items = res.json()["items"] ``` The TypeScript and Python SDKs wrap both endpoints as `client.customers.emails.list()` and `client.customers.emails.retrieveBody()` (`retrieve_body()` in Python). Each item carries its `email_log_id`, which you pass to the content endpoint, and its `status`. It also carries the `failure_code` and `failure_reason` when the send failed, and `has_preview` to say whether stored content exists. The content endpoint returns `422` when an email has no content to show. Each item also carries a `policies` object that states what you may do with the row: | Field | Meaning | | - | - | | `resend_allowed` | The email was delivered, and you may send it again. | | `retry_allowed` | The send failed, and you may attempt it again. | | `resends_remaining` | How many resends the email has left. | | `requires_different_address` | The same address would fail again, so you must supply another one. | | `superseded` | A later send of the same email replaced this row. | Read `policies` rather than deriving eligibility yourself. The server applies the rules above. > [card] [Customer Management](/features/customers) > > Manage customers, purchase history, and self-service access. > [card] [Communication Preferences](/features/communication-preferences) > > Choose which emails Dodo Payments sends on your behalf. # Discord Entitlement Source: https://docs.dodopayments.com/features/entitlements/discord Add paying customers to your Discord server with an optional role, and remove them automatically when their access ends. > [!NOTE] > > The Discord entitlement adds a paying customer to your Discord server and can assign them a role. The customer connects their Discord account after their subscription becomes active or their one-time payment succeeds. When the grant is revoked, for example on cancellation or refund, Dodo Payments removes the role and removes the customer from the server. ## What Gets Delivered * The customer connects their Discord account from the Customer Portal. The payment confirmation email marks the entitlement **Action Required** and links to the portal. * After they authorize, the Dodo Payments bot adds them to your server, or finds their existing membership, and assigns the role you configured. * If you don't pick a role, the customer gets server membership only. Use it for paid communities, supporter perks, and tiered access channels. ## Connect Discord **1. Open Entitlements** In the Dodo Payments dashboard, go to **Entitlements** and click **+** to start a new entitlement. **2. Pick Discord** Choose **Discord Access** as the integration. If Discord isn't connected for your business yet, click **Connect Discord**. ![New entitlement panel prompting the merchant to connect Discord](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/discord/connect-prompt.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=8a34c436dd7510942db2a9221f623938) Connect Discord prompt before the OAuth handoff. Discord opens in a new tab. Sign in, pick the server you want to gate, and approve the bot's permissions on that server: **Manage Roles**, **Kick Members**, and **Create Invite**. ![Discord OAuth screen asking which server to add the Dodo Payments bot to](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/discord/oauth-add-bot.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=b57bf306fa15aa3f49b528f803cc625e) Discord OAuth: pick the server to add the bot to. ![Discord bot permission confirmation screen](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/discord/oauth-permissions.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=438c0b04177e3a4863fb90986f5b95e0) Discord OAuth: confirm the bot's permissions on the server. When Discord redirects back, a confirmation page shows that the server is connected. ![Discord Access connected successfully confirmation page](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/discord/connected.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=bd1cbb3f9960e4eb1881d7a818dc6f16) Server connected. Return to the Dodo Payments dashboard to continue. **3. Pick a Server and Role** Back in the dashboard, select the **Server** you connected. To assign a role on delivery, select it under **Role**. To grant server membership only, leave **Role** set to **No specific role**. Enter a **Name** for the entitlement and click **Create Entitlement**. ![New Entitlement - Discord Access form with connected server, server picker, role dropdown, and name field](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/discord/create.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=79e95041881d2925e58fc752280d508e) **4. Attach It to a Product** The entitlement is saved and available to attach to any product. See [Attach Entitlements to Products](/features/entitlements/introduction#attach-entitlements-to-products). ## Customer Flow 1. The customer completes checkout. 2. Dodo Payments creates a grant in `Pending` status. Dodo Payments tries to create a Discord authorization URL right away and stores it in `oauth_url`. If that fails, `oauth_url` stays `null` until the customer starts the accept flow. 3. The payment confirmation email lists the entitlement as **Action Required** and links to the Customer Portal. In the portal, the customer clicks **Connect** on the entitlement. 4. The customer authorizes Dodo Payments on Discord. The bot adds them to the server and assigns the configured role, and the grant moves to `Delivered`. 5. When the grant is revoked (the subscription is cancelled, paused, put on hold, or expires, the one-time payment is refunded, or you revoke the grant), the bot removes the role and removes the customer from the server. The grant moves to `Revoked`. An authorization link expires 30 minutes after it's generated. If the customer returns to the Customer Portal after that, Dodo Payments generates a new link. If a customer leaves your server on their own, Dodo Payments revokes their grant with `revocation_reason: platform_external`. > [!TIP] > > Place the Dodo Payments bot's role **above** the role you grant. Discord doesn't let a bot assign a role at or above its own highest role. Managed roles, such as bot and integration roles, can't be assigned. ## Required Configuration | Field | Required | Description | | - | - | - | | `guild_id` | Yes | The Discord server (guild) ID. The dashboard's server picker fills this in for you. | | `role_id` | No | The role to assign on delivery. Omit it, or pass `null`, for server-membership-only access. | ## Create via API ```typescript TypeScript expandable theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], environment: 'test_mode', }); const entitlement = await client.entitlements.create({ name: 'Patrons Discord Role', integration_type: 'discord', integration_config: { guild_id: '123456789012345678', role_id: '987654321098765432', }, }); ``` ```python Python expandable theme={null} import os from dodopayments import DodoPayments client = DodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), environment="test_mode", ) entitlement = client.entitlements.create( name="Patrons Discord Role", integration_type="discord", integration_config={ "guild_id": "123456789012345678", "role_id": "987654321098765432", }, ) ``` ```go Go expandable theme={null} // client is a *dodopayments.Client, for example from // dodopayments.NewClient(option.WithEnvironmentTestMode()); ctx is a context.Context. client.Entitlements.New(ctx, dodopayments.EntitlementNewParams{ Name: dodopayments.F("Patrons Discord Role"), IntegrationType: dodopayments.F(dodopayments.EntitlementIntegrationTypeDiscord), IntegrationConfig: dodopayments.F[dodopayments.IntegrationConfigUnionParam]( dodopayments.IntegrationConfigDiscordConfigParam{ GuildID: dodopayments.F("123456789012345678"), RoleID: dodopayments.F("987654321098765432"), }, ), }) ``` ## Webhooks Subscribe to the [`entitlement_grant.*` webhook events](/developer-resources/webhooks/intents/entitlement-grant) to track Discord grants: * `entitlement_grant.created` fires with `status: "Pending"`. `oauth_url` may already hold the authorization URL. If it is `null`, it is populated once the customer starts the accept flow from the Customer Portal. * `entitlement_grant.delivered` fires once the customer joins the server and the role is assigned. * `entitlement_grant.revoked` fires when the role is removed and the customer is removed from the server. ## Troubleshooting > [accordion] Customer never sees the role assigned > > The grant stays `Pending` until the customer completes the Discord authorization. Open the entitlement in the dashboard and check the customer's grant. If it's still `Pending`, ask the customer to open the Customer Portal and click **Connect** on the Discord entitlement. > [accordion] Grant moves to failed with permission errors > > Make sure the Dodo Payments bot is still in the server, has the **Manage Roles** permission, and sits above the role being assigned. If the bot is removed from the server, Dodo Payments revokes the server's pending and delivered grants. Re-saving the entitlement checks only its settings, not the bot's permissions. After you fix the permissions, ask the customer to open the Customer Portal and click **Connect** on the Discord entitlement to retry the grant. > [accordion] Customer cancelled but still has the role > > Revocation removes the role and removes the customer from the server. If the grant shows `Revoked` but the customer is still in the server, confirm the bot still has the **Manage Roles** and **Kick Members** permissions and sits above the role. If the customer's Discord app still shows the role, ask them to refresh it. The server-side state is the source of truth. # Feature Flag Entitlement Source: https://docs.dodopayments.com/features/entitlements/feature-flags Gate features in your own application off a purchase. Feature flag entitlements deliver a boolean capability on payment and revoke it automatically on cancellation. > [!NOTE] > > A feature flag entitlement turns Dodo Payments into a billing-aware feature flag store. Attach a flag such as `advanced_reports` to a product, and every paying customer gets a grant that your application checks through the API or keeps in sync with webhooks. There's no external platform, OAuth step, or delivery step: the grant itself is the capability. ## What Gets Delivered Nothing leaves Dodo Payments. The grant **is** the deliverable: * On purchase, Dodo Payments creates the grant directly in `Delivered`. It never enters `Pending`, needs no customer action, and has no delivery step that can fail. * The grant carries a typed `feature` payload: `{ "feature_type": "boolean", "feature_id": "advanced_reports" }`. Your application reads `feature_id` to decide what to unlock. * Cancellation, refund, or a manual revoke moves the grant to `Revoked`, and the flag disappears from the customer's delivered grants. Common uses include plan-based feature gating (Pro unlocks analytics), add-on capabilities (an "API access" upgrade), and early-access programs sold as one-time purchases. > [!NOTE] > > `feature_id` is an identifier you choose, and it isn't unique across entitlements. Two entitlements can confer the same `feature_id`, for example a monthly and a yearly Pro plan that both grant `advanced_reports`. ## Create a Feature Flag **1. Open Entitlements** In the Dodo Payments dashboard, go to **Entitlements** and click **+** to start a new entitlement, then choose **Feature Flags**. **2. Name the Flag** Enter a **Display Name** for your dashboard and reports, and a **Description** so your team knows what the flag controls. The **Feature ID** is what your application checks. The dashboard fills it in from the display name (for example, "API access" becomes `api_access`), and you can edit it. It can't contain spaces. ![New Feature Flag form with display name, feature ID, description, and metadata key-value entries](https://mintcdn.com/dodopayments/oS2MTbJuY6MeBjjs/images/entitlements/feature-flags/create.png?fit=max\&auto=format\&n=oS2MTbJuY6MeBjjs\&q=85\&s=08d8fc2cfee102ff08fd150c76b5fcf9) Creating a feature flag. The Feature ID is what your application checks; Meta Data attaches limits alongside the flag. **3. Add Metadata (Optional)** Turn on **Meta Data** to attach key-value configuration, such as limits, tier names, or quotas, that your application receives alongside the flag. Click **Add Entry** for each pair. See [Attach limits with metadata](#attach-limits-with-metadata). **4. Confirm** Click **Confirm**. The flag appears in your entitlements list, ready to attach to products. ![Entitlements dashboard showing the Advanced Reports feature flag with its grant activity pane](https://mintcdn.com/dodopayments/oS2MTbJuY6MeBjjs/images/entitlements/feature-flags/list.png?fit=max\&auto=format\&n=oS2MTbJuY6MeBjjs\&q=85\&s=02eedcbbf7ece9f67d375c984c5515b9) The created feature flag. The right pane tracks every customer grant issued from it. ## Attach to a Product Open a product, or create one, and find the **Entitlements** card. Click **+** to attach existing entitlements, select your feature flag, and click **Done**. ![Entitlements attach panel with the Advanced Reports feature flag selected](https://mintcdn.com/dodopayments/oS2MTbJuY6MeBjjs/images/entitlements/feature-flags/attach-picker.png?fit=max\&auto=format\&n=oS2MTbJuY6MeBjjs\&q=85\&s=da2137873e285cc6ce0ce234fe899ed3) Attaching the feature flag to a product. One product can deliver multiple entitlements. The attached flag shows on the product form, and the checkout preview lists it under **Includes**. ![Product form with the Advanced Reports feature flag attached in the Entitlements card](https://mintcdn.com/dodopayments/oS2MTbJuY6MeBjjs/images/entitlements/feature-flags/attach-to-product.png?fit=max\&auto=format\&n=oS2MTbJuY6MeBjjs\&q=85\&s=3556181389997edddde9c396d0ce408d) The product now includes the feature flag. Every successful purchase or active subscription grants it. ## Required Configuration | Field | Required | Description | | - | - | - | | `feature_id` | Yes | The identifier your application checks, for example `advanced_reports`. Not unique across entitlements. | | `feature_type` | Yes | The type of capability conferred. `boolean` is the only supported value. | ### Create via API ```typescript TypeScript expandable theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], environment: 'test_mode', }); const entitlement = await client.entitlements.create({ name: 'Advanced Reports', integration_type: 'feature_flag', integration_config: { feature_type: 'boolean', feature_id: 'advanced_reports', }, metadata: { tier: 'pro', monthly_report_limit: 100, }, }); ``` ```python Python expandable theme={null} import os from dodopayments import DodoPayments client = DodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), environment="test_mode", ) entitlement = client.entitlements.create( name="Advanced Reports", integration_type="feature_flag", integration_config={ "feature_type": "boolean", "feature_id": "advanced_reports", }, metadata={ "tier": "pro", "monthly_report_limit": 100, }, ) ``` ```go Go expandable theme={null} // client is a *dodopayments.Client, for example from // dodopayments.NewClient(option.WithEnvironmentTestMode()); ctx is a context.Context. client.Entitlements.New(ctx, dodopayments.EntitlementNewParams{ Name: dodopayments.F("Advanced Reports"), IntegrationType: dodopayments.F(dodopayments.EntitlementIntegrationTypeFeatureFlag), IntegrationConfig: dodopayments.F[dodopayments.IntegrationConfigUnionParam]( dodopayments.IntegrationConfigFeatureFlagConfigParam{ FeatureType: dodopayments.F(dodopayments.FeatureTypeBoolean), FeatureID: dodopayments.F("advanced_reports"), }, ), }) ``` *** ## Attach Limits with Metadata A boolean flag answers "Does this customer have the feature?". Metadata answers "With what configuration?". Entitlement metadata accepts string, integer, number, and boolean values. Every grant takes a **frozen snapshot** of the entitlement's metadata when the grant is created. The snapshot is what makes metadata safe to use for plan limits: * Editing the entitlement's metadata later affects only **future** grants. Customers keep the limits they purchased under. * Each grant returns its snapshot in its `metadata` field, so one API call gives you both the flag and its configuration. For example, an `advanced_reports` flag with `{ "tier": "pro", "monthly_report_limit": 100 }` lets your application unlock the dashboard *and* enforce the 100-report quota without a second lookup. If you later raise the limit to 250, existing customers stay at 100 until they receive a new grant, for example after a plan change. > [!TIP] > > Use metadata for limits and configuration, and use `feature_id` only for identity. Encoding a limit in the ID (`advanced_reports_100`) forces a new flag for every limit change and breaks your application's checks. *** ## Check a Customer's Features To build the set of features a customer has, list their delivered feature flag grants. The endpoint returns one row per grant across all entitlements, and you can filter it by `integration_type` and `status`. These examples use the `client` from [Create via API](#create-via-api). ```typescript TypeScript expandable theme={null} const features = new Map>(); for await (const grant of client.customers.listEntitlementGrants('cus_abc123', { integration_type: 'feature_flag', status: 'Delivered', })) { if (grant.feature) { features.set(grant.feature.feature_id, grant.metadata ?? {}); } } if (features.has('advanced_reports')) { const limit = features.get('advanced_reports')?.monthly_report_limit; // unlock the dashboard, enforce the limit } ``` ```python Python expandable theme={null} page = client.customers.list_entitlement_grants( customer_id="cus_abc123", integration_type="feature_flag", status="Delivered", ) # Iterating the page fetches every page of results. features = { grant.feature.feature_id: grant.metadata for grant in page if grant.feature } if "advanced_reports" in features: limit = features["advanced_reports"].get("monthly_report_limit") ``` ```go Go expandable theme={null} iter := client.Customers.ListEntitlementGrantsAutoPaging( ctx, "cus_abc123", dodopayments.CustomerListEntitlementGrantsParams{ IntegrationType: dodopayments.F(dodopayments.CustomerListEntitlementGrantsParamsIntegrationTypeFeatureFlag), Status: dodopayments.F(dodopayments.CustomerListEntitlementGrantsParamsStatusDelivered), }, ) features := map[string]bool{} for iter.Next() { grant := iter.Current() if grant.Feature.FeatureID != "" { features[grant.Feature.FeatureID] = true } } if err := iter.Err(); err != nil { panic(err.Error()) } ``` > [!NOTE] > > The `feature` payload is populated only on `feature_flag` grants. It's `null` for every other integration type. See the [List Customer Grants](/api-reference/entitlements/list-customer-grants) API reference for the full response shape. Calling the API on every request adds latency to your hot path. Cache each customer's feature set with a short TTL (minutes, not hours), and invalidate the cache from your webhook handler when a grant changes state. Together, these keep checks fast and make revocations take effect on the next request. *** ## Lifecycle Feature flag grants follow the standard [grant lifecycle](/features/entitlements/introduction#how-grants-work) with one simplification: there's no delivery step, so grants never sit in `Pending` and never move to `Failed`. | Trigger | Effect | | - | - | | One-time payment succeeds / subscription becomes active | Grant created with `status: Delivered` and `delivered_at` set. | | Subscription put on hold, paused, cancelled, or expired | Grant revoked with the matching `revocation_reason`. | | Refund on a one-time payment | Grant revoked with `revocation_reason: refund`. | | Subscription recovers (for example, dunning succeeds) or is unpaused | The revoked grant is restored to `Delivered`, with the same grant `id` and the revocation fields cleared. | | Manual API revoke | Grant revoked with `revocation_reason: manual`. Not auto-restored on renewal. | Grants are idempotent per entitlement and customer. While a customer has a non-revoked grant for a flag, repeat purchases and renewals don't create duplicates. *** ## Webhooks To mirror flags into your own database instead of polling, subscribe to the [`entitlement_grant.*` events](/developer-resources/webhooks/intents/entitlement-grant): * `entitlement_grant.created` arrives already `Delivered`, with the `feature` payload. Enable the feature. * `entitlement_grant.delivered` fires when a previously revoked grant is restored. Enable the feature again. * `entitlement_grant.revoked` means access was withdrawn. Disable the feature, and check `revocation_reason` to choose your messaging. This Express handler verifies the webhook signature with the SDK, then stores the flag state: ```typescript TypeScript expandable theme={null} import express from 'express'; import DodoPayments from 'dodopayments'; // Reads DODO_PAYMENTS_API_KEY and DODO_PAYMENTS_WEBHOOK_KEY from the environment. const client = new DodoPayments({ environment: 'test_mode' }); const app = express(); app.post('/webhooks/dodo', express.raw({ type: 'application/json' }), async (req, res) => { let event: DodoPayments.UnwrapWebhookEvent; try { event = client.webhooks.unwrap(req.body.toString(), { headers: req.headers as Record, }); } catch { res.sendStatus(400); // invalid signature return; } const grant = 'feature' in event.data ? event.data : null; if (event.type.startsWith('entitlement_grant.') && grant?.feature) { const enabled = event.type !== 'entitlement_grant.revoked'; // db is your application's database client. await db.customerFeatures.upsert({ customerId: grant.customer_id, featureId: grant.feature.feature_id, enabled, config: grant.metadata ?? {}, }); } res.sendStatus(200); }); ``` Feature flags never fire `entitlement_grant.failed`, because delivery happens entirely inside Dodo Payments. *** ## Example: Pro Plan Unlocks Advanced Reports 1. **Create the flag.** Set `feature_id: advanced_reports` with metadata `{ "tier": "pro", "monthly_report_limit": 100 }`. 2. **Attach it** to your Pro Plan subscription product. 3. **A customer subscribes.** Dodo Payments creates a `Delivered` grant and fires `entitlement_grant.created`. Your webhook handler enables `advanced_reports` for the customer with a limit of 100. 4. **Your app gates the feature.** On dashboard load, check the cached feature set (or call `listEntitlementGrants`) and render the reports tab only when `advanced_reports` is present. 5. **The customer cancels.** Dodo Payments revokes the grant and fires `entitlement_grant.revoked`, and your handler disables the feature. If a subscription later recovers through dunning, `entitlement_grant.delivered` restores the feature with no code changes. *** ## Best Practices * **Use stable feature IDs in `snake_case`.** Your application code checks these strings, so renaming one is a breaking change on both sides. * **Use one flag per capability.** Prefer `advanced_reports` and `api_access` as two entitlements over a single `pro_bundle`, so revocation and plan combinations stay clean. * **Drive state from webhooks, and verify with the API.** Webhooks keep your database current. The list endpoint is the source of truth for reconciliation jobs and cache misses. * **Treat `Revoked` as immediate.** A revoked flag means the customer no longer pays for the feature. Gate on the next request, not the next session. * **Put limits in metadata, not in code.** Changing a quota then requires only an edit to the entitlement. New customers get the new value, and existing grants keep their purchased snapshot. # Framer Entitlement Source: https://docs.dodopayments.com/features/entitlements/framer Give paying customers the remix link of your Framer template, so they can remix it into their own Framer account after purchase. > [!NOTE] > > The Framer entitlement gives paying customers the remix link of a Framer template. You register the template's remix link in Dodo Payments and attach the entitlement to a product. Customers get the link in the Customer Portal and use it to remix the template into their own Framer account. ## What Gets Delivered * The remix link of the Framer template you registered. Every customer who buys the product receives the same link. * The customer opens the link from the Customer Portal and remixes the template into their own Framer workspace. * On cancellation or refund, the Customer Portal stops showing the link. The link itself keeps working in Framer, so anyone who saved it can still remix the template. Common uses include paid Framer landing-page templates, portfolio kits, and component libraries. ## Connect Framer Framer is connected implicitly the first time you create a template entitlement. There's no separate OAuth step. **1. Open Entitlements** In the Dodo Payments dashboard, go to **Entitlements** and click **+**. **2. Pick Framer** Choose **Framer Template** as the integration. **3. Grab the Remix Link from Framer** Open your Framer project. From the top-left menu, go to **File → Copy Remix Link**. This copies a public remix URL that lets anyone clone the project into their own Framer account. Dodo Payments shares this link with paying customers. ![Framer File menu with Copy Remix Link option highlighted](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/framer/copy-remix-link.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=a0e1e4d5c9cc0a88ca5dbf059a4d2329) Framer File menu: click Copy Remix Link to copy the template's remix URL. **4. Add the Template and Create the Entitlement** Back in the Dodo Payments dashboard, select the template under **Template**. To register a new template, click **+ Create new template**, enter a **Template name**, paste the link you copied into **Remix link** (it must be a `framer.com` URL), and click **Create template**. Enter a **Name** for the entitlement and click **Create Entitlement**. ![Framer template entitlement form with template picker and name field](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/framer/create.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=f3b5bfdb1092047e06f4eeba03d7bddf) Dodo Payments stores the registered template's ID as `framer_template_id` in the entitlement's `integration_config`, so you can reference it programmatically. ## Customer Flow 1. The customer completes checkout. 2. Dodo Payments creates a `Pending` grant and attaches the template's remix link to it. 3. The grant moves to `Delivered` once the remix link is attached. The payment confirmation email links to the Customer Portal, where the customer finds the link on the entitlement. 4. The customer opens the link, signs in to Framer, and remixes the template. 5. On revocation, the Customer Portal stops showing the link. Copies already remixed into the customer's Framer account remain, since Framer doesn't expose a way to revoke them. ## Required Configuration | Field | Required | Description | | - | - | - | | `framer_template_id` | Yes | The ID (a UUID) of the template you registered in the dashboard. | ## Create via API ```typescript TypeScript expandable theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], environment: 'test_mode', }); const entitlement = await client.entitlements.create({ name: 'Portfolio Kit', integration_type: 'framer', integration_config: { framer_template_id: '3f2b8c1e-7d4a-4e9b-a6c5-1d2e3f4a5b6c', }, }); ``` ```python Python expandable theme={null} import os from dodopayments import DodoPayments client = DodoPayments(bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), environment="test_mode") entitlement = client.entitlements.create( name="Portfolio Kit", integration_type="framer", integration_config={"framer_template_id": "3f2b8c1e-7d4a-4e9b-a6c5-1d2e3f4a5b6c"}, ) ``` ```go Go expandable theme={null} // client is a *dodopayments.Client, for example from // dodopayments.NewClient(option.WithEnvironmentTestMode()); ctx is a context.Context. client.Entitlements.New(ctx, dodopayments.EntitlementNewParams{ Name: dodopayments.F("Portfolio Kit"), IntegrationType: dodopayments.F(dodopayments.EntitlementIntegrationTypeFramer), IntegrationConfig: dodopayments.F[dodopayments.IntegrationConfigUnionParam]( dodopayments.IntegrationConfigFramerConfigParam{ FramerTemplateID: dodopayments.F("3f2b8c1e-7d4a-4e9b-a6c5-1d2e3f4a5b6c"), }, ), }) ``` ## Webhooks See [`entitlement_grant.*` webhook events](/developer-resources/webhooks/intents/entitlement-grant). Framer grants arrive `Pending` and transition to `Delivered` once the remix link is attached to the grant. ## Troubleshooting > [accordion] Customer's remix link doesn't work > > The remix link isn't single-use or tied to one customer. Every customer receives the link you registered, and can open it again from the Customer Portal while the grant is `Delivered`. If the link fails, open it yourself to confirm the remix link is still valid in Framer. > [accordion] Refunded customer still has a remixed copy > > This is expected. Framer treats a remix as the customer's own project once it's cloned. Dodo Payments stops showing the link in the Customer Portal but can't delete copies in the customer's account, and can't disable the remix link itself. # GitHub Entitlement Source: https://docs.dodopayments.com/features/entitlements/github Grant customers collaborator access to a private GitHub repository at the permission level you choose, and revoke it automatically on cancellation. > [!NOTE] > > The GitHub entitlement adds a paying customer as a collaborator on a private repository. You choose the permission level (`pull`, `push`, `triage`, `maintain`, or `admin`). Dodo Payments sends the collaborator invitation and removes the collaborator when the grant is revoked. ## What Gets Delivered * The customer connects their GitHub account from the Customer Portal. This links their GitHub account to the purchase. * Dodo Payments invites that account to your repository at the configured permission level. The customer gets access after they accept the invitation on GitHub. If the customer owns the repository, no invitation is needed. * Cancellation, refund, or a manual revoke removes the collaborator and cancels any pending invitation. Common uses include source-available products, paid templates, course code repositories, and gated client SDKs. ## Connect GitHub **1. Open Entitlements** In the Dodo Payments dashboard, go to **Entitlements** and click **+** to start a new entitlement. **2. Pick GitHub** Choose **GitHub Access** as the integration. If GitHub isn't connected yet, click **Connect GitHub**. ![New entitlement panel prompting the merchant to connect GitHub](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/github/connect-prompt.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=8a836c94099accdb2b3dc31c22d0e11b) Connect GitHub prompt before the install handoff. GitHub opens in a new tab. Sign in, then install the Dodo Payments GitHub App on the organization or user account that owns the repository. You can grant the app access to **All repositories** or **Only select repositories**. If you select repositories, include every repository you intend to gate. ![GitHub Install and Authorize page with All repositories and Only select repositories options](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/github/oauth-install.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=0788d3f6e9df8a087de824967f09c215) GitHub Install & Authorize page. Choose which repositories the app can manage. When GitHub redirects back, a confirmation page shows that the account is connected. ![GitHub Access connected successfully confirmation page](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/github/connected.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=ee3c87c3b3917f473ff3d376dfdc6494) Account connected. Return to the Dodo Payments dashboard to continue. **3. Pick a Repository and Permission** Back in the dashboard, select the **Repository** the entitlement grants access to, then select the **Permission** level. The repository picker lists only repositories the GitHub App can access. Enter a **Name** for the entitlement and click **Create Entitlement**. ![GitHub entitlement form with connected GitHub Access, repository selector, permission dropdown, and name field](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/github/create.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=722e925ec5158a5d16c58213132ccb9d) Creating a GitHub entitlement. Pick the repository and the permission you want customers to receive. **4. Attach It to a Product** Attach the entitlement to any product. Customers who buy that product receive a GitHub invitation after they connect their GitHub account. ## Permission Levels The entitlement uses GitHub's standard repository permissions: | Permission | Best for | | - | - | | `pull` | Read-only access. Customers can clone, fetch, and view the repository. | | `triage` | Read access plus the ability to manage issues and pull requests. | | `push` | Read and write access. Customers can push branches and open pull requests. | | `maintain` | Push access plus management of repository settings, excluding sensitive ones. | | `admin` | Full control of the repository. Use with caution. | > [!WARNING] > > Grant the **least privilege** that fits your use case. Most paid-content products need only `pull`. > [!NOTE] > > A repository owned by a personal GitHub account supports only `push` for collaborators. GitHub doesn't allow read-only access on these repositories. If you pick any other permission for a personal-account repository, creating or updating the entitlement fails with a `422` error. Use `push`, or move the repository to a GitHub organization to offer `pull`, `triage`, `maintain`, or `admin`. ## Customer Flow 1. The customer completes checkout. 2. Dodo Payments creates a grant in `Pending` status. Dodo Payments tries to create a GitHub authorization URL right away and stores it in `oauth_url`. If that fails, `oauth_url` stays `null` until the customer starts the accept flow. 3. The payment confirmation email lists the entitlement as **Action Required** and links to the Customer Portal. In the portal, the customer clicks **Connect** and authorizes with GitHub. An authorization link expires after 30 minutes, and the Customer Portal generates a new one when the customer returns. 4. Dodo Payments invites the customer's GitHub account to the repository at the configured permission. The grant moves to `Delivered` once the invitation is created. If GitHub rejects the invitation, the grant isn't delivered. 5. If the subscription is cancelled, the payment is refunded, or the grant is revoked, Dodo Payments removes the customer as a collaborator and cancels any pending invitation. ## Required Configuration | Field | Required | Description | | - | - | - | | `target_id` | Yes | The repository to invite the customer to, in `owner/repo` format. The dashboard's repository picker fills this in for you. | | `permission` | Yes | One of `pull`, `push`, `triage`, `maintain`, `admin`. A repository owned by a personal account accepts only `push`. | ## Create via API ```typescript TypeScript expandable theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], environment: 'test_mode', }); const entitlement = await client.entitlements.create({ name: 'Code Share Repository', integration_type: 'github', integration_config: { target_id: 'acme/private-sdk', permission: 'pull', }, }); ``` ```python Python expandable theme={null} import os from dodopayments import DodoPayments client = DodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), environment="test_mode", ) entitlement = client.entitlements.create( name="Code Share Repository", integration_type="github", integration_config={ "target_id": "acme/private-sdk", "permission": "pull", }, ) ``` ```go Go expandable theme={null} // client is a *dodopayments.Client, for example from // dodopayments.NewClient(option.WithEnvironmentTestMode()); ctx is a context.Context. client.Entitlements.New(ctx, dodopayments.EntitlementNewParams{ Name: dodopayments.F("Code Share Repository"), IntegrationType: dodopayments.F(dodopayments.EntitlementIntegrationTypeGitHub), IntegrationConfig: dodopayments.F[dodopayments.IntegrationConfigUnionParam]( dodopayments.IntegrationConfigGitHubConfigParam{ TargetID: dodopayments.F("acme/private-sdk"), Permission: dodopayments.F(dodopayments.GitHubPermissionPull), }, ), }) ``` ## Webhooks The standard [`entitlement_grant.*` webhook events](/developer-resources/webhooks/intents/entitlement-grant) cover the GitHub flow: * `entitlement_grant.created` fires with `status: "Pending"`. `oauth_url` may already hold the GitHub authorization URL. If it is `null`, it is populated once the customer starts the accept flow from the Customer Portal. * `entitlement_grant.delivered` fires once the collaborator invitation is created. * `entitlement_grant.revoked` fires when access is withdrawn. If you uninstall the GitHub App, Dodo Payments revokes that installation's pending and delivered grants with `revocation_reason: platform_external`. * `entitlement_grant.failed` fires with `error_code: "GRANT_ACCESS_FAILED"` if Dodo Payments can't add the customer to the repository, for example because the GitHub App lost access to it. ## Troubleshooting > [accordion] Repository picker is empty > > The Dodo Payments GitHub App must be installed on the organization or user that owns the repository. In the entitlement form, click **Disconnect** on the GitHub card, then click **Connect GitHub** to reinstall the app, and grant it access to the repositories you want to gate. > [accordion] Grant fails with a permission error > > The GitHub App's installation no longer has access to the repository, or the repository was renamed or transferred. Grant the app access to the repository again, and the next regrant succeeds. > [accordion] Customer hasn't accepted the invite > > Customers accept the GitHub invitation from their GitHub notifications or from the link in GitHub's invitation email. Until they accept, they're invited but can't clone the repository. The grant is still `Delivered` in Dodo Payments, because the invitation is what Dodo Payments issues. # Introduction Source: https://docs.dodopayments.com/features/entitlements/introduction Deliver license keys, downloadable files, feature flags, and access to Discord, GitHub, Telegram, Framer, and Notion automatically when customers pay. > [!NOTE] > > Entitlements turn a successful payment or active subscription into access: a license key in your customer's inbox, a feature flag your app checks, a Discord role, a GitHub repository, a Notion template, a Framer remix link, a Telegram chat invite, or a downloadable file bundle. Dodo Payments issues, tracks, and revokes that access automatically as the payment lifecycle changes. ![Entitlements dashboard with a list of entitlements on the left and grant activity on the right](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/list.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=12a326205f64d1e71485bce46114d296) The Entitlements dashboard. Each entitlement is a reusable template; the right pane shows individual customer grants. ## What Are Entitlements? An **entitlement** is a reusable definition of something you deliver to a customer, such as a Pro license key, a "Patrons" Discord role, access to your private GitHub repository, or a downloadable e-book bundle. You attach entitlements to products, and Dodo Payments delivers them when a customer pays. When a customer buys the product, Dodo Payments creates a **grant**: one customer's issuance of that entitlement. A grant has one of four statuses: `Pending` while delivery is in progress, `Delivered` once the customer has access, `Failed` if delivery couldn't complete, and `Revoked` when access is withdrawn. > [!TIP] > > Entitlements gate **fulfillment** (does the customer have access?). Credits gate **consumption** (how much of it can they use?). You can attach both to the same product. See [Credit-Based Billing](/features/credit-based-billing) for credits. ## Available Integrations Each entitlement delivers through one integration. Pick the integration that matches what you sell. > [card] [License Keys](/features/license-keys) > > Generate unique license keys with activation limits and expiry. Best for software, plugins, and CLIs. > [card] [Digital Files](/features/digital-product-delivery) > > Deliver downloadable files, such as e-books, templates, and media, with presigned download URLs and optional instructions. > [card] [Feature Flags](/features/entitlements/feature-flags) > > Gate features in your own app on a purchase. Delivered on creation, checked through the API, and revoked on cancellation. > [card] [Discord](/features/entitlements/discord) > > Give a customer a role in your Discord server when they buy. The role is removed automatically on cancellation. > [card] [GitHub](/features/entitlements/github) > > Add customers as collaborators to a private repository at the permission level you choose. > [card] [Telegram](/features/entitlements/telegram) > > Add customers to a private Telegram chat or channel after purchase. > [card] [Framer](/features/entitlements/framer) > > Unlock a Framer template remix link for paying customers. > [card] [Notion](/features/entitlements/notion) > > Duplicate a Notion template into the customer's workspace on purchase. *** ## How Grants Work Grants follow the same payment and subscription events that you receive as webhooks. Dodo Payments creates and revokes grants for purchases automatically, based on the payment lifecycle, so you don't call the grant API yourself. ### Grant Lifecycle A grant moves through these statuses: **1. Created** Dodo Payments creates a grant when a payment completes or a subscription becomes active. Feature-flag grants start as `Delivered`. License-key grants also start as `Delivered` when the entitlement uses `fulfillment_mode: auto` (the default). Under `fulfillment_mode: manual`, the grant starts as `Pending` with no key until you supply one with [Fulfill License Key Grant](/api-reference/entitlements/fulfill-license-key). Every other integration starts as `Pending`. OAuth-based integrations (Discord, GitHub, Notion) expose an `oauth_url` that the customer visits to give consent. Dodo Payments tries to generate this URL when it creates the grant. If that fails, the field stays `null` until the customer starts the accept flow from their delivery email or the Customer Portal. Platform-direct integrations (Telegram, Framer, Digital Files) stay `Pending` only while delivery is provisioned, then move to `Delivered`. **2. Delivered** When delivery completes, the grant moves to `Delivered` and `delivered_at` is set. Delivery is complete when the license key is generated, the role is assigned, the repository access is granted, the file links are resolved, or the OAuth flow is finished. **3. Failed** If the integration call returns a non-retryable error, such as a revoked OAuth token, a denied permission, or a file that no longer exists, the grant moves to `Failed`. The `error_code` and `error_message` fields record the reason. **4. Revoked** When access is withdrawn, for example because a subscription is cancelled, a refund is issued, or you revoke the grant, the grant moves to `Revoked`. The `revocation_reason` field records the trigger. ### Grant Behavior by Event Each payment and subscription event changes grants as follows: | Event | Behavior | | - | - | | `payment.succeeded` (one-time payment) | Issues one grant per attached entitlement. A License Key entitlement issues one grant per key. | | `payment.succeeded` (subscription-linked payment) | No change. The subscription events below drive these grants. | | `subscription.active` | Issues grants for any attached entitlements that don't have one yet, and re-grants grants previously revoked for the same subscription. Grants revoked with `manual`, `refund`, or `platform_external` aren't re-granted. | | `subscription.renewed` | No change. Existing grants persist across renewals. | | `subscription.past_due` | No change. Grants stay delivered for the whole [grace period](/features/subscription#grace-period). | | `subscription.on_hold` | Revokes all delivered and pending grants with `revocation_reason: subscription_on_hold`. | | `subscription.paused` | Revokes all delivered and pending grants with `revocation_reason: SubscriptionPaused`. Unlike the other subscription reasons, this value uses PascalCase, so match it exactly. | | `subscription.unpaused` | Re-grants grants previously revoked for the same subscription, the same way `subscription.active` does. | | `subscription.cancelled` | Revokes all grants with `revocation_reason: subscription_cancelled`. | | `subscription.expired` | Revokes all grants with `revocation_reason: subscription_expired`. | | `subscription.plan_changed` | Revokes all current grants with `revocation_reason: plan_changed`, then issues grants for the new plan's entitlements. | | `refund.succeeded` (one-time payment) | Revokes the grants for that payment with `revocation_reason: refund`. | | Manual API revoke | Revokes the grant with `revocation_reason: manual`. Manual revokes aren't re-granted automatically on subscription renewal. | | License key disabled | For license-key grants, disabling the underlying key revokes the grant with `revocation_reason: license_key_disabled`. Re-enabling the key restores the grant automatically. | | Platform drift detected | If the platform side of an integration drifts out of sync, such as a Discord role removed manually, the GitHub App losing repository access, or a reconciliation pass finding a missing target, Dodo Payments revokes the grant with `revocation_reason: platform_external`. It isn't re-granted automatically on subscription renewal until the platform issue is resolved. | > [!NOTE] > > Subscription-driven grants are idempotent per `(entitlement, customer, subscription)`, so renewals and re-activations don't create duplicate grants. One-time grants are idempotent per `(entitlement, customer, payment)`. *** ## Create Your First Entitlement **1. Open Entitlements** Go to **Entitlements** in the dashboard and click **+** to create an entitlement. **2. Pick an Integration** Choose the integration type: License Key, Digital Files, Feature Flag, Discord, GitHub, Telegram, Figma, Framer, or Notion. For a platform integration, connect your account first if you haven't already. **3. Configure Delivery** Fill in the fields for the integration. For example, GitHub asks for a repository and a permission level, Discord asks for a server and an optional role, and License Key asks for an activations limit and a license length. ![New Entitlement form with integration selector and configuration fields](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/github/create.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=722e925ec5158a5d16c58213132ccb9d) Creating a GitHub entitlement. Each integration shows the fields it needs. **4. Save** Click **Create Entitlement**. You can now attach the entitlement to any product. ## Attach Entitlements to Products Open a product, go to its **Entitlements** section, and select the entitlements to deliver when the product is purchased. One product can deliver several entitlements at once. For example, a Pro plan can include a license key, GitHub access, and a Discord role. ![Product entitlement selection panel showing checkboxes for each available entitlement](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/attach-to-product.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=965ad78262791fa8dbb712b4fdf89538) Attaching entitlements to a product. Selected entitlements are delivered on every successful purchase or active subscription. *** ## Customer Experience ### Email and Customer Portal After a purchase, the customer receives a delivery email with the license key, download links, OAuth invitation links, or platform invite that applies to the entitlements on the product. The same details stay available in the [Customer Portal](/features/customer-portal), under their order history, while the grant is active. ### OAuth-Based Delivery Discord, GitHub, and Notion subscriber access requires the customer to authorize Dodo Payments to grant that access. These grants stay `Pending` until the customer completes the OAuth flow from the link in their email or the Customer Portal. After the customer authorizes, the grant moves to `Delivered` and Dodo Payments provisions the platform access. ### Revocation When a grant is revoked, Dodo Payments removes the access on the platform: it removes the Discord role, removes the GitHub collaborator, or disables the license key. The customer sees the change in the Customer Portal. > [!WARNING] > > For Digital Files, revocation stops new presigned download URLs, but it doesn't invalidate copies that a customer has already downloaded. Plan your content gating with this in mind. *** ## Manage Grants Open any entitlement from the dashboard to see its grants. The detail panel shows the total granted, a status filter, and one row per grant with the customer, the date accessed, the status, and a **Revoke** action. To manage grants programmatically, list them with the `status` filter and revoke a single grant by ID: ```typescript TypeScript expandable theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], }); // List grants for an entitlement const grants = await client.entitlements.grants.list('ent_abc123', { status: 'Delivered', }); // Revoke a single grant await client.entitlements.grants.revoke('entg_xyz789', { id: 'ent_abc123', }); ``` ```python Python expandable theme={null} # Assumes client = DodoPayments(bearer_token=os.environ["DODO_PAYMENTS_API_KEY"]) grants = client.entitlements.grants.list( "ent_abc123", status="Delivered", ) client.entitlements.grants.revoke( "entg_xyz789", id="ent_abc123", ) ``` ```go Go expandable theme={null} // Assumes client := dodopayments.NewClient() and ctx := context.Background(). grants, err := client.Entitlements.Grants.List( ctx, "ent_abc123", dodopayments.EntitlementGrantListParams{ Status: dodopayments.F(dodopayments.EntitlementGrantListParamsStatusDelivered), }, ) if err != nil { panic(err.Error()) } fmt.Println(len(grants.Items)) _, err = client.Entitlements.Grants.Revoke(ctx, "ent_abc123", "entg_xyz789") ``` *** ## API Management > [card] [Create Entitlement](/api-reference/entitlements/create-entitlement) > > Create an entitlement of any integration type. > [card] [List Entitlements](/api-reference/entitlements/list-entitlements) > > List entitlements, filtered by integration type. > [card] [Get Entitlement](/api-reference/entitlements/get-entitlement) > > Retrieve an entitlement and its resolved configuration. > [card] [Update Entitlement](/api-reference/entitlements/update-entitlement) > > Update the name, description, or integration configuration. > [card] [Delete Entitlement](/api-reference/entitlements/delete-entitlement) > > Soft-delete an entitlement. Existing grants aren't revoked, but Dodo Payments no longer manages them. > [card] [Upload File](/api-reference/entitlements/upload-file) > > Upload a file of up to 500 MiB to a Digital Files entitlement. > [card] [List Grants](/api-reference/entitlements/list-grants) > > List an entitlement's grants, filtered by status and customer. > [card] [Revoke Grant](/api-reference/entitlements/revoke-grant) > > Revoke a single grant manually. *** ## Webhooks Dodo Payments sends four webhook events for the grant lifecycle. Subscribe to them to keep your application in sync with what each customer can access. | Event | Fires when | | - | - | | `entitlement_grant.created` | A grant is created. Auto-fulfilled license-key grants and feature-flag grants arrive `Delivered`. Manually fulfilled license-key grants and every other integration arrive `Pending`, then move to `Delivered` once the platform call succeeds or, for OAuth-based integrations, once the customer authorizes. | | `entitlement_grant.delivered` | An existing grant moves to `Delivered`, so the customer now has access. A grant that is `Delivered` on creation fires only `created`. | | `entitlement_grant.failed` | The grant couldn't be delivered. Inspect `error_code` and `error_message`. | | `entitlement_grant.revoked` | Access has been withdrawn. Inspect `revocation_reason`. | > [card] [Entitlement Grant Webhook Payloads](/developer-resources/webhooks/intents/entitlement-grant) > > View the full payload schema, sample events, and `revocation_reason` reference. *** ## Best Practices * **Use one entitlement per delivery channel.** Don't share one Discord entitlement across products with different role intentions. Create one entitlement per role, so revocation stays clean. * **Test in test mode first.** Create the entitlement, attach it to a test product, run a checkout, and watch the grant move from `Pending` to `Delivered`. Then cancel the test subscription and confirm that the grant is revoked. * **Listen to `entitlement_grant.delivered`, not `payment.succeeded`.** A payment can succeed before fulfillment finishes, especially for OAuth flows. Wait for the grant to reach `Delivered` before you unlock dependent features in your own systems. A grant that is delivered on creation, such as an auto-fulfilled license key or a feature flag, arrives as `entitlement_grant.created` with `status: "Delivered"` instead. * **Treat `entitlement_grant.failed` as actionable.** A failed grant means a customer paid but didn't get access. Surface these grants to your support team or trigger a re-grant. * **Map `revocation_reason` to your retention flows.** A `subscription_on_hold` revoke is recoverable, because the customer may update their card. A `manual` revoke is intentional. Treat them differently in customer messages. * **Do not revoke access on `subscription.past_due`.** That event opens a [grace period](/features/subscription#grace-period), and the customer keeps access until the window ends. Wait for `subscription.on_hold` or `subscription.cancelled`. # Notion Entitlement Source: https://docs.dodopayments.com/features/entitlements/notion Copy a Notion template into the customer's Notion workspace when they purchase, after they authorize Dodo Payments with Notion. > [!NOTE] > > The Notion entitlement copies a template you prepared into the paying customer's Notion workspace. The customer authorizes Dodo Payments with Notion and picks the workspace to receive the template, and Dodo Payments creates the copy. ## What Gets Delivered * The customer connects their Notion workspace from the Customer Portal. The payment confirmation email marks the entitlement **Action Required** and links to the portal. * After they authorize, Dodo Payments copies the configured template into a page the customer shared during authorization, in the workspace they chose. * When the grant is revoked, the copy stays in the customer's workspace. Dodo Payments marks the grant `Revoked` for record-keeping and doesn't delete the copy. Common uses include paid Notion templates, productivity systems, and OS or CRM templates. ## Connect Notion **1. Open Entitlements** In the Dodo Payments dashboard, go to **Entitlements** and click **+**. **2. Pick Notion** Choose **Notion Template** as the integration. If Notion isn't connected yet, click **Connect Notion**. ![New entitlement panel prompting the merchant to connect Notion](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/notion/connect-prompt.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=90f1f2a60c96918a8da19665a24fcaca) Connect Notion prompt before the OAuth handoff. Notion opens in a new tab. Sign in to the workspace that owns your source templates and review the permissions Dodo Payments requests. Then pick the pages (templates) the integration can read and copy. ![Notion OAuth permissions screen for Dodo Payments](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/notion/oauth-permissions.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=957e39812ac19bbf81cceb50f023a14a) Notion OAuth: review the permissions Dodo Payments requests. ![Notion page picker selecting which templates Dodo Payments can access](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/notion/oauth-select-pages.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=1f8bd414d5900f9d246d96f15877aba1) Notion OAuth: pick the template pages to share. When Notion redirects back, a confirmation page shows that the workspace is connected. ![Notion Template connected successfully confirmation page](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/notion/connected.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=5e526d2cc12c27f526b2a6e469157bd8) Workspace connected. Return to the Dodo Payments dashboard to continue. **3. Pick a Template** Back in the dashboard, select the template to copy under **Template**. Only pages you shared in the previous step appear here. Enter a **Name** for the entitlement and click **Create Entitlement**. ![Notion entitlement form with connected workspace, template picker, and name field](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/notion/create.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=82a51c79ed0c6937abf866c187673ab7) **4. Attach It to a Product** Attach the entitlement to any product. See [Attach Entitlements to Products](/features/entitlements/introduction#attach-entitlements-to-products). ## Customer Flow 1. The customer completes checkout. 2. Dodo Payments creates a grant in `Pending` status. Dodo Payments tries to create a Notion authorization URL right away and stores it in `oauth_url`. If that fails, `oauth_url` stays `null` until the customer starts the accept flow. 3. In the Customer Portal, the customer clicks **Connect** on the entitlement, authorizes with Notion, picks the workspace to receive the template, and shares at least one page with Dodo Payments. 4. Dodo Payments copies the template into a shared page in that workspace. The grant moves to `Delivered`. 5. On revocation, the grant is marked `Revoked`, and the copy remains in the customer's workspace. > [!NOTE] > > Revocation doesn't delete the copy. The copy lives in the customer's workspace, and the Dodo Payments revoke flow only marks the grant `Revoked`. ## Required Configuration | Field | Required | Description | | - | - | - | | `notion_template_id` | Yes | The ID (a UUID) of the template to copy. The dashboard's template picker fills this in. | ## Create via API ```typescript TypeScript expandable theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], environment: 'test_mode', }); const entitlement = await client.entitlements.create({ name: 'Study Notes', integration_type: 'notion', integration_config: { notion_template_id: '3f2b8c1e-7d4a-4e9b-a6c5-1d2e3f4a5b6c', }, }); ``` ```python Python expandable theme={null} import os from dodopayments import DodoPayments client = DodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), environment="test_mode", ) entitlement = client.entitlements.create( name="Study Notes", integration_type="notion", integration_config={"notion_template_id": "3f2b8c1e-7d4a-4e9b-a6c5-1d2e3f4a5b6c"}, ) ``` ```go Go expandable theme={null} // client is a *dodopayments.Client, for example from // dodopayments.NewClient(option.WithEnvironmentTestMode()); ctx is a context.Context. client.Entitlements.New(ctx, dodopayments.EntitlementNewParams{ Name: dodopayments.F("Study Notes"), IntegrationType: dodopayments.F(dodopayments.EntitlementIntegrationTypeNotion), IntegrationConfig: dodopayments.F[dodopayments.IntegrationConfigUnionParam]( dodopayments.IntegrationConfigNotionConfigParam{ NotionTemplateID: dodopayments.F("3f2b8c1e-7d4a-4e9b-a6c5-1d2e3f4a5b6c"), }, ), }) ``` ## Webhooks The [`entitlement_grant.*` webhook events](/developer-resources/webhooks/intents/entitlement-grant) cover the Notion flow: * `entitlement_grant.created` fires with `status: "Pending"`. `oauth_url` may already hold the Notion authorization URL. If it is `null`, it is populated once the customer starts the accept flow from the Customer Portal. * `entitlement_grant.delivered` fires once the template is copied. * `entitlement_grant.revoked` fires on cancellation. The customer's copy is left untouched. ## Troubleshooting > [accordion] Customer didn't get the template > > The grant stays `Pending` until the customer completes the Notion authorization. Ask the customer to open the Customer Portal and click **Connect**. Each authorization link expires 30 minutes after it's generated, and the Customer Portal generates a new one when the customer returns. During authorization, the customer must share at least one page, because Dodo Payments creates the copy inside a shared page. > [accordion] Template picker is empty > > In the entitlement form, click **Disconnect** on the Notion card, then click **Connect Notion** and reconnect with the workspace that owns the source templates. Share the template pages during authorization. > [accordion] Customer wants the template removed after refund > > Dodo Payments doesn't delete the copy when it revokes the grant. The customer must delete the copy from their own workspace. # Telegram Entitlement Source: https://docs.dodopayments.com/features/entitlements/telegram Add paying customers to a private Telegram group or channel when they subscribe or purchase, and remove them automatically when access ends. > [!NOTE] > > The Telegram entitlement gives paying customers access to a private Telegram group or channel. The customer links their Telegram account in the Customer Portal, and the Dodo Payments Telegram bot sends them a join request link that it approves only for that account. When the grant is revoked, the bot removes the customer from the chat. ## What Gets Delivered * The grant is created in `Pending`. It stays `Pending` after the customer links their Telegram account and the bot issues the join request link. * In the Customer Portal, the customer clicks **Connect**, sends `/start` to the Dodo Payments bot to get their Telegram user ID, enters it, and clicks **Link account**. * The bot sends the customer a join request link in Telegram. When the customer requests to join, the bot approves the request for their linked account only. * On cancellation, refund, or manual revoke, the bot removes the customer from the chat and bans them. If they buy again, the bot lifts the ban before it sends a new link. Common uses include private alpha channels, paid signal groups, and community-tier perks. ## Connect Telegram **1. Open Entitlements** In the Dodo Payments dashboard, go to **Entitlements** and click **+**, then choose **Telegram Access** as the integration. The dashboard asks for your Telegram user ID, which links the chats you add the bot to with your business. ![New Entitlement Telegram Access form prompting for Telegram user ID and Connect Telegram button](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/telegram/connect-prompt.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=dbb8be6964b2cbfb9bbe9902944f3d5f) New Entitlement → Telegram Access. The dashboard needs your Telegram user ID before it lists chats. > [!TIP] > > The next two steps happen in Telegram, and you can do them in either order: get your user ID, and add the bot to your chat as an admin. When both are done, return to the dashboard for the final step. **2. Get Your Telegram User ID** In Telegram, send **`/start`** to: * **`@dodo_payments_bot`** if you're using **Live Mode** * **`@DodoPaymentsTestBot`** if you're using **Test Mode** The bot replies with your numeric Telegram user ID. Copy it. You paste it into the dashboard in the last step. **3. Add the Bot to Your Chat as an Admin** From the same Telegram account, open the group or channel you want to gate and **add the same bot as an admin** (`@dodo_payments_bot` for live mode, `@DodoPaymentsTestBot` for test mode). Enable these two permissions: * **Ban Users**: required to remove members on revocation. * **Add Users**: required to invite paying customers. Leave every other admin permission off. ![Telegram Promote to admin screen showing Ban Users and Add Users enabled for the Dodo Payments bot](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/telegram/promote-bot-admin.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=bf927f2ee98616b671257d246de06cd3) Telegram → Promote to admin. Only Ban Users and Add Users need to be enabled. **4. Connect Telegram and Pick the Chat** Back in the dashboard, paste the user ID from step 2 into **Telegram User ID** and click **Connect Telegram**. The **Chat** picker lists the groups and channels you added the bot to from that account. Pick the chat you want to gate, enter a **Name** for the entitlement, and click **Create Entitlement**. ## Customer Flow 1. The customer completes checkout. 2. Dodo Payments creates a `Pending` grant. No invite link exists yet. 3. The payment confirmation email lists the entitlement as **Action Required** and links to the Customer Portal. In the portal, the customer clicks **Connect**, sends `/start` to the bot, enters their Telegram user ID, and clicks **Link account**. 4. The bot sends the customer a join request link in Telegram. The customer opens the link and requests to join, and the bot approves the request. 5. On revocation, the bot removes the customer from the chat. > [!TIP] > > The bot approves join requests only from the Telegram account the customer linked. A forwarded link doesn't give anyone else access. The linked account can't be changed on an existing grant. ## Required Configuration | Field | Required | Description | | - | - | - | | `chat_id` | Yes | The Telegram chat ID (numeric, and often negative for groups and channels). The dashboard's chat picker fills this in for you. | ## Create via API ```typescript TypeScript expandable theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env['DODO_PAYMENTS_API_KEY'], environment: 'test_mode', }); const entitlement = await client.entitlements.create({ name: 'Premium Signals Group', integration_type: 'telegram', integration_config: { chat_id: '-1001234567890', }, }); ``` ```python Python expandable theme={null} import os from dodopayments import DodoPayments client = DodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), environment="test_mode", ) entitlement = client.entitlements.create( name="Premium Signals Group", integration_type="telegram", integration_config={"chat_id": "-1001234567890"}, ) ``` ```go Go expandable theme={null} // client is a *dodopayments.Client, for example from // dodopayments.NewClient(option.WithEnvironmentTestMode()); ctx is a context.Context. client.Entitlements.New(ctx, dodopayments.EntitlementNewParams{ Name: dodopayments.F("Premium Signals Group"), IntegrationType: dodopayments.F(dodopayments.EntitlementIntegrationTypeTelegram), IntegrationConfig: dodopayments.F[dodopayments.IntegrationConfigUnionParam]( dodopayments.IntegrationConfigTelegramConfigParam{ ChatID: dodopayments.F("-1001234567890"), }, ), }) ``` ## Webhooks See [`entitlement_grant.*` webhook events](/developer-resources/webhooks/intents/entitlement-grant). Telegram grants arrive `Pending` and stay `Pending` after the customer links their Telegram account. If a customer with a delivered grant leaves the chat, Dodo Payments revokes the grant with `revocation_reason: platform_external`. ## Troubleshooting > [accordion] Chat doesn't appear in the picker > > Add the Dodo Payments bot to the chat **as an admin** with **Add Users** enabled, from the Telegram account whose user ID you entered in the dashboard. The chat appears in the picker once the bot is an admin. > [accordion] Customer says the invite link doesn't work > > The bot approves join requests only from the linked Telegram account. Ask the customer to open the link from that account. > > Revoking a grant is final. You can't reissue a revoked grant, so the customer needs a new purchase to get a new grant. > [accordion] Customer cancelled but is still in the chat > > The bot needs the **Ban Users** admin permission to remove members. Open the chat settings and confirm that both **Ban Users** and **Add Users** are enabled for the Dodo Payments bot. # Transferring Your Business to a New Entity Source: https://docs.dodopayments.com/features/entity-transfer Change the legal entity behind your business, such as moving from an individual to a registered company, while you keep receiving payments. ## Introduction An entity transfer changes the legal entity behind your business. Use it when you incorporate as a company, move the business to a different registered company, or go back to trading as an individual. Your business keeps receiving payments throughout. Products, customers, subscriptions, API keys, and integrations stay as they are. Dodo Payments verifies the new entity's details and bank account again, and pauses auto payouts until that verification is complete. > [!NOTE] > > To hand the business to a different person, use an [ownership transfer](/features/ownership-transfer) instead. An entity transfer keeps the same Owner. ## Supported Changes The entity transfer dialog offers two business types: **Individual** and **Registered entity**. What Dodo Payments verifies again depends on the type you move to. Your identity verification (KYC) is never repeated. | From | To | Verified again | | - | - | - | | Individual | Registered entity | Business verification (KYB) and bank account | | Registered entity | A different registered entity | Business verification (KYB) and bank account | | Registered entity | Individual | Bank account | A change from one individual to a different individual isn't an entity transfer, so the dialog doesn't offer it. Use an [ownership transfer](/features/ownership-transfer). To choose between the two types, see [Account Type](/miscellaneous/verification-process#account-type). ## Requirements * **Only the Owner can start an entity transfer.** * **The business must have a business type.** If the dashboard asks you to contact support to set the business type, do that first. * **A business can have one open transfer at a time.** An open entity transfer or [ownership transfer](/features/ownership-transfer) blocks a new one until it closes. ## Start an Entity Transfer > [!WARNING] > > You can't undo an entity transfer from the dashboard. As soon as you confirm the code, auto payouts pause and your current bank account is replaced by the one you verify for the new entity. **1. Open the Danger Zone** Go to **Settings → Business** and scroll to the **Danger Zone** panel. Next to **Entity transfer**, select **Start Transfer**. ![Danger Zone panel with the Entity transfer row and the Start Transfer button](https://mintcdn.com/dodopayments/WEk1ipt5KkjTZPhb/images/entity-transfer/danger-zone.png?fit=max\&auto=format\&n=WEk1ipt5KkjTZPhb\&q=85\&s=55dbf18870e61df3759c69c8f10be3ce) **2. Select the New Business Type** **Current setup** shows the type your business has today. Under **Moving to**, select the type of the new entity, then select **Continue**. ![Entity Transfer dialog with Individual as the current setup and Registered entity selected as the new type](https://mintcdn.com/dodopayments/WEk1ipt5KkjTZPhb/images/entity-transfer/select-type.png?fit=max\&auto=format\&n=WEk1ipt5KkjTZPhb\&q=85\&s=ec25d382f2d02de9c311c0b7a196ce42) **3. Review the Changes and Confirm** Read what happens to your business. Enter a **Reason for the change** of up to 1,000 characters. Type `TRANSFER` in the confirmation field, then select **Continue**. Dodo Payments emails a confirmation code to your login email address. ![Confirmation dialog listing that payments continue, verification restarts, and auto payouts pause, with a reason and TRANSFER entered](https://mintcdn.com/dodopayments/WEk1ipt5KkjTZPhb/images/entity-transfer/confirm.png?fit=max\&auto=format\&n=WEk1ipt5KkjTZPhb\&q=85\&s=76312c4ca5a75e2083825bd25323c431) **4. Enter the Code from Your Email** Enter the 6-digit code and select **Confirm Transfer**. The code expires after a short time, and too many wrong attempts mean you need to start again. ![Confirm the transfer dialog with a 6-digit code entered](https://mintcdn.com/dodopayments/WEk1ipt5KkjTZPhb/images/entity-transfer/code.png?fit=max\&auto=format\&n=WEk1ipt5KkjTZPhb\&q=85\&s=8be0516fcafb65223557db4172976fbb) If you no longer have access to your email, use the **Contact support** link in the dialog. **5. Verify the New Entity** The dashboard opens **Verification** and lists the forms you need to submit again. Select **Start Verification** and complete each form. See [Business Verification](/miscellaneous/verification-process#business-verification-kyb-—-registered-entities-only) and [Bank Verification](/miscellaneous/verification-process#bank-verification). ![Pop-up listing Business verification and Bank verification as the steps to complete the entity transfer](https://mintcdn.com/dodopayments/WEk1ipt5KkjTZPhb/images/entity-transfer/verification-popup.png?fit=max\&auto=format\&n=WEk1ipt5KkjTZPhb\&q=85\&s=65f46d3f08390c7b2904a599553cb919) ## While the Transfer Is in Progress The transfer stays open until Dodo Payments approves every verification of the new entity. During that time: * A strip at the top of every page reminds you what is left to verify, with a **Complete verification** link. * The **Danger Zone** shows **In-Progress** next to **Entity transfer**. * Your business keeps receiving payments. * Auto payouts stay paused. ![Danger Zone panel showing the In-Progress badge next to Entity transfer](https://mintcdn.com/dodopayments/WEk1ipt5KkjTZPhb/images/entity-transfer/danger-zone-in-progress.png?fit=max\&auto=format\&n=WEk1ipt5KkjTZPhb\&q=85\&s=80745771839746534c2cb297c63b915a) To stop an entity transfer, contact [support](/miscellaneous/help-support). Dodo Payments can restore your previous entity details and bank account. ## After the Transfer Completes When every verification is approved, the transfer completes and the dashboard shows a one-time confirmation. * Your business is set up as the new entity type. * Payouts go to the bank account you verified for the new entity. * Auto payouts stay off until you turn them back on. > [card] [Verification Process](/miscellaneous/verification-process) > > See what each verification form asks for. > [card] [Ownership Transfer](/features/ownership-transfer) > > Make a teammate the Owner of your business. > [card] [Payout Structure](/features/payouts/payout-structure) > > Learn how and when payouts are sent. > [card] [Help and Support](/miscellaneous/help-support) > > Get help with an entity transfer. # Hybrid Billing Models Source: https://docs.dodopayments.com/features/hybrid-billing Combine multiple billing modes to create sophisticated pricing strategies: subscription + usage, seats + add-ons, base + overage, and more. > [!NOTE] > > Hybrid billing combines two or more billing models into a single pricing strategy. This lets you capture value from different dimensions—recurring fees, usage, seats, and features—while giving customers flexibility and predictability. > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Foundation for consumption-based pricing. > [card] [Subscriptions](/features/subscription) > > Foundation for recurring billing. > [card] [Add-ons](/features/addons) > > Extend subscriptions with optional upgrades. > [card] [Seat-Based Billing](/features/seat-based-billing) > > Per-user pricing models. *** ## What Is Hybrid Billing? Hybrid billing combines multiple pricing dimensions into a single product offering. Instead of choosing between flat-rate subscriptions or usage-based pricing, you use both together. ### Why Use Hybrid Billing? | Business Goal | Hybrid Solution | | - | - | | Predictable revenue + growth upside | Base subscription + usage overage | | Team pricing that scales | Per-seat + feature add-ons | | Land customers, expand later | Low base fee + consumption charges | | Enterprise flexibility | Committed spend + on-demand charges | | Fair pricing for variable usage | Included allowance + pay-per-use | ### Common Hybrid Patterns | Model | Description | Example | Native Support | | - | - | - | - | | **1. Subscription + Usage** | Base fee + consumption charges | \$49/mo + \$0.01/API call after 10K free | ✅ Full | | **2. Subscription + Seats** | Platform fee + per-user charges | \$99/mo + \$15/seat | ✅ Full | | **3. Subscription + Feature Add-ons** | Core plan + optional upgrades | \$29/mo + \$19/mo analytics + \$9/mo API access | ✅ Full | | **4. Seats + Usage** | Per-user fee + consumption overage | \$10/user/mo + \$0.05/GB after 5GB/user | ⚠️ Workaround | | **5. Subscription + Seats + Usage** | Platform + users + consumption | \$199/mo + \$20/seat + usage overage | ⚠️ Workaround | | **6. Tiered Base + Usage Overage** | Different tiers with different allowances | Starter (5K calls) vs Pro (50K calls) + overage | ✅ Full | | **7. Subscription + On-Demand Charges** | Recurring fee + variable manual charges | \$99/mo retainer + hourly billing for work | ✅ Full | *** ## Hybrid Model 1: Subscription + Usage The most common hybrid model. Customers pay a base subscription fee plus charges for consumption that exceeds included allowances. ### How It Works **Pro Plan: \$49/month** * **Included**: 10,000 API calls/month * **Overage**: \$0.005 per call after 10,000 **Example calculation (customer uses 25,000 calls this month):** * Base subscription: \$49.00 * Overage: (25,000 - 10,000) × \$0.005 = \$75.00 * **Total: \$124.00** ### Use Cases * **API platforms**: Base access + per-request charges * **AI/ML services**: Subscription + token/generation usage * **Storage services**: Base plan + per-GB overage * **Communication platforms**: Base + per-message/minute charges ### Implementation **1. Create Usage Meter** Set up a meter to track the billable usage dimension. ```bash theme={null} Dashboard: Meters → Create Meter Event Name: "api.call" Aggregation: Count This tracks API calls per customer ``` **2. Create Subscription Product with Usage Pricing** Create a subscription product and attach the usage meter with pricing. ```bash theme={null} Dashboard: Create Product → Subscription Name: "Pro Plan" Base Price: $49/month Then attach usage pricing: - Meter: api.call - Price per unit: $0.005 - Free threshold: 10,000 (included in subscription) ``` > [!NOTE] > > The usage meter is attached directly to the subscription product. Usage charges are calculated and added to the subscription invoice automatically. **3. Create Checkout Session** Create a checkout session with your subscription product. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_pro_plan', quantity: 1 } ], customer: { email: 'customer@example.com' }, return_url: 'https://yourapp.com/success' }); ``` **4. Send Usage Events** Track usage throughout the billing period. ```typescript theme={null} await fetch('https://test.dodopayments.com/events/ingest', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.DODO_PAYMENTS_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [{ event_id: `call_${Date.now()}`, customer_id: 'cus_123', event_name: 'api.call', timestamp: new Date().toISOString(), metadata: { endpoint: '/v1/generate' } }] }) }); ``` ### Pricing Variations > [tab] Included Allowance > > Free threshold covers usage included in base subscription. > > **Pro Plan: \$49/month** > > * Includes: 10,000 API calls > * Overage: \$0.005/call after 10,000 > * Customer uses 8,000 → Pays \$49 (no overage) > [tab] Zero Base + Pure Usage > > No base fee, every unit is billable from the first use. > > **Pay-As-You-Go: \$0/month base** > > * Includes: 0 API calls > * Usage: \$0.01/call from first call > * Customer uses 5,000 → Pays \$50 > [tab] Tiered Allowances > > Different tiers include different allowances. > > * **Starter**: \$19/month (1,000 calls included) > * **Pro**: \$49/month (10,000 calls included) > * **Enterprise**: \$199/month (100,000 calls included) > * All tiers: \$0.005/call overage *** ## Hybrid Model 2: Subscription + Seats Platform fee plus per-user charges. Ideal for team collaboration tools and B2B SaaS. ### How It Works **Team Plan: \$99/month + \$15/seat** * **Base platform fee**: \$99/month (includes 3 seats) * **Additional seats**: \$15/seat/month **Example calculation (team of 12 users):** * Platform fee: \$99.00 * Extra seats: (12 - 3) × \$15 = \$135.00 * **Total: \$234.00/month** ### Use Cases * **Collaboration tools**: Workspace fee + per-member * **CRM systems**: Platform license + per-sales-rep * **Project management**: Team plan + per-contributor * **Developer tools**: Organization fee + per-developer ### Implementation **1. Create Seat Add-on** Create an add-on for additional seats. ```bash theme={null} Dashboard: Products → Add-ons → Create Add-on Name: "Additional Seat" Price: $15/month Description: "Add another team member" ``` **2. Create Base Subscription** Create the subscription product with platform fee and attach the add-on. ```bash theme={null} Dashboard: Create Product → Subscription Name: "Team Plan" Price: $99/month Description: "Includes 3 team members" Then in Add-ons section: - Attach: "Additional Seat" add-on ``` **3. Create Checkout with Seats** Specify seat quantity during checkout. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_team_plan', quantity: 1, addons: [{ addon_id: 'addon_seat', quantity: 9 // 9 extra seats (12 total with 3 included) }] }], customer: { email: 'admin@company.com' }, return_url: 'https://yourapp.com/success' }); ``` **4. Adjust Seats as Needed** Add or remove seats on existing subscriptions. ```typescript theme={null} // Add 5 more seats await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_team_plan', quantity: 1, proration_billing_mode: 'prorated_immediately', addons: [{ addon_id: 'addon_seat', quantity: 14 // New total: 14 extra seats }] }); ``` ### Pricing Variations > [tab] Included Seats > > Base plan includes some seats, charge for extras. > > **Team Plan: \$99/month** > > * Includes: 5 seats > * Extra seats: \$15/seat/month > * 20 users = \$99 + (15 × \$15) = \$324/month > [tab] Pure Per-Seat > > No platform fee, only per-user charges. > > **Per User: \$25/user/month** > > * No platform fee > * 5 users = \$125/month > * 50 users = \$1,250/month > > Implementation: Set base subscription price to \$0, use seat add-on only. > [tab] Tiered Per-Seat > > Per-seat price decreases at higher tiers. > > * **Starter**: \$20/seat (1-10 seats) > * **Growth**: \$15/seat (11-50 seats) > * **Enterprise**: \$10/seat (51+ seats) > > Implementation: Create separate subscription products for each tier with different add-on prices. *** ## Hybrid Model 3: Subscription + Feature Add-ons Core subscription with optional feature upgrades customers can add. ### How It Works **Core Plan: \$29/month** **Optional Add-ons:** * Advanced Analytics: +\$19/month * API Access: +\$9/month * Priority Support: +\$29/month * White-label: +\$49/month **Example calculation (customer chooses Core + Analytics + API Access):** * Core plan: \$29.00 * Analytics: \$19.00 * API Access: \$9.00 * **Total: \$57.00/month** ### Use Cases * **SaaS platforms**: Core features + premium modules * **Marketing tools**: Base tool + integrations * **Analytics products**: Dashboard + advanced reports * **Security software**: Basic protection + advanced features ### Implementation **1. Create Feature Add-ons** Create an add-on for each optional feature. ```bash theme={null} # Add-on 1: Advanced Analytics Dashboard: Products → Add-ons → Create Add-on Name: "Advanced Analytics" Price: $19/month # Add-on 2: API Access Name: "API Access" Price: $9/month # Add-on 3: Priority Support Name: "Priority Support" Price: $29/month # Add-on 4: White-label Name: "White-label" Price: $49/month ``` **2. Create Core Subscription** Define your base subscription and attach all feature add-ons. ```bash theme={null} Dashboard: Create Product → Subscription Name: "Core Plan" Price: $29/month Then in Add-ons section: - Attach all feature add-ons ``` **3. Let Customers Choose** Checkout with selected features. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_core_plan', quantity: 1, addons: [ { addon_id: 'addon_analytics', quantity: 1 }, { addon_id: 'addon_api_access', quantity: 1 } // Customer didn't select support or white-label ] }], return_url: 'https://yourapp.com/success' }); ``` **4. Add Features Later** Customers can add features to existing subscriptions. ```typescript theme={null} // Customer wants to add Priority Support await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_core_plan', quantity: 1, proration_billing_mode: 'prorated_immediately', addons: [ { addon_id: 'addon_analytics', quantity: 1 }, { addon_id: 'addon_api_access', quantity: 1 }, { addon_id: 'addon_priority_support', quantity: 1 } // New! ] }); ``` *** ## Hybrid Model 4: Seats + Usage Per-user fee combined with consumption-based charges. Each user gets an allowance. > [!WARNING] > > **Constraint**: Dodo Payments does not currently support attaching both usage meters and add-ons to the same subscription product. This model requires a workaround using application-level logic. ### How It Works **Team Analytics: \$20/user/month** **Each user includes:** * 5 GB data processing/month * Overage: \$2/GB after allowance **Example calculation (10-user team using 80 GB total):** * Seat fees: 10 × \$20 = \$200.00 * Included data: 10 × 5 GB = 50 GB * Overage: (80 - 50) × \$2 = \$60.00 * **Total: \$260.00/month** ### Use Cases * **Analytics platforms**: Per-analyst + data processing * **Design tools**: Per-designer + storage/exports * **Development environments**: Per-developer + compute hours * **Communication tools**: Per-user + message/call volume ### Implementation Options Since you cannot attach both usage meters and add-ons to the same subscription, choose one of these approaches: > [tab] Option A: Usage Product + App-Managed Seats > > Use a usage-based subscription and manage seat billing in your application. > > **1. Create Usage Meter** > > ```bash theme={null} > Dashboard: Meters → Create Meter > Event Name: "data.processed" > Aggregation: Sum > Property: "bytes" > ``` > > **2. Create Usage-Based Subscription** > > ```bash theme={null} > Dashboard: Create Product → Subscription > Name: "Team Analytics" > Base Price: $0/month > > Attach usage pricing: > - Meter: data.processed > - Price per unit: $2/GB > - Free threshold: 0 (managed by your app) > ``` > > **3. Manage Seats in Your Application** > > Track seat count and calculate seat fees separately. > > ```typescript theme={null} > // Your application tracks seats and calculates total cost > async function calculateMonthlyBill(customerId: string) { > const seatCount = await getSeatCount(customerId); > const seatFee = seatCount * 20; // $20/seat > > // Usage is billed by Dodo automatically > // You invoice/charge seat fees separately or include in base price > > // The update subscription endpoint can't change a subscription's price. > // To bill a different base amount when seats change, move the customer to > // another product with client.subscriptions.changePlan. > return seatFee; > } > ``` > > **4. Calculate Dynamic Free Threshold** > > Adjust included usage based on seat count. > > ```typescript theme={null} > // When checking usage, apply per-seat allowance > async function checkUsageOverage(customerId: string) { > const seatCount = await getSeatCount(customerId); > const includedGB = seatCount * 5; // 5 GB per user > > const currentUsage = await getUsageFromDodo(customerId); > const overage = Math.max(0, currentUsage - includedGB); > > // Overage is billed by Dodo at $2/GB > return { included: includedGB, used: currentUsage, overage }; > } > ``` > [tab] Option B: Seat Add-on + On-Demand Usage Charges > > Use add-ons for seats and charge usage manually via on-demand charges. > > **1. Create Seat Add-on** > > ```bash theme={null} > Dashboard: Products → Add-ons → Create Add-on > Name: "Team Member" > Price: $20/month > ``` > > **2. Create Subscription with Add-on** > > ```bash theme={null} > Dashboard: Create Product → Subscription > Name: "Team Analytics" > Base Price: $0/month > > Attach add-on: > - "Team Member" add-on > > Enable on-demand charging > ``` > > **3. Track Usage in Your Application** > > ```typescript theme={null} > // Track usage events in your system > async function trackDataProcessed(customerId: string, bytes: number) { > await saveUsageEvent({ > customer_id: customerId, > event_type: 'data.processed', > bytes: bytes, > timestamp: new Date() > }); > } > ``` > > **4. Charge Usage at End of Cycle** > > Calculate and charge usage overages manually. > > ```typescript theme={null} > async function billUsageOverage(subscriptionId: string) { > const subscription = await getSubscription(subscriptionId); > const seatCount = subscription.addons.find(a => a.addon_id === 'addon_seat')?.quantity || 0; > > const includedGB = seatCount * 5; > const usedGB = await calculatePeriodUsage(subscription.customer.customer_id); > const overageGB = Math.max(0, usedGB - includedGB); > > if (overageGB > 0) { > const overageCharge = overageGB * 200; // $2/GB in cents > await client.subscriptions.charge(subscriptionId, { > product_price: overageCharge, > product_description: `Data overage: ${overageGB} GB × $2/GB` > }); > } > } > ``` > [!NOTE] > > **Recommendation**: Option B (Seat Add-on + On-Demand Usage) is often easier to implement because Dodo handles seat billing automatically. You only need to track and charge usage overages. *** ## Hybrid Model 5: Subscription + Seats + Usage (Triple Hybrid) The most comprehensive model: platform fee + per-user + consumption. > [!WARNING] > > **Constraint**: Dodo Payments does not currently support attaching both usage meters and add-ons to the same subscription product. This model requires a workaround approach. ### How It Works **Enterprise Platform** * **Platform Fee**: \$199/month * **Per Seat**: \$25/user/month * **Usage**: \$0.10/1000 API calls (50K included) **Example calculation (company with 20 users, 150,000 API calls):** * Platform: \$199.00 * Seats: 20 × \$25 = \$500.00 * Usage: (150K - 50K) × \$0.10/1K = \$10.00 * **Total: \$709.00/month** ### Use Cases * **Enterprise SaaS**: Platform + team + consumption * **Data platforms**: Workspace + analysts + queries * **Integration platforms**: Hub + connectors + transactions * **AI platforms**: Workspace + developers + inference ### Implementation Options Choose one of these approaches to implement triple hybrid billing: > [tab] Option A: Base + Seats (Add-on) + On-Demand Usage > > Use subscription with seat add-ons, charge usage manually via on-demand charges. > > **This is the recommended approach** because Dodo handles the platform fee and seat billing automatically. > > **1. Create Seat Add-on** > > ```bash theme={null} > Dashboard: Products → Add-ons → Create Add-on > Name: "User Seat" > Price: $25/month > ``` > > **2. Create Subscription Product** > > ```bash theme={null} > Dashboard: Create Product → Subscription > Name: "Enterprise Platform" > Base Price: $199/month > > Attach add-on: > - "User Seat" add-on > > Enable on-demand charging > ``` > > **3. Create Checkout with Seats** > > ```typescript theme={null} > const session = await client.checkoutSessions.create({ > product_cart: [{ > product_id: 'pdt_enterprise_platform', > quantity: 1, > addons: [{ > addon_id: 'addon_user_seat', > quantity: 20 // 20 users > }] > }], > customer: { email: 'enterprise@company.com' }, > return_url: 'https://yourapp.com/success' > }); > ``` > > **4. Track Usage in Your Application** > > Store usage events in your system. > > ```typescript theme={null} > // Track API calls in your system > async function trackApiCall(customerId: string, endpoint: string) { > await saveUsageEvent({ > customer_id: customerId, > event_type: 'api.call', > endpoint: endpoint, > timestamp: new Date() > }); > } > ``` > > **5. Charge Usage at End of Cycle** > > Calculate and charge usage overages via on-demand charge. > > ```typescript theme={null} > async function billUsageOverage(subscriptionId: string) { > const usage = await calculatePeriodUsage(subscriptionId); > const includedCalls = 50000; > const overageCalls = Math.max(0, usage.totalCalls - includedCalls); > > if (overageCalls > 0) { > // $0.10 per 1000 calls = $0.0001 per call > const overageCharge = Math.ceil(overageCalls / 1000) * 10; // cents > await client.subscriptions.charge(subscriptionId, { > product_price: overageCharge, > product_description: `API usage: ${overageCalls.toLocaleString()} calls over 50K included` > }); > } > } > ``` > [tab] Option B: Base + Usage (Meter) + App-Managed Seats > > Use subscription with usage meter, manage seat billing in your application. > > **1. Create Usage Meter** > > ```bash theme={null} > Dashboard: Meters → Create Meter > Event Name: "api.call" > Aggregation: Count > ``` > > **2. Create Subscription Product with Usage** > > ```bash theme={null} > Dashboard: Create Product → Subscription > Name: "Enterprise Platform" > Base Price: $199/month > > Attach usage pricing: > - Meter: api.call > - Price: $0.10 per 1000 calls > - Free threshold: 50,000 > ``` > > **3. Manage Seats in Your Application** > > Track seat count and adjust base subscription price accordingly. > > ```typescript theme={null} > // When seats change, update subscription price > async function updateSeatCount(subscriptionId: string, newSeatCount: number) { > const basePlatformFee = 19900; // $199 in cents > const perSeatFee = 2500; // $25 in cents > const totalPrice = basePlatformFee + (newSeatCount * perSeatFee); > > // Store seat count in your system > await updateSeatsInDatabase(subscriptionId, newSeatCount); > > // Note: You may need to handle this via plan changes or > // create multiple tier products for common seat counts > } > ``` > > **4. Send Usage Events to Dodo** > > ```typescript theme={null} > await fetch('https://test.dodopayments.com/events/ingest', { > method: 'POST', > headers: { > 'Authorization': `Bearer ${process.env.DODO_PAYMENTS_API_KEY}`, > 'Content-Type': 'application/json' > }, > body: JSON.stringify({ > events: [{ > event_id: `api_${Date.now()}`, > customer_id: 'cus_enterprise', > event_name: 'api.call', > timestamp: new Date().toISOString() > }] > }) > }); > ``` > [!NOTE] > > **Recommendation**: Option A (Base + Seats + On-Demand Usage) is generally easier because Dodo handles platform and seat billing automatically. You only need to track usage and submit charges at the end of each billing cycle. *** ## Hybrid Model 6: Tiered Base + Usage Overage Different subscription tiers with different included allowances and overage rates. ### How It Works | Tier | Price | Included Calls | Overage Rate | | - | - | - | - | | **Starter** | \$19/month | 1,000 | \$0.02/call | | **Pro** | \$79/month | 25,000 | \$0.01/call | | **Business** | \$199/month | 100,000 | \$0.005/call | | **Enterprise** | \$499/month | 500,000 | \$0.002/call | ### Implementation Create separate subscription products for each tier, each with its own usage configuration: ```bash theme={null} # For each tier, create a subscription product: # Starter Tier Dashboard: Create Product → Subscription Name: "Starter" Base Price: $19/month Usage Pricing: - Meter: api.call - Price: $0.02/call - Free threshold: 1,000 # Pro Tier Name: "Pro" Base Price: $79/month Usage Pricing: - Meter: api.call - Price: $0.01/call - Free threshold: 25,000 # ... and so on for Business and Enterprise ``` ### Upgrade Path When customers upgrade tiers, they get: * Higher included allowance * Lower overage rates * More value per dollar ```typescript theme={null} // Customer upgrades from Starter to Pro await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_pro', quantity: 1, proration_billing_mode: 'prorated_immediately' }); ``` *** ## Hybrid Model 7: Subscription + On-Demand Charges Recurring subscription plus variable manual charges for services or overages. ### How It Works **Retainer Plan: \$199/month** **Includes:** * Platform access * 5 hours consulting/month * Email support **On-Demand Charges (as needed):** * Extra consulting: \$150/hour * Custom development: \$200/hour * Emergency support: \$100/incident **Example calculation (this month):** * Retainer: \$199.00 * 3 extra consulting hours: \$450.00 * 1 emergency support: \$100.00 * **Total: \$749.00** ### Use Cases * **Consulting services**: Retainer + hourly billing * **Managed services**: Base fee + incident charges * **Agency services**: Monthly fee + project charges * **Support plans**: SLA fee + per-ticket or per-hour ### Implementation **1. Create On-Demand Subscription** Set up subscription with on-demand charging enabled. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_retainer', quantity: 1 }], customer: { customer_id: 'cus_123' }, return_url: 'https://yourapp.com/success', subscription_data: { on_demand: { mandate_only: false, product_price: 19900 // $199 initial charge } } }); ``` **2. Charge for Services** Create charges when services are delivered. ```typescript theme={null} // Charge for 3 hours of consulting await client.subscriptions.charge('sub_123', { product_price: 45000, // $450.00 (3 × $150) product_description: 'Consulting - 3 hours (March 15)' }); // Charge for emergency support incident await client.subscriptions.charge('sub_123', { product_price: 10000, // $100.00 product_description: 'Emergency support - Server outage (March 18)' }); ``` **3. Track and Invoice** All charges appear on the customer's invoice. ```typescript theme={null} // Retrieve subscription charges const payments = await client.payments.list({ subscription_id: 'sub_123' }); // Show itemized breakdown to customer payments.items.forEach(payment => { console.log(`${payment.payment_id}: $${payment.total_amount / 100}`); }); ``` *** ## Real-World Examples > [!NOTE] > > These examples show ideal pricing structures. Due to the constraint that usage meters and add-ons cannot be attached to the same product, some combinations require workarounds (using on-demand charges for usage or app-managed seats). ### Example 1: AI SaaS Platform **Pricing Structure:** * **Base Subscription**: \$99/month (platform access, 5 seats included) * **Seat Add-on**: \$20/seat/month * **Feature Add-ons**: Custom Models (\$49/mo), API Access (\$29/mo), Priority Queue (\$19/mo) * **Usage Overage**: \$0.02 per 1,000 tokens after 100K (charged via on-demand) **Implementation**: Use subscription with seat and feature add-ons. Track token usage in your application and charge overages via on-demand charges at the end of the billing cycle. **Example Customer (12 users, 500K tokens, Custom Models + API Access):** | Component | Calculation | Amount | | - | - | - | | Base | Platform fee | \$99 | | Extra seats | 7 × \$20 | \$140 | | Custom Models | Add-on | \$49 | | API Access | Add-on | \$29 | | Token overage | 400K × \$0.02/1K (on-demand) | \$8 | | **Total** | | **\$325/month** | ### Example 2: Developer Tools Platform **Tier Options:** | | Free | Pro | Enterprise | | - | - | - | - | | **Price** | \$0/month | \$29/month | \$199/month | | **Users** | 1 | 5 included | Unlimited | | **Builds** | 100 | 1,000 | 10,000 | | **Storage** | 1 GB | 10 GB | 100 GB | **Implementation Options**: **Option A** (Usage-focused): Create products with usage meters for builds/storage. Manage users in your application. **Option B** (Seat-focused): Create products with seat add-ons. Track builds/storage usage and charge overages via on-demand. **Add-ons (if using Option B):** * Extra users: \$10/user/month * Priority builds: \$19/month * Custom domains: \$9/domain/month ### Example 3: Marketing Automation **Pricing Structure:** * **Base**: \$79/month (core automation features, 3 seats included) * **Contact Tiers** (add-ons): 1K included, 5K (+\$30), 25K (+\$80), 100K (+\$200) * **Feature Add-ons**: SMS Marketing (\$29/mo), Landing Pages (\$19/mo), A/B Testing (\$29/mo) * **Team Seats**: \$15/user/month add-on * **Email Volume**: Track in application, charge overage via on-demand (\$1/1,000 emails over limit) **Implementation**: Use subscription with contact tier add-ons, feature add-ons, and seat add-ons. Track email sends in your application and charge overages via on-demand charges at the end of the billing cycle. *** ## Implementation Best Practices ### Pricing Page Clarity > [!TIP] > > Make hybrid pricing easy to understand. Show base costs, what's included, and how overages work prominently on your pricing page. **Clear**: "\$49/month includes 10,000 API calls. Additional calls: \$0.005 each" **Unclear**: "\$49/month + usage fees" ### Cost Predictability Help customers estimate their costs: ```typescript theme={null} // Provide a cost calculator function estimateMonthlyCost({ plan, seats, expectedUsage, addons }: EstimateParams): number { let total = plan.basePrice; // Add seat costs const extraSeats = Math.max(0, seats - plan.includedSeats); total += extraSeats * plan.seatPrice; // Add usage overage const overage = Math.max(0, expectedUsage - plan.includedUsage); total += overage * plan.overageRate; // Add feature add-ons total += addons.reduce((sum, addon) => sum + addon.price, 0); return total; } ``` ### Usage Visibility Show customers their usage in real-time: ```typescript theme={null} // Display usage dashboard async function getUsageSummary(subscriptionId: string) { const usage = await client.subscriptions.retrieveUsageHistory(subscriptionId); // Each item is a billing period; each meter reports its usage for that period. const latestPeriod = usage.items[0]; return latestPeriod.meters.map((meter) => { const consumed = Number(meter.consumed_units); const chargeable = Number(meter.chargeable_units); return { meter: meter.name, current: consumed, included: meter.free_threshold, remaining: Math.max(0, meter.free_threshold - consumed), overage: chargeable, cost: meter.total_price }; }); } ``` ### Billing Transparency Provide detailed invoices showing all components: | Line Item | Amount | | - | - | | Pro Plan (Monthly) | \$49.00 | | Additional Seats (7 × \$15.00) | \$105.00 | | API Usage - Included (10,000 calls) | \$0.00 | | API Usage - Overage (15,420 calls × \$0.005) | \$77.10 | | Advanced Analytics Add-on | \$19.00 | | **Subtotal** | **\$250.10** | | Tax (8.5%) | \$21.26 | | **Total Due** | **\$271.36** | *** ## Troubleshooting Hybrid Billing > [accordion] Usage not being tracked correctly > > **Symptoms**: Usage shows 0 or incorrect values. > > **Solutions**: > > 1. Verify event ingestion is working (check API responses) > 2. Confirm `customer_id` matches the subscription customer > 3. Check `event_name` matches the meter configuration > 4. Verify events have correct timestamps (not future-dated) > [accordion] Proration confusion with multiple components > > **Symptoms**: Customer charged unexpected amounts when changing plans. > > **Solutions**: > > 1. Use `previewChangePlan` API to show exact charges before confirming > 2. Communicate that proration applies to subscription AND add-ons > 3. Consider using `difference_immediately` for simpler upgrade billing > [accordion] Free threshold not applying correctly > > **Symptoms**: Customer charged for usage that should be free. > > **Solutions**: > > 1. Verify free threshold is configured on the usage-based product > 2. Check threshold unit matches event aggregation (calls vs. requests) > 3. Confirm usage meter is correctly attached to the subscription product > [accordion] Add-ons not appearing in checkout > > **Symptoms**: Can't add seats or features during checkout. > > **Solutions**: > > 1. Verify add-ons are attached to the subscription product in dashboard > 2. Check add-on IDs are correct in API calls > 3. Ensure add-on currency matches subscription product currency *** ## Related Documentation > [card] [Products](/features/products) > > Overview of all product types and guides. > [card] [Usage-Based Billing Guide](/developer-resources/usage-based-billing-guide) > > Complete usage billing implementation. > [card] [Subscription Management](/features/subscription) > > Managing recurring subscriptions. > [card] [Add-ons](/features/addons) > > Extending subscriptions with add-ons. # Invoice-Based Billing Source: https://docs.dodopayments.com/features/invoice-based-billing Send an invoice first and collect payment after. Bill one-time or recurring items on payment terms, by auto-charge or through a hosted invoice page. ![The Manage Invoices page in the Dodo Payments dashboard, with tiles for drafts, open invoices, past-due invoices, and the outstanding amount](https://mintcdn.com/dodopayments/aP958i30jx5nBLqD/images/invoice-based-billing/invoice-list.png?fit=max\&auto=format\&n=aP958i30jx5nBLqD\&q=85\&s=9f268a2b5ea6b2bb58e7b34df2234317) ## Overview Invoice-based billing lets you bill a customer before they pay. You issue an invoice with a due date. The customer reviews it, then pays on a hosted invoice page, or Dodo Payments charges their saved card on the due date. Use it for B2B sales on payment terms, such as Net 30, for annual contracts, and for customers who need an invoice before their finance team pays. This is the opposite order to checkout. With checkout, the customer pays first and Dodo Payments generates the invoice after the payment. With invoice-based billing, the invoice comes first and the payment settles it. Dodo Payments is the [Merchant of Record](/features/mor-introduction) on every invoice. The Dodo Payments legal entity is the seller, and your brand name and logo identify the sale for your customer. > [card] [Invoice Management](/features/invoice-generation) > > Set the brand name and logo that every invoice shows. > [card] [Subscription Payment Retries](/features/recovery/payment-retries) > > Configure the retry schedule that auto-charge invoices use. ## How It Works An invoice goes through these steps: **1. Draft** You create a draft with a customer, items, a currency, a due date, and a collection method. You can change every field of a draft, or delete it. **2. Finalize** You finalize the draft. Dodo Payments fixes the tax, the currency, the customer address, and the tax ID, sets the due date, and the invoice becomes `open`. You can send it to the customer at the same time. **3. Collect** With **Auto-charge**, Dodo Payments charges the customer's saved card on the due date. With manual collection, the customer pays on the hosted invoice page. Reminder emails follow your reminder schedule. **4. Settle** When the payment succeeds, the invoice becomes `paid`. If the due date passes first, the invoice becomes `past_due`, and you can extend the due date, void the invoice, or mark it uncollectable. ## Invoice Statuses An invoice always has one of these statuses: | Status | Meaning | | - | - | | `draft` | The invoice is not issued. You can edit or delete it. The customer cannot see it. | | `open` | The invoice is issued and waits for payment before its due date. | | `past_due` | The due date passed and the invoice is not paid. | | `paid` | A payment settled the full amount due. | | `void` | You cancelled the invoice before payment. No payment is collected. | | `uncollectable` | The invoice is written off after dunning ends. | `paid`, `void`, and `uncollectable` are final statuses. A deleted draft is removed from the list. A `paid` invoice can also carry tags. Tags do not change the status: | Tag | Meaning | | - | - | | `partially_refunded` | Part of the payment is refunded. | | `refunded` | The full payment is refunded. | | `disputed` | The customer opened a dispute on the payment. | | `payment_reversed` | The dispute was lost, accepted, or expired. | ## Creating an Invoice You create invoices on the **Invoices** page of the dashboard, or with the API. The customer must have a billing address with a country, street, city, and ZIP code before you can finalize the invoice. ![The Create New Invoice form, with a selected customer, one product item, and a live PDF preview](https://mintcdn.com/dodopayments/aP958i30jx5nBLqD/images/invoice-based-billing/create-invoice.png?fit=max\&auto=format\&n=aP958i30jx5nBLqD\&q=85\&s=c668d37ebedbad767a4b1672e1da2e55) **1. Open the invoice form** Go to **Invoices** and click **Create Invoice**. **2. Select the customer** In **Select Customer**, search for a customer by name or email, or add a new customer. If the customer has no billing address, click **Add** next to **Billing Address**. A business customer also needs a tax ID. See [B2B Payments](/features/b2b-payments). **3. Add items** In **Items**, add products from your catalogue. To bill a subscription through invoices, add a subscription product. **4. Set the payment terms** In **Payments**, select a **Due Date**: **Today**, **Tomorrow**, **1 Week**, **2 Weeks**, or **Pick a date**. Terms count from the time you finalize the invoice. To apply a discount, select the **Apply Additional Discount** checkbox, then select a [discount code](/features/discount-codes). **5. Select how to collect** To charge the customer's saved card on the due date, turn on **Auto-charge** and select the card. Auto-charge needs a subscription item. Otherwise, leave it off, and the customer pays on the hosted invoice page. **6. Set review and reminders** For an invoice with a subscription item, turn on **Manual review** to review each renewal invoice before it goes to the customer. See [Reviewing Renewal Invoices](#reviewing-renewal-invoices). Keep **Reminders** on to send reminder emails on your business reminder schedule. **7. Check the preview** Use the **Preview** panel to see the **PDF**, the **Email Preview**, and the **Hosted Preview**. **8. Save or finalize** Click **Save as Draft** to keep the invoice editable. Click **Finalise Invoice** to issue it. In the **Review Invoice** dialog, click **Add Recipients** to set the **Send to** and **Additional CC recipients** addresses, then click **Finalise & Send**. ![The Payments and Reminders sections of the invoice form, with the due date, discount, Auto-charge, and Dunning and Retries controls](https://mintcdn.com/dodopayments/aP958i30jx5nBLqD/images/invoice-based-billing/create-invoice-payments.png?fit=max\&auto=format\&n=aP958i30jx5nBLqD\&q=85\&s=f7271738cb70ca0df474f66c832d6998) ### What Happens at Finalize When you finalize an invoice, Dodo Payments does these steps: * It calculates the tax and fixes the currency, the billing address, and the tax ID. After this, you cannot change them. * It sets the due date from the payment terms. A manual invoice that is due on receipt gets 24 hours to be paid. * It applies the customer's [wallet](/features/customer-wallet) credit to the amount due. * It fixes the reminder schedule for the invoice. If the amount due is zero, the invoice becomes `paid` immediately. No payment method or payment link is necessary. A custom due date must still be in the future when you finalize. If it is not, select a new due date. ## Collecting Payment ### Auto-Charge An auto-charge invoice charges the customer's saved card on the due date. * If the charge on the due date fails, the invoice becomes `past_due`. If you turned on [Subscription Payment Retries](/features/recovery/payment-retries), Dodo Payments then retries the charge on your retry schedule. A hard decline stops the retries until the customer adds a new card. * If the customer has no saved card on the due date, the invoice becomes `past_due`. When the customer saves a card later, Dodo Payments charges it at once. If that charge fails, retries follow your schedule. * To charge the saved card again before the next scheduled attempt, use the [Retry Invoice API](/api-reference/invoices/retry-invoice). The invoice must be `open` or `past_due`, use auto-charge, and have a saved card, and its subscription must not be cancelled. You cannot retry while a payment is processing or while dunning is paused. ### Manual Collection A manual invoice is not charged automatically. The customer pays on the hosted invoice page. If the customer does not pay by the due date, the invoice becomes `past_due`. ### Reminder Emails Each invoice follows your business reminder schedule. Dodo Payments fixes that schedule on the invoice when you finalize it. If your business has no reminder schedule, no reminders are sent. Configure the schedule in **Settings → Recovery**. The **Configure** button next to **Dunning & Retries** on the invoice form opens that page. Reminders go out only for an invoice that you sent. A finalized invoice that you never send gets no reminders. On an auto-charge invoice with a saved card, only the reminders before the due date go out, because retries take the place of later reminders. To change the schedule of one invoice, use the API: * Send `dunning` when you create or update a draft, with `reminders_enabled` and `offsets_days`. Each offset is a number of days from the due date. A negative offset sends the reminder before the due date. * Send `pause`, `resume`, or `reschedule` to the dunning endpoint of an open or past-due invoice. A paused invoice gets no reminders, no retries, and no automatic write-off. ### The Hosted Invoice Page The hosted invoice page lets the customer pay without a login. It shows the amount due, the due date, the line items, and the totals. The customer can pay the amount due and download the invoice PDF. After a refund, the page also links to the refund receipt. ![A hosted invoice page with the amount due, a Pay button, the invoice number, the line items, and a Download PDF button](https://mintcdn.com/dodopayments/aP958i30jx5nBLqD/images/invoice-based-billing/hosted-invoice-page.png?fit=max\&auto=format\&n=aP958i30jx5nBLqD\&q=85\&s=df460e29f88693719e9346c6c6b6b2b1) To get the link, use one of these methods: * In the dashboard, copy the link from the invoice details page, or click **Copy Link** on the invoice in the list. * In the API, read `hosted_url` on a sent invoice, or call the hosted link endpoint. Getting the link counts as sending the invoice. Draft, void, and uncollectable invoices have no new link. The link stays valid while the invoice is open, past due, or paid. If you void the invoice or mark it uncollectable, a link that you already sent opens a read-only page until it expires. When the invoice has a subscription item, the payment saves the customer's card for later renewals. ### Emails to the Customer Dodo Payments sends these emails to the customer: | Email | When | | - | - | | Invoice | You send the invoice, or Dodo Payments sends a renewal invoice. | | Reminder | A reminder on the invoice schedule is due. | | Card needed | An auto-charge invoice reaches a reminder time before its due date, and the customer has no saved card. | | Payment confirmation | The payment succeeds. | | Payment failed | An automatic charge fails. | | Due date updated | You change the due date of a sent, unpaid invoice. | | Invoice voided | You void the invoice. | Every email except the void email has a link to the hosted invoice page. The void email goes only to the customer email of a sent invoice. You also get emails when a renewal draft is ready for review, and when an invoice is sent, paid, past due, voided, has a failed payment, or reaches the end of dunning. ## Managing Invoices ![The Invoice Details page for an open invoice, with the hosted page link, Edit and More Actions buttons, the summary, and the activity log](https://mintcdn.com/dodopayments/aP958i30jx5nBLqD/images/invoice-based-billing/invoice-details.png?fit=max\&auto=format\&n=aP958i30jx5nBLqD\&q=85\&s=73db7655984bc292f62ee7a2d56e1394) The invoice details page shows the summary, the line items, the payments, the subscriptions that the invoice bills, the refunds in **Credit Notes**, and an **Activity Log** of every action. Click **Add Note** to add an internal note to the activity log. ### Editing an Invoice What you can edit depends on the status: | Status | Editable fields | | - | - | | `draft` | All fields | | `open` | Due date, collection method, recipients, and metadata | | `past_due` | Due date, recipients, and metadata | | `paid`, `void`, `uncollectable` | Metadata only | A new due date must be in the future. If you move the due date of a `past_due` invoice to the future, the invoice becomes `open` again. If the invoice was sent, the customer gets an email with the new due date. To correct an amount, an item, the currency, the customer, or the tax ID on an issued invoice, void the invoice and create a new one. ### Voiding an Invoice To void an invoice, open it, click **More Actions**, then **Update Status**, select **Mark as Void**, and click **Continue**. ![The Update Invoice Status dialog with the Mark as Void option](https://mintcdn.com/dodopayments/aP958i30jx5nBLqD/images/invoice-based-billing/update-status.png?fit=max\&auto=format\&n=aP958i30jx5nBLqD\&q=85\&s=f3e80fff392605111d065e75cec8b0d6) * You can void only an `open` or `past_due` invoice. To remove a draft, delete it. * You cannot void an invoice while a payment is processing. * Wallet credit applied to the invoice goes back to the customer's wallet. * The hosted page and the PDF stay available, without a payment button. * If the invoice is the first invoice of a subscription, the subscription fails. ### Marking an Invoice Uncollectable When dunning of a `past_due` invoice ends, you get an email. You then have 7 days to extend the due date, void the invoice, or mark it uncollectable. If you do nothing, Dodo Payments marks the invoice `uncollectable` after 7 days. Dunning ends at these times: * **Manual collection:** at the due date plus the recovery window of your [Payment Retries](/features/recovery/payment-retries) settings. With no retry settings, dunning ends at the due date. * **Auto-charge:** at the last failed retry. If you pause dunning, the automatic write-off does not happen. Wallet credit applied to the invoice stays applied when the invoice becomes uncollectable. To mark it yourself, open the invoice, click **More Actions**, then **Update Status**, and select **Mark as Uncollectable**. Only a `past_due` invoice can be marked uncollectable. ### Late Payments If a payment succeeds on a `void` or `uncollectable` invoice, Dodo Payments refunds the full payment automatically. The invoice keeps its status. A second payment on a `paid` invoice is also refunded. ### Duplicating an Invoice To create a new draft with the same details, click **Duplicate Invoice** on the invoice in the list. The copy does not keep a custom due date, the manual review setting, or usage lines. You cannot duplicate a renewal invoice or a plan change invoice. ## Recurring Invoices When an invoice has a subscription item, it starts a subscription that invoices bill. Dodo Payments creates the subscription with the draft, in the `pending` status. The subscription becomes `active` when the customer pays the first invoice. If you delete the draft, or void the first invoice, or it becomes uncollectable, the subscription fails. On each next billing date, Dodo Payments creates a renewal invoice with the same payment terms and collection method. If the first invoice used a custom due date, renewal invoices are due on receipt. For a usage-based subscription, the renewal invoice comes 1 hour after the billing date, so that late usage events count. The renewal invoice controls the subscription status: * If a renewal or plan change invoice becomes `past_due`, the subscription enters its [grace period](/features/subscription#grace-period), or goes `on_hold` if you have no grace period. * When the customer pays, the subscription becomes `active` again. * An `on_hold` subscription gets no new renewal invoice until the customer pays. An invoice with more than one subscription cannot have one-time items. All items must use the invoice currency. These subscription actions are not available when invoices bill the subscription: pause, on-demand charges, a change of the next billing date, and `collect_via_payment_link` on a plan change. ### Free Trials An invoice-billed subscription can start with a free trial. Dodo Payments creates the subscription and a paid \$0 invoice for the trial. The first invoice that bills an amount comes when the trial ends. **1. Add one subscription product** In **Create Invoice**, select the customer and add one subscription product. The trial is available only with one product, no add-ons, no other items, and no discount. **2. Turn on the trial** Turn on **Start with a free trial**. **Trial days** shows the trial length of the product. You can set 1 to 730 days. **3. Set the terms after the trial** Select the payment terms and the collection method for the invoices after the trial. For **Auto-charge**, select a saved card. Discounts, reminders, and metadata do not apply to a trial. **4. Start the trial** Click **Start Trial**, check the details in the dialog, and click **Start Trial** again. If a product has a trial and you do not turn on **Start with a free trial**, the invoice bills the full price now. The form shows a warning. * [Preventing Trial Misuse](/features/subscription#preventing-trial-misuse) applies only when you keep the trial length of the product. A custom length skips the check. * The customer gets a reminder email before the trial ends. * You cannot change the plan during the trial. * Paid trials are not available. * With the API, send `POST /billing/subscriptions`. Set `trial_period_days` to change the trial length. For auto-charge, send `payment_method_id`. ### Reviewing Renewal Invoices With **Manual review** on, each renewal invoice is saved as a draft. You get an email when the draft is ready. You have 72 hours after the billing date to review and send it. If you do not, Dodo Payments finalizes the draft and sends it to the customer automatically. You can change the due date, the collection method, the recipients, the reminders, and the metadata of a renewal draft. You cannot change its prices or items. ### Changing Plans Change the plan of an invoice-billed subscription from the dashboard or with the [Change Plan API](/api-reference/subscriptions/change-plan). The proration uses the same [proration modes](/features/subscription#proration-modes) as other subscriptions. * **Change now:** Dodo Payments creates a plan change invoice. A positive total is an amount due. Use the `invoice` object to set its `payment_terms` and `collection_method`. They default to the subscription values. To review the invoice before it is issued, set `invoice.finalize` to `false`. If you do not finalize the draft in 72 hours, Dodo Payments finalizes it. * **Change at the next billing date:** nothing is billed now. The next renewal invoice bills the new plan. * **Downgrade credit:** set `credit` to `customer_balance` (default) to add the credit to the customer's wallet, or to `refund` to refund it to the last paid payment. The credit goes to the wallet if there is no paid payment, if the last payment uses a different currency, or if the refund fails. You cannot change the plan while an earlier plan change invoice is unpaid. Pay, void, or delete that invoice first. Customers cannot change the plan of an invoice-billed subscription from the [Customer Portal](/features/customer-portal). ### Cancelling a Subscription * **Cancel now:** the subscription becomes `cancelled`, and renewal drafts are deleted. Open invoices stay open, and the customer can still pay them. Auto-charge stops. * **Cancel at the next billing date:** no renewal invoice is created, and the subscription ends at the billing date. To cancel a `pending` subscription, void its first invoice. ## Refunds and Disputes Refund an invoice payment from the payment, the same as any other payment. On the invoice details page, click **More Actions**, then **Refund via Payment**. See [Refunds](/features/transactions/refunds). A refund does not change the invoice status. It adds the `refunded` or `partially_refunded` tag and a refund receipt. A dispute on an invoice payment adds the `disputed` tag. If the dispute is lost, accepted, or expires, the tag changes to `payment_reversed`. To bill the customer again, duplicate the invoice. ## Limits These limits apply to each invoice: | Item | Limit | | - | - | | Items per invoice | 1 to 50 | | Quantity per item | 1 to 10,000 | | Discount codes per invoice | 20 | | CC recipients | 10 | | Note | 2,000 characters | ## Webhooks Dodo Payments sends these webhook events for invoices. See [Invoice Webhooks](/developer-resources/webhooks/intents/invoice) for the payload schema. The payload is the invoice object, the same as the response of `GET /billing/invoices/{id}`. It shows the invoice at the time of delivery, not at the time of the event. | Event | Fires when | | - | - | | `invoice.finalized` | An invoice is finalized. | | `invoice.sent` | You send an invoice, Dodo Payments sends a renewal invoice, or the hosted link is first created. | | `invoice.paid` | An invoice is paid, including a \$0 invoice at finalize. | | `invoice.payment_failed` | An automatic charge fails. | | `invoice.past_due` | An invoice becomes past due. | | `invoice.reopened` | A past-due invoice becomes open after a due date change. | | `invoice.voided` | An invoice is voided. | | `invoice.marked_uncollectable` | An invoice is marked uncollectable. | Refunds and disputes on invoice payments send the usual [refund](/developer-resources/webhooks/intents/refund) and [dispute](/developer-resources/webhooks/intents/dispute) events. ## API Management All invoice endpoints accept your API key. Each invoice response has an `ETag` header. Send its value in the `If-Match` header when you change the invoice. If the invoice changed after you read it, the request fails, and you must read the invoice again. > [accordion] Create and Edit Invoices > > Create a draft, list and read invoices, update a draft, or delete it. Send an `Idempotency-Key` header on create to prevent duplicate drafts. > > > [card] [Create Invoice](/api-reference/invoices/create-invoice) > > > > Create a draft invoice. > > > [card] [List Invoices](/api-reference/invoices/list-invoices) > > > > List invoices with filters. > > > [card] [Get Invoice](/api-reference/invoices/get-invoice) > > > > Get one invoice with its lines and payments. > > > [card] [Update Invoice](/api-reference/invoices/update-invoice) > > > > Change the editable fields of an invoice. > > > [card] [Delete Invoice](/api-reference/invoices/delete-invoice) > > > > Delete a draft. > > > [card] [Duplicate Invoice](/api-reference/invoices/duplicate-invoice) > > > > Copy an invoice to a new draft. > [accordion] Preview Invoices > > Show the PDF, the email, or the data of an invoice before you issue it. > > > [card] [Preview Invoice Request](/api-reference/invoices/preview-invoice-request) > > > > Preview an invoice without saving it. > > > [card] [Preview Invoice](/api-reference/invoices/preview-invoice) > > > > Preview a saved draft. > > > [card] [Get Upcoming Invoice](/api-reference/subscriptions/get-upcoming-invoice) > > > > Preview the next renewal invoice of a subscription. > [accordion] Issue and Send Invoices > > Finalize a draft, email it, or get the hosted invoice page link. Send `"send": true` on finalize to also send the invoice. > > > [card] [Finalize Invoice](/api-reference/invoices/finalize-invoice) > > > > Issue a draft. > > > [card] [Send Invoice](/api-reference/invoices/send-invoice) > > > > Email the invoice to the customer. > > > [card] [Create Hosted Link](/api-reference/invoices/create-hosted-link) > > > > Get the hosted invoice page link. > [accordion] Collect Payment > > Charge the saved card now, or pause, resume, or reschedule the reminders of an invoice. > > > [card] [Retry Invoice](/api-reference/invoices/retry-invoice) > > > > Charge the saved card of an auto-charge invoice. > > > [card] [Change Dunning](/api-reference/invoices/change-dunning) > > > > Pause, resume, or reschedule reminders. > [accordion] Close Invoices > > Void an unpaid invoice, or write off a past-due invoice. > > > [card] [Void Invoice](/api-reference/invoices/void-invoice) > > > > Cancel an open or past-due invoice. > > > [card] [Mark Uncollectable](/api-reference/invoices/mark-uncollectable) > > > > Write off a past-due invoice. > [accordion] Notes and History > > Add an internal note, or read every action on an invoice. > > > [card] [Add Note](/api-reference/invoices/add-note) > > > > Add a note to the activity log. > > > [card] [List Invoice Events](/api-reference/invoices/list-invoice-events) > > > > Get the event history of an invoice. ## Not Supported These items are not available for invoice-based billing: * Marking an invoice paid for a payment made outside Dodo Payments. * Partial payments. The customer pays the full amount due. > [card] [Subscriptions](/features/subscription) > > Learn how subscriptions, plan changes, and grace periods work. > [card] [Webhook Events Guide](/developer-resources/webhooks/intents/webhook-events-guide) > > See every webhook event that Dodo Payments sends. # Invoice Management Source: https://docs.dodopayments.com/features/invoice-generation Dodo Payments generates a branded invoice for every successful payment. Set the name and logo it shows, see what it contains, and download it. ![Invoice Generation Cover Image](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/cover-images/Invoice%20Generation.webp?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=d51414d96f53014f6374ddcce586559d) ## Overview Dodo Payments generates an invoice for every successful transaction, so you never create invoices by hand and every sale is documented the same way. After each payment, your customer receives a payment confirmation email with the receipt details and a **Download invoice** button. The invoice isn't attached to the email. The button opens the invoice PDF through a signed link that works for 30 days. When a payment has no invoice, the button is **View details** and opens the payment in the Customer Portal instead. > [!NOTE] > > Invoices are generated for both one-time purchases and recurring subscription payments. > [!TIP] > > To send an invoice before the customer pays, with payment terms such as Net 30, use [Invoice-Based Billing](/features/invoice-based-billing). ## Key Features > [card] Automatic Generation > > Dodo Payments creates the invoice when a payment succeeds, with no manual work. > [card] Custom Branding > > Each invoice shows your brand's name and logo, so it matches your other customer touchpoints. > [card] Email Delivery > > Customers receive a payment confirmation email with a link to download the invoice after each payment. > [card] Dashboard Management > > Download the invoice for any payment from its details page in the dashboard. ## Setting Up Invoice Branding An invoice shows the name and logo of the brand the payment belongs to. For a business with one brand, that is your primary brand. With several brands, set the name and logo on each brand. See [Multi-Brand Setup](/features/multi-brands). **1. Navigate to Business Settings** Open the Dodo Payments dashboard and go to **Settings** → **Business**. **2. Configure Branding** In the **Brands Under \[Your Business]** panel, open the brand's `...` menu and select **Edit**. Upload the **Brand Logo** and enter the **Brand Name**. Invoices for the brand's payments show these details. > [!TIP] > > Use a high-resolution logo (minimum 300x300px) in PNG format for the best print quality. > [!NOTE] > > **Accepted logo formats:** PNG, JPEG, GIF, WebP, ICO, and SVG. Any other format, AVIF included, is rejected at upload with a `422` error. WebP and ICO files are converted to PNG when the invoice is rendered, so they print correctly. Keep each side under 4096 pixels. If the invoice can't render the logo, it is generated without one. **3. Save Configuration** Click **Save Changes** to apply your branding. Invoices generated from then on use these details. > [!TIP] > > Your invoice branding is configured and applies to all new invoices. ## What's Included in Invoices Every generated invoice contains these transaction details: * **Business Information**: Your brand's name and logo, with the Dodo Payments entity that sells to your customer as the Merchant of Record * **Customer Details**: Customer name and billing address. For a business purchase with a tax ID, the customer's business name. * **Invoice Number**: A unique invoice ID for tracking and reference * **Transaction Date**: When the payment was processed, with the payment ID * **Payment Details**: Amount paid and currency * **Product/Service Description**: Itemized list of purchased products or subscriptions, with quantity, unit price, and tax for each line, plus any discount * **Tax Information**: Applicable taxes and tax identification numbers * **Payment Status**: **Paid** for a successful payment > [!NOTE] > > Dodo Payments generates the invoice ID automatically. It is unique to each invoice. ## How Invoice Generation Works > [tab] One-Time Purchases > > When a customer completes a one-time purchase: > > 1. The payment is processed successfully. > 2. Dodo Payments generates an invoice with the transaction details. > 3. The customer receives a payment confirmation email. > 4. The invoice is available on the payment's details page under **Transactions → Payments**. > > One-time purchase invoices include product details, pricing, and payment confirmation. > [tab] Subscription Renewals > > For recurring subscription payments: > > 1. The subscription renewal payment is processed automatically. > 2. Dodo Payments generates an invoice for the billing period. > 3. The customer receives a payment confirmation email. > 4. The invoice is stored with the renewal payment in your dashboard for your records. > > Subscription invoices list the subscription plan as a line item. They don't show the billing period or the next renewal date. ## Managing Invoices ### Accessing Your Invoices Invoices are attached to payments. To find one, go to **Transactions → Payments** in your Dodo Payments dashboard and open the payment. From there you can: * **View Invoice Details**: See the complete transaction information on the payment's details page. * **Download PDF**: Click **Invoice** in the top-right corner to download the invoice as a PDF. For a refund, open it under **Transactions → Refunds** and click **Download Refund Invoice**. * **Resend to Customer**: To send the customer's payment email again, use **Resend** on the customer's **Sent Emails** tab. See [Email Logs](/features/email-logs). * **Filter and Search**: Filter payments by date, status, or currency to find the invoices you need. To download an invoice in code, call [Get Invoice](/api-reference/payments/get-invoice) with the payment ID. The response is the PDF. > [!TIP] > > Filter payments by date to collect the invoices for an accounting period or a customer support request. ## Invoice Template Preview A branded invoice looks like this: ![Invoice template showing business branding, transaction details, and professional layout](https://mintcdn.com/dodopayments/OWlOkbdK5mDdUO5r/images/invoice-generation/image.png?fit=max\&auto=format\&n=OWlOkbdK5mDdUO5r\&q=85\&s=8fc207d1dd2f0cce16c315c5bf0d2a18) Example of a generated invoice with custom branding ## Related Features > [card] [Subscription Management](/features/subscription) > > Learn how subscriptions work with automatic recurring invoices. > [card] [Multi-Brand Support](/features/multi-brands) > > Manage multiple brands with separate invoice branding for each. > [card] [Customer Portal](/features/customer-portal) > > Let customers view and download their invoices in the Customer Portal. > [card] [Tax Configuration](/features/tax-inclusive-pricing) > > Configure tax settings so invoices display the correct tax information. # License Keys Source: https://docs.dodopayments.com/features/license-keys Issue license keys with activation limits and expiry through the License Key entitlement, then activate, validate, and deactivate them from your software. [License Keys | Dodo Payments](https://www.youtube.com/embed/BNuLTXok8dQ) > [!NOTE] > > License keys are the License Key entitlement type. Create a License Key entitlement once with the activation limit, expiry, and activation message you want, then attach it to any product. By default, Dodo Payments generates and emails one key for each unit purchased or each subscription seat. ## What Are License Keys? A license key is a unique token that authorizes access to your product. Use license keys for: * **Software licensing**: desktop apps, plugins, and CLIs. * **Per-seat controls**: limit activations per user or device. * **Digital goods**: gate downloads, updates, or premium features. Dodo Payments manages license keys through [Entitlements](/features/entitlements/introduction). The same payment and subscription events that drive your other entitlements drive each key's lifecycle: creation, expiry, revocation, and re-grant. ## Create a License Key Entitlement **1. Open Entitlements** Go to **Entitlements** in the dashboard and click **+** to create an entitlement. **2. Choose License Key** Select **License Keys**, enter a **Name**, and configure how each issued key behaves: * **Fulfillment Mode**: **Automatic** (the default) generates and emails each key. **Manual** lets you supply each key yourself. See [Manual Fulfillment](#manual-fulfillment). * **Activations Limit**: the maximum number of active activations per key, for example `1` for a single user or `5` for a team license. Select **Unlimited** for no limit. * **License Length**: how long a key stays valid after it's issued, for example 30 days or 1 year, or **No expiration**. For subscription products, choose **No expiration**: keys issued for a subscription have no expiry, and their validity follows the subscription status. * **Activation Message**: optional customer-facing instructions, up to 2,500 characters, included in the email that delivers the key. For example: `Paste the key in Settings → License` or `Run: mycli activate `. ![New License Key entitlement form with name, fulfillment mode, license length, activations limit, and activation message](https://mintcdn.com/dodopayments/sZYZEc6Biy3IrQNZ/images/entitlements/license-keys/create.png?fit=max\&auto=format\&n=sZYZEc6Biy3IrQNZ\&q=85\&s=65f24596e834387d0c35278ef92d14ea) **3. Save the Entitlement** Click **Create Entitlement**. You can now attach the entitlement to any product. ## Attach to Products Open a product, go to its **Entitlements** section, and select your License Key entitlement. One product can deliver a license key together with other entitlements on the same purchase, such as Discord access, file downloads, or GitHub repository access. ![Product entitlements panel with License Key selected](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/attach-to-product.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=965ad78262791fa8dbb712b4fdf89538) Selecting the License Key entitlement in the product entitlements panel. *** ## How Keys Are Issued Key issuance follows the standard [grant lifecycle](/features/entitlements/introduction#how-grants-work). Each event affects license keys as follows: | Event | Behavior | | - | - | | `payment.succeeded` (one-time) | Generates one key per unit of `quantity` purchased. Each key's expiry follows the entitlement's **License Length**. | | `subscription.active` | Generates one key per subscription seat (`quantity`). The keys have no expiry. Their validity follows the subscription status. | | `subscription.renewed` | No change. Existing keys stay active. | | `subscription.past_due` | No change. The keys stay active for the whole [grace period](/features/subscription#grace-period). | | `subscription.on_hold` | Disables the keys. They're re-enabled when the subscription comes off hold. | | `subscription.paused` | Disables the keys. They're re-enabled when the subscription is resumed. | | `subscription.cancelled` / `expired` | Disables the keys permanently. | | `subscription.plan_changed` | Disables the old keys and issues new ones for the new plan. | | `refund.succeeded` (one-time) | Disables the keys. | | Manual revoke through the API or dashboard | Disables the keys with `revocation_reason: manual`. These keys aren't re-granted automatically on subscription renewal. | | License key disabled directly | Revokes the grant with `revocation_reason: license_key_disabled`. Re-enabling the key restores the grant automatically. | ### Quantity Behavior The number of keys depends on where the grant comes from. Each key gets its own grant. * **Subscription products** issue one key per seat (`subscriptions.quantity`). * **One-time products** issue one key per unit of the cart line item (`product_cart.quantity`). * **Manual API grants** issue exactly one key. ### Fulfillment Mode Every License Key entitlement has a `fulfillment_mode` that controls who supplies the key: * **`auto`** (default, **Automatic** in the dashboard): Dodo Payments generates and emails the key on payment or subscription. This is the behavior in the table above, and it applies when `fulfillment_mode` is omitted. * **`manual`** (**Manual** in the dashboard): each unit purchased creates a `Pending` grant with no key, and you supply each key value. See [Manual Fulfillment](#manual-fulfillment). *** ## Manual Fulfillment With manual fulfillment, you supply each license key instead of Dodo Payments generating it. The purchase creates a `Pending` grant with no key, notifies you with a webhook, and waits for you to submit the key value. Use it when keys come from your own system, a third-party vendor, or a finite pool of pre-printed codes. > [!NOTE] > > For a step-by-step build, from product creation to key delivery, see the [Manual License Key Fulfillment Integration Guide](/developer-resources/manual-license-key-fulfillment). ### When to Use It Automatic fulfillment suits most software licensing. Choose manual fulfillment when Dodo Payments can't generate the key itself: * **Bring your own keys**: your application, a desktop product, or your own license server generates the key. * **Third-party vendors**: you resell keys that an upstream provider issues, such as a game key, an API credential, or a partner platform license. * **Finite inventory**: you hand out codes from a pre-allocated pool and assign them one at a time. * **Human review**: you want to check a purchase before you release access. ### Enable Manual Fulfillment To enable manual fulfillment through the API, set `fulfillment_mode: "manual"` in the License Key entitlement's `integration_config`. In the dashboard, set **Fulfillment Mode** to **Manual**. ```typescript Node.js expandable theme={null} // `client` is a DodoPayments instance created with your API key. const entitlement = await client.entitlements.create({ name: 'Pro License (Manual)', integration_type: 'license_key', integration_config: { fulfillment_mode: 'manual', activations_limit: 5, duration_count: 1, duration_interval: 'Year', }, }); ``` ```bash cURL expandable theme={null} curl -X POST https://test.dodopayments.com/entitlements \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Pro License (Manual)", "integration_type": "license_key", "integration_config": { "fulfillment_mode": "manual", "activations_limit": 5, "duration_count": 1, "duration_interval": "Year" } }' ``` > [!NOTE] > > `fulfillment_mode` is backward compatible. Entitlements created before this setting existed have no `fulfillment_mode` and behave as `auto`. Switching to `manual` affects only grants created **after** the change. Keys already delivered don't change. ### Find Grants Awaiting Fulfillment When a customer buys a product with a manual-mode entitlement, Dodo Payments creates the grant in `Pending` status with no key and sends an [`entitlement_grant.created`](/developer-resources/webhooks/intents/entitlement-grant) webhook with `integration_type: "license_key"` and `status: "Pending"`. React to that webhook, or poll the [List Customer Grants](/api-reference/entitlements/list-customer-grants) endpoint with the `integration_type` and `status` filters: ```typescript theme={null} const pending = await client.customers.listEntitlementGrants('cus_abc123', { integration_type: 'license_key', status: 'Pending', }); ``` ### Deliver the Key To deliver a key, send it to the [Fulfill License Key Grant](/api-reference/entitlements/fulfill-license-key) endpoint. The grant moves to `Delivered`, and Dodo Payments emails the key to the customer. It's the same email the customer receives under automatic fulfillment. ```bash cURL expandable theme={null} curl -X POST https://test.dodopayments.com/grants/entg_8VbC6JDZ/license-key \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "key": "PRO-AAAA-BBBB-CCCC-DDDD", "activations_limit": 5, "expires_at": "2027-05-01T00:00:00Z" }' ``` `activations_limit` and `expires_at` are optional. When you omit them, Dodo Payments uses the entitlement's configuration. Each grant can be fulfilled once: retrying an already-fulfilled grant returns `409` instead of issuing a second key. > [!TIP] > > You don't need to email the key yourself. Dodo Payments delivers it when the grant is fulfilled. [Importing keys](#import-existing-license-keys-via-api) with `POST /license_keys` works differently: it does **not** notify the customer. *** ## Activation, Validation, Deactivation Your software manages a key at runtime through three endpoints. Activation records a device or installation against the key, validation checks that the key is usable, and deactivation frees an activation. > [!NOTE] > > **Public Endpoints**: The activate, deactivate, and validate license endpoints are public and don't require an API key. Call them directly from desktop software, CLIs, or browser-based clients without exposing your API credentials. The SDK constructors still require a bearer token value, so the SDK examples pass a placeholder. ### Activate a License Activation creates an activation instance for the key and returns it with an `lki_` ID. Store that ID, because you need it to deactivate the instance. The request returns `403` if the key isn't active, `404` if the key doesn't exist, and `422` if the key has reached its activation limit. ```typescript TypeScript expandable theme={null} import DodoPayments from 'dodopayments'; // The license endpoints don't check the token, but the SDK requires a value. // Never ship your secret API key in client software. const client = new DodoPayments({ bearerToken: 'public', environment: 'test_mode' }); const response = await client.licenses.activate({ license_key: 'PRO-AAAA-BBBB-CCCC-DDDD', name: 'Device Name', }); console.log(response.id); ``` ```python Python expandable theme={null} from dodopayments import DodoPayments # The license endpoints don't check the token, but the SDK requires a value. client = DodoPayments(bearer_token="public", environment="test_mode") response = client.licenses.activate( license_key="PRO-AAAA-BBBB-CCCC-DDDD", name="Device Name", ) print(response.id) ``` ```bash cURL expandable theme={null} curl -X POST https://test.dodopayments.com/licenses/activate \ -H "Content-Type: application/json" \ -d '{ "license_key": "PRO-AAAA-BBBB-CCCC-DDDD", "name": "Device Name" }' ``` ### Validate a License Validation returns `valid: true` when the key's status is `active` and the key hasn't expired. To also check that a specific activation instance still exists, pass its `license_key_instance_id`. ```typescript TypeScript theme={null} // Uses the client from the activation example. const response = await client.licenses.validate({ license_key: 'PRO-AAAA-BBBB-CCCC-DDDD', }); console.log(response.valid); ``` ```bash cURL theme={null} curl -X POST https://test.dodopayments.com/licenses/validate \ -H "Content-Type: application/json" \ -d '{ "license_key": "PRO-AAAA-BBBB-CCCC-DDDD" }' ``` ### Deactivate an Activation Instance Deactivation removes an activation instance and frees one activation on the key. Pass the key and the instance ID that activation returned. The request returns `403` if the instance doesn't belong to the key, and `404` if the key doesn't exist. ```typescript theme={null} await client.licenses.deactivate({ license_key: 'PRO-AAAA-BBBB-CCCC-DDDD', license_key_instance_id: 'lki_abc123', }); ``` *** ## Manage Keys To see issued keys, open the License Key entitlement under **Entitlements**. The grants list shows one row per customer key, with the customer, the date accessed, the status, and a **Revoke** action. To see a key's expiry, activation count, and activation limit, open it under **Sales → License Keys**. To list grants programmatically, call List Grants. On each license-key grant, the `license_key` object carries the key, status, expiry, activations used, and activations limit. The object is `null` on a manual-mode grant that's still `Pending`. ```typescript theme={null} const grants = await client.entitlements.grants.list('ent_license_key_id', { status: 'Delivered', }); for (const grant of grants.items) { console.log(grant.license_key?.key, grant.license_key?.activations_used); } ``` ## Import Existing License Keys via API To migrate license keys from another system, import them with the [Create License Key](/api-reference/licenses/create-license-key) API. Your customers keep activating, validating, and deactivating the same key strings, so you don't need to reissue keys. > [!WARNING] > > License keys created or updated through the API do not trigger email notifications to customers. To tell customers about an imported key, notify them from your own application. The request requires `key`, `customer_id`, and `product_id`. Omit `activations_limit` for unlimited activations, and omit `expires_at` for a key that never expires. Importing a key string that already exists returns `409`. ```typescript theme={null} const licenseKey = await client.licenseKeys.create({ customer_id: 'cus_abc123', product_id: 'pdt_456', key: 'YOUR-EXISTING-LICENSE-KEY', activations_limit: 5, expires_at: '2026-12-31T23:59:59Z', }); ``` ### How Keys Differ by Source The `source` field records how each license key was created: | Field | Auto-generated key | Manually fulfilled key | Imported key | | - | - | - | - | | `source` | `"auto"` | `"manual"` | `"import"` | | Origin | Generated by Dodo Payments on payment | [Supplied by you](#manual-fulfillment) for a pending grant | Created or migrated with `POST /license_keys` | | `payment_id` | The originating payment | Resolved from the grant or its subscription | `null` (no Dodo Payments transaction) | | `subscription_id` | Set if issued through a subscription | Set if the grant came from a subscription | `null` (the import request has no subscription field) | | Customer email notification | Sent on issuance | Sent on fulfillment | Not sent. Notify the customer yourself | Use `source` to tell migrated and manually fulfilled keys apart from keys that Dodo Payments generated, for example when you reconcile or audit keys. The field is on license key records, such as the `POST /license_keys` response. The `license_key` object on grants from [List Grants](/api-reference/entitlements/list-grants) doesn't include it. The legacy `GET /license_keys` endpoint, which returns `source` and accepts a `source` filter, is deprecated. > [!TIP] > > Migrating from **Polar.sh** or **Lemon Squeezy**? The [`dodo-migrate` CLI](/migrate-to-dodo) imports products, customers, discounts, and license keys in bulk with a single command, and maps external IDs to Dodo Payments IDs. *** ## License Keys in Return URL When a customer buys a product with a License Key entitlement, Dodo Payments appends the generated key to your `return_url` as the `license_key` query parameter. Your success page can show the key without an extra API call: ```text theme={null} https://yoursite.com/return?payment_id=pay_xxx&status=succeeded&license_key=LK-001&email=customer%40example.com ``` If the purchase generates more than one key (quantity above 1), the parameter holds a comma-separated list. The comma is URL-encoded as `%2C`, so read the parameter with a URL parser, which decodes it, before you split it: ```text theme={null} https://yoursite.com/return?payment_id=pay_xxx&status=succeeded&license_key=LK-001%2CLK-002&email=customer%40example.com ``` For subscriptions, the URL carries `subscription_id` and the subscription status instead of `payment_id`: ```text theme={null} https://yoursite.com/return?subscription_id=sub_xxx&status=active&license_key=LK-001&email=customer%40example.com ``` > [!TIP] > > Read the `license_key` parameter on your return page to show the key right after purchase. *** ## API Management > [accordion] Lifecycle Operations (Public Endpoints) > > Activation, deactivation, and validation are public and require no API key. > > > [card] [Activate License](/api-reference/licenses/activate-license) > > > > Create an activation instance for a license key. > > > [card] [Deactivate License](/api-reference/licenses/deactivate-license) > > > > Remove an activation instance to free up capacity. > > > [card] [Validate License](/api-reference/licenses/validate-license) > > > > Check that a key is active and unexpired before you grant access. > [accordion] License Key Management > > Create, list, retrieve, and update individual license key records. Use these endpoints to import existing keys or read usage details. > > > [!WARNING] > > > > `GET /license_keys`, `GET /license_keys/{id}`, and `PATCH /license_keys/{id}` are deprecated. For reads, use the entitlement grant endpoints ([List Grants](/api-reference/entitlements/list-grants), [List Customer Grants](/api-reference/entitlements/list-customer-grants)). `POST /license_keys` remains supported for importing existing keys. > > > [card] [Create License Key](/api-reference/licenses/create-license-key) > > > > Create a license key or import an existing one. > > > [card] [List License Keys](/api-reference/licenses/list-license-keys) > > > > Browse all keys with status and usage details. > > > [card] [Get License Key](/api-reference/licenses/get-license-key) > > > > Retrieve a specific key and its metadata. > > > [card] [Update License Key](/api-reference/licenses/update-license-key) > > > > Change the expiry or activation limit, or enable or disable a key. > [accordion] Entitlement Management > > Manage the License Key entitlement itself: its activation limit, license length, and activation message. > > > [card] [Create Entitlement](/api-reference/entitlements/create-entitlement) > > > > Create a License Key entitlement. > > > [card] [Update Entitlement](/api-reference/entitlements/update-entitlement) > > > > Update the entitlement's configuration. > > > [card] [List Grants](/api-reference/entitlements/list-grants) > > > > List the keys issued for an entitlement. > > > [card] [Revoke Grant](/api-reference/entitlements/revoke-grant) > > > > Revoke a customer's key manually. *** ## Webhooks License key delivery and revocation send the four [`entitlement_grant.*` webhook events](/developer-resources/webhooks/intents/entitlement-grant). For license-key grants, the payload includes a `license_key` object with the key, status, expiry, activations used, and activations limit. The legacy `license_key.created` event still fires when a license key record is created. See the [License Key webhook payload page](/developer-resources/webhooks/intents/license-key). > [!TIP] > > For new integrations, handle entitlement grant events instead of `license_key.created`. An auto-fulfilled key arrives as `entitlement_grant.created` with `status: "Delivered"`, and no separate `entitlement_grant.delivered` event follows. A manually fulfilled key fires `entitlement_grant.delivered` when you supply it. The same events cover every entitlement on the product, not only the license key. *** ## Legacy License Keys > [!NOTE] > > Products created with the older `license_key_enabled` flag have been **automatically migrated** to a License Key entitlement. The migration is transparent: existing customers' keys keep working, the public `/licenses/activate`, `/licenses/validate`, and `/licenses/deactivate` endpoints keep working, and the `/license_keys/*` API endpoints read and write the same key store. > > The standalone **Sales → License Keys** dashboard section remains available as a flat list of every key issued, for audit and search. To change activation limits, license length, or the activation message, edit the migrated License Key entitlement under **Entitlements**. *** ## Best Practices * **Choose clear activation limits**: pick defaults such as 1 for single-user apps or 3–5 for team licenses, and document them for your customers. * **Write precise activation messages**: customers copy them from the license key email, so exact paths and commands prevent support tickets. * **Validate keys against the API**: for network-connected products, call `/licenses/validate` instead of relying on a locally cached activation. * **Use webhooks for revocation**: handle `entitlement_grant.revoked` to disable in-app features when a customer cancels or receives a refund. * **Test subscriptions and one-time purchases**: license key behavior differs between the two, for example subscription keys don't expire, so test both before you go live. # Localized Pricing Source: https://docs.dodopayments.com/features/localized-pricing Set your own fixed price for each currency or country instead of letting exchange rates decide. Charge round, market-tuned prices and run per-country promotions. ## What Is Localized Pricing? Every product has a base price in a base currency. Localized Pricing lets you override that base with **fixed prices you set per currency or per country**. Turn it on by setting a `pricing_mode` on the product, then attach one rule per market. It's one of several independent levers for international pricing, each solving a different problem: | Mechanism | What it does | The number the customer sees | | :- | :- | :- | | **Localized Pricing** | A fixed price you set per currency or country | Exactly the amount you set | | [**Adaptive Currency**](/features/adaptive-currency) | Automatically converts your base price at live FX rates | Base price converted at the current exchange rate | | [**Purchasing Power Parity**](/features/purchasing-power-parity) | Automatically charges a share of your price, by country | A percentage of the base price | | [**Charm Pricing**](/features/charm-pricing) | Automatically rounds the converted price to a clean ending | A tidy number such as 49.99 | | [**Discount codes**](/features/discount-codes) | A percentage or flat-amount reduction off the base price | Base price minus the discount | > [!NOTE] > > Localized Pricing and Adaptive Currency work together. When no localized rule matches, the product falls back to its base price — charged directly if the customer is already in your base currency, or converted through Adaptive Currency if not. *** ## Use Cases > [card] Exact Prices for One Market > > Charge a specific amount in a price-sensitive market. A `by_country` rule lets a \$20 base product sell for **₹999 in India** — the exact number you chose, not an FX conversion. To reduce prices by country automatically instead, use [Purchasing Power Parity](/features/purchasing-power-parity). > [card] Exact Prices per Currency Zone > > A live FX conversion of \$19.99 lands on an awkward number like €18.43. A `by_currency` rule sets the exact price you type — **€9.99**, **¥1000**, **₹499**. To round converted prices to clean endings automatically, in every currency, use [Charm Pricing](/features/charm-pricing). > [card] Reversible Market-Entry Promotions > > Launching in a new country? Add a `by_country` rule with an introductory price, then **archive it** when the promotion ends to fall back to base/adaptive pricing. Rules are archived, never deleted, so you keep a clean record of what was live and when. > [card] Competitive Price-Matching > > Pin a single market to match a local competitor. A `by_country` rule for **£9.00 in the United Kingdom** holds that exact price regardless of how the GBP/USD rate moves. ## Core Concepts * **Pricing modes** — A product is in exactly one mode at a time, set by its `pricing_mode`: * `by_currency`: one price per currency, regardless of country. Everyone paying in EUR sees €9.99. * `by_country`: a price specific to a country (₹999 in India), even when several countries share a currency. * **Fixed amounts, in the smallest unit** — A rule's `amount` is an integer in the currency's smallest unit, the same as everywhere else in the API: `99900` is ₹999.00, `999` is €9.99. It's a price you set, never a converted value. * **A matched rule wins over automatic pricing** — When a localized rule applies to a line, [Purchasing Power Parity](/features/purchasing-power-parity) and [Charm Pricing](/features/charm-pricing) are both skipped for that line. At checkout, the customer pays the amount you set, unchanged. On a subscription plan change, a rule in a different currency from the subscription is converted; see [How It Applies on Subscription Plan Changes](#how-it-applies-on-subscription-plan-changes). * **When no rule matches** — The product keeps its existing behavior: customers in your base currency pay the base price directly; everyone else gets it converted through [Adaptive Currency](/features/adaptive-currency). * **Fees are inclusive when a rule matches** — The customer pays exactly the amount you set. The [Adaptive Currency](/features/adaptive-currency#enable-fees-inclusive) FX fee is absorbed by you (treated as fees-inclusive for that transaction) rather than added on top, so your stated local price is always the price charged. ## Set Up in the Dashboard **1. Open the product form** In your Merchant Dashboard, go to **Products** and create a product (or open an existing one to edit). Set the base **Price** and currency as usual. **2. Enable Localized Pricing and choose a mode** In the **Pricing** section, tick **Localized Pricing**, then choose **By Country** or **By Currency**. ![Localized Pricing enabled on the product form with By Country selected](https://mintcdn.com/dodopayments/hpHKp5MybOFgIhM2/images/localized-pricing/pricing-section.png?fit=max\&auto=format\&n=hpHKp5MybOFgIhM2\&q=85\&s=933fc68155db9639d36d624c0f84dfee) **3. Add a price for each market** Click **Add Country Price** or **Add Currency Price**, fill in the **Localized pricing** panel, and click **Add**. Each market you add appears in the overrides table, where you can edit or remove it later. > [tab] By Country > > Pick a country, choose the currency, and enter the amount (for example ₹999 for India), then click **Add**. > > ![Adding a 999 INR override for India](https://mintcdn.com/dodopayments/hpHKp5MybOFgIhM2/images/localized-pricing/add-country-override.png?fit=max\&auto=format\&n=hpHKp5MybOFgIhM2\&q=85\&s=62ae6975abd9c023655126a02fab611d) > > The country now appears in the **Country overrides** table, where you can edit or remove it. > > ![Country overrides table showing India at 999 INR](https://mintcdn.com/dodopayments/hpHKp5MybOFgIhM2/images/localized-pricing/country-overrides-table.png?fit=max\&auto=format\&n=hpHKp5MybOFgIhM2\&q=85\&s=1ef8ef7f6368448896015febccd11b58) > [tab] By Currency > > Pick a currency and enter the amount (for example €9.99 for EUR), then click **Add**. > > ![Adding a 9.99 EUR override](https://mintcdn.com/dodopayments/hpHKp5MybOFgIhM2/images/localized-pricing/add-currency-override.png?fit=max\&auto=format\&n=hpHKp5MybOFgIhM2\&q=85\&s=8f4b14e3c0ba37b2162cc45fc7b199eb) > > The currency now appears in the **Currency overrides** table, where you can edit or remove it. > > ![Currency overrides table showing EUR at 9.99](https://mintcdn.com/dodopayments/hpHKp5MybOFgIhM2/images/localized-pricing/currency-overrides-table.png?fit=max\&auto=format\&n=hpHKp5MybOFgIhM2\&q=85\&s=ed713ac592444f1685f2fa75de2e8b3f) **4. Save the product** Save with **Add product**. Localized prices apply to future checkouts immediately. > [!TIP] > > Run a test checkout with a billing country that has a rule, and confirm the localized amount appears. ## Manage via API Localized Pricing is fully available over the API. First set the product's pricing mode, then attach rules. ### Set the Pricing Mode Set `pricing_mode` when you create the product (or update an existing one). `null` means base-only, the existing behavior. ```typescript theme={null} theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', }); await client.products.update('pdt_premium_plan', { pricing_mode: 'by_country', }); ``` ```python theme={null} theme={null} import os from dodopayments import DodoPayments client = DodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), environment="test_mode", ) client.products.update( "pdt_premium_plan", pricing_mode="by_country", ) ``` ```go theme={null} theme={null} package main import ( "context" "os" "github.com/dodopayments/dodopayments-go" "github.com/dodopayments/dodopayments-go/option" ) func main() { client := dodopayments.NewClient( option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), ) err := client.Products.Update( context.TODO(), "pdt_premium_plan", dodopayments.ProductUpdateParams{ PricingMode: dodopayments.F(dodopayments.PricingModeByCountry), }, ) if err != nil { panic(err) } } ``` ### Add a Localized Price Attach a rule to the product. In `by_country` mode `country_code` is required; in `by_currency` mode it must be omitted. ```typescript theme={null} theme={null} // ₹999.00 for customers in India const localizedPrice = await client.products.localizedPrices.create('pdt_premium_plan', { currency: 'INR', country_code: 'IN', amount: 99900, }); ``` ```python theme={null} theme={null} # ₹999.00 for customers in India localized_price = client.products.localized_prices.create( "pdt_premium_plan", currency="INR", country_code="IN", amount=99900, ) ``` ```go theme={null} theme={null} // ₹999.00 for customers in India localizedPrice, err := client.Products.LocalizedPrices.New( context.TODO(), "pdt_premium_plan", dodopayments.ProductLocalizedPriceNewParams{ Currency: dodopayments.F(dodopayments.CurrencyInr), CountryCode: dodopayments.F(dodopayments.CountryCodeIn), Amount: dodopayments.F(int64(99900)), }, ) ``` For a `by_currency` product, omit `country_code`. For example, a flat `€9.99` for everyone paying in EUR (`currency: 'EUR'`, `amount: 999`). ### List, Update, and Archive You can update only a rule's `amount`; currency and country are fixed once created. Archiving is an idempotent soft-delete, so the rule stops matching but stays in your history. ```typescript theme={null} theme={null} // List all active rules on a product const rules = await client.products.localizedPrices.list('pdt_premium_plan'); // Change the amount (e.g. end a promo) await client.products.localizedPrices.update('lcp_india_price', { product_id: 'pdt_premium_plan', amount: 119900, }); // Archive a rule await client.products.localizedPrices.archive('lcp_india_price', { product_id: 'pdt_premium_plan', }); ``` ```python theme={null} theme={null} # List all active rules on a product rules = client.products.localized_prices.list("pdt_premium_plan") # Change the amount (e.g. end a promo) client.products.localized_prices.update( "lcp_india_price", product_id="pdt_premium_plan", amount=119900, ) # Archive a rule client.products.localized_prices.archive( "lcp_india_price", product_id="pdt_premium_plan", ) ``` ```go theme={null} theme={null} // List all active rules on a product _, err := client.Products.LocalizedPrices.List(context.TODO(), "pdt_premium_plan") // Change the amount (e.g. end a promo) _, err = client.Products.LocalizedPrices.Update( context.TODO(), "pdt_premium_plan", "lcp_india_price", dodopayments.ProductLocalizedPriceUpdateParams{ Amount: dodopayments.F(int64(119900)), }, ) // Archive a rule err = client.Products.LocalizedPrices.Archive( context.TODO(), "pdt_premium_plan", "lcp_india_price", ) ``` > [card] [API Reference](/api-reference/products/post-products-localized-prices) > > See the full Product Localized Prices endpoints: create, list, retrieve, update, and archive. ## How It Applies at Checkout Localized pricing is resolved per cart line, and only for products that have a `pricing_mode` set. Dodo Payments reads two signals from the request: the customer's **billing country**, and an optional **`billing_currency`** (when omitted, a currency is derived from the billing country). * **By Country**: looks for a rule matching the billing country. If one exists, the customer is charged the rule's amount in the rule's currency. * **By Currency**: looks for a rule matching the customer's currency (the `billing_currency`, or the currency derived from their country). If one exists, the customer is charged the rule's amount in that currency. * **No match, or no `pricing_mode`**: the base price applies, charged directly when the customer's currency equals the base currency, otherwise converted through [Adaptive Currency](/features/adaptive-currency). Each cart line is resolved on its own, so you can localize one product and leave others on base pricing in the same checkout. If any line matches a localized rule, the whole transaction is forced fees-inclusive (see [Core Concepts](#core-concepts)). ## How It Applies on Subscription Plan Changes Localized pricing follows your subscribers when they switch plans. When an existing subscription [changes plan](/features/subscription#subscription-plan-changes) into a product that has a `pricing_mode`, the new plan's price is resolved with the same rules as checkout, using the billing country and currency already locked on the subscription: * **By Country**: a rule matching the subscription's billing country applies. If the rule's currency differs from the currency the subscription is billed in, the rule's amount is converted at live FX rates — the rule is applied, not skipped. * **By Currency**: a rule matching the currency the customer is billed in applies, and the customer is charged exactly the rule's amount. * **No match, or no `pricing_mode`**: the new plan's base price applies, converted through [Adaptive Currency](/features/adaptive-currency) when needed — the same fallback as checkout. This holds everywhere a plan change can originate: the [Change Plan API](/api-reference/subscriptions/change-plan), the [Customer Portal](/features/customer-portal)'s self-service plan changes, and changes scheduled for the end of the billing period. * **Previews are exact.** [Preview Change Plan](/api-reference/subscriptions/preview-change-plan) returns the same localized amount the actual change charges. * **Renewals keep the localized price.** After the change, the new plan renews at its localized amount — and stays fees-inclusive — exactly like a subscription created at that price. * **Proration uses real amounts.** On an upgrade, the credit for unused time is based on what the customer actually paid for the old plan, while the new plan is priced by its localized rule. * **Scheduled changes lock the price when scheduled.** A change scheduled for the end of the billing period charges the amount calculated at scheduling time, even if you edit the rule in between. * **The billing currency never changes.** A plan change never switches the currency a subscription settles in; a rule in another currency is FX-converted into it. * **Add-ons are not localized.** Add-on prices on the new plan always use their base pricing. ## Important Behaviors | Behavior | Detail | | :- | :- | | **Pre-tax amounts** | A localized amount is the price before tax. For tax-exclusive products, tax is added on top at checkout, so the localized amount is not the final total. See [Tax-Inclusive Pricing](/features/tax-inclusive-pricing). | | **Not for Pay What You Want** | Localized rules never apply to [Pay What You Want](/features/pay-what-you-want) products, where the customer chooses the amount. | | **By-currency differs from base** | A `by_currency` rule must use a currency different from the product's base currency. | | **One rule per market** | A product can have at most one active rule per currency (by-currency) or per country (by-country). | | **One-time and subscription products** | Applies to one-time and subscription products — including when an existing subscriber [changes plan](#how-it-applies-on-subscription-plan-changes). Usage-based prices don't support Localized Pricing. | > [!NOTE] > > Localized rule changes do not emit their own webhooks. The resolved amount appears on the resulting payment or subscription exactly like any other price. ## Best Practices * **Keep a sensible base price.** It is the fallback for every market without a rule, converted through Adaptive Currency. * **Type clean numbers.** The whole point of a fixed amount is a tidy price like ₹999, €9.99, or ¥1000, not an FX result. For automatic rounding across every currency, see [Charm Pricing](/features/charm-pricing). * **Pick the mode for the job.** Use `by_country` for purchasing-power pricing; use `by_currency` when one price per currency zone is enough. * **Archive, don't recreate, for promotions.** Archiving a rule reverts the market to base/adaptive while preserving history; recreate or re-price later as needed. * **Mind the tax line before advertising a total.** For tax-exclusive products the customer pays the localized amount *plus* tax, so don't quote it as the final price in ads. *** ## Related > [card] [Purchasing Power Parity](/features/purchasing-power-parity) > > Reduce prices by country automatically, with one percentage per country. > [card] [Charm Pricing](/features/charm-pricing) > > Round converted prices to clean endings such as 49.99, in every currency. > [card] [Adaptive Currency](/features/adaptive-currency) > > Automatic FX conversion and the fee handling localized pricing builds on. > [card] [Tax-Inclusive Pricing](/features/tax-inclusive-pricing) > > Control whether your prices include tax. > [card] [Pay What You Want](/features/pay-what-you-want) > > Let customers choose the amount. Localized rules do not apply there. # Moderation API Source: https://docs.dodopayments.com/features/moderation Screen prompts and images before your AI product generates, and get an allow, flag, or deny verdict with a score for 17 content categories. > [card] [Screen a Prompt](/api-reference/moderation/screen) > > Send text, an image, or both, and get a verdict. > [card] [Get Moderation Usage](/api-reference/moderation/get-usage) > > See your billable screens and your next charge. ## Overview The Moderation API screens user input before your AI product generates from it. You send the text of a prompt, an image, or both, and Dodo Payments returns a verdict of `allow`, `flag`, or `deny`, together with a score for each content category. Use it in front of any image, video, or text generation model that takes input from your users. The Moderation API is on for every business by default and runs with your existing Dodo Payments API key, so there is nothing to sign up for. Dodo Payments can turn it off for an individual business, and calls then return `403` with `MODERATION_DISABLED`. ## Why We Built the Moderation API An AI generation product creates new content from whatever its users type. You cannot review each prompt by hand, and one harmful output can put your business at risk. As your Merchant of Record, Dodo Payments is legally and reputationally responsible for what is sold through the platform. The [Merchant Acceptance Policy](/miscellaneous/merchant-acceptance) reviews AI content generation tools and does not allow impersonation, deepfakes, or explicit content, including AI-generated content. An account that generates harmful content, excessive chargebacks, or flags from payment partners can be placed under review or suspended. We built the Moderation API so that you can stop this content before your model creates it: * **Screen before you generate.** A blocked prompt never reaches your model, so no harmful output exists and you spend no compute on it. * **Cover the categories that matter for generation.** The screen scores 17 categories, including real-person likeness, non-consensual intimate imagery, minor-coded language, and the combination of a real person with sexual content that marks a sexual deepfake. * **Integrate without another vendor.** The API runs with your Dodo Payments API key, and its fee is debited from your balance. There is no separate contract, invoice, or account. * **Keep user content private.** Dodo Payments does not store or log the text and images you screen. > [!NOTE] > > The Moderation API is a tool for your own enforcement. It does not replace the Merchant Acceptance Policy, and you remain responsible for what your product generates. ## How It Works Call the Moderation API from your backend after the user submits a prompt and before your model runs: ```mermaid theme={null} flowchart LR A[User submits a prompt] --> B[Your backend calls POST /moderation/screen] B -->|allow| C[Generate] B -->|flag| D[Apply your own policy] B -->|deny| E[Block the request] B -->|error, no verdict| E ``` Each call is one **screen**. Text and an image sent in the same call count as one screen. ### Verdicts The `decision` field carries the verdict: | Verdict | Meaning | What to do | | - | - | - | | `allow` | The content passed. | Generate. | | `flag` | The content crossed a category threshold that calls for judgement. It is not a soft deny. | Apply your own policy. You can block, send to review, or generate. | | `deny` | The content must not be generated. | Block the request and show the user an error. | > [!WARNING] > > Do not generate when you receive no verdict. A `503` means Dodo Payments could not produce a verdict, and a timeout or network error leaves you without one. Treat all of these as a block and ask the user to try again. ## Screening a Prompt To screen a prompt, send a `POST` request to `/moderation/screen` with at least one of `text` and `image`. The request accepts three fields: | Field | Type | Description | | - | - | - | | `text` | string | The text to screen, up to 8,000 characters. | | `image` | string | The image to screen, as base64, with or without a `data:image/...;base64,` prefix. | | `request_id` | string | Optional. Your identifier for this screen, such as a generation ID, up to 128 characters with no control characters. The response returns it unchanged. | The TypeScript and Python SDKs expose the endpoint as `client.moderation.screen()`. This example blocks generation on `deny`, on `flag`, and on any error: > [!NOTE] > > The examples call live mode, because only live mode runs the moderation model. Test mode returns [mock verdicts](#testing-your-integration) and never screens the content. Live mode screens are billed. ```typescript Node.js expandable theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', }); async function generateImage(prompt: string, generationId: string) { let verdict; try { verdict = await client.moderation.screen({ text: prompt, request_id: generationId, }); } catch (err) { // No verdict: do not generate. throw new Error('Moderation is unavailable. Try again in a moment.'); } if (verdict.decision !== 'allow') { throw new Error('This prompt cannot be generated. Revise it and try again.'); } return myModel.generate(prompt); } ``` ```python Python expandable theme={null} import os from dodopayments import DodoPayments, APIError client = DodoPayments( bearer_token=os.environ["DODO_PAYMENTS_API_KEY"], environment="live_mode", ) def generate_image(prompt: str, generation_id: str): try: verdict = client.moderation.screen(text=prompt, request_id=generation_id) except APIError: # No verdict: do not generate. raise RuntimeError("Moderation is unavailable. Try again in a moment.") if verdict.decision != "allow": raise ValueError("This prompt cannot be generated. Revise it and try again.") return my_model.generate(prompt) ``` ```bash cURL theme={null} curl -X POST https://live.dodopayments.com/moderation/screen \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "text": "a watercolor painting of a lighthouse at sunset", "request_id": "gen_7Hc2k9" }' ``` The example treats `flag` like `deny`. If your product allows some flagged content, check `triggered` to decide by category instead. > [!TIP] > > Screen the text your user wrote, not the prompt template you wrap around it. Your own template is the same on every call and adds nothing to the screen. ### Screening Images Send an image to screen an uploaded reference image, or a generated image before you show it. The image must meet these requirements: * The format is JPEG, PNG, WebP, GIF, or BMP. * The base64 string is at most 6,991,530 characters, and the decoded image is at most 5 MiB. * The image is a single still frame. Animated GIF and WebP images are rejected. * The longest edge is at least 32 pixels. An image that fails one of these checks returns `400` with `MODERATION_INVALID_IMAGE`, or `413` with `MODERATION_INPUT_TOO_LARGE` when it is too large. To screen an image, read the file, encode it as base64, and send it in `image`. To screen an image and its prompt together, send both `text` and `image` in the same call. It counts as one screen. This example uses the `client` from the previous example: ```typescript Node.js expandable theme={null} import { readFile } from 'node:fs/promises'; async function screenImage(path: string, prompt: string, generationId: string) { const image = (await readFile(path)).toString('base64'); const verdict = await client.moderation.screen({ image, // or `data:image/png;base64,${image}` text: prompt, // optional: screen the prompt with the image request_id: generationId, }); return verdict.decision === 'allow'; } ``` ```python Python expandable theme={null} import base64 def screen_image(path: str, prompt: str, generation_id: str) -> bool: with open(path, "rb") as f: image = base64.b64encode(f.read()).decode("ascii") verdict = client.moderation.screen( image=image, # or f"data:image/png;base64,{image}" text=prompt, # optional: screen the prompt with the image request_id=generation_id, ) return verdict.decision == "allow" ``` ```bash cURL expandable theme={null} # Builds the JSON body with jq, so a large image does not hit the shell argument limit. base64 < reference.png | tr -d '\n' \ | jq -Rs '{image: ., text: "turn this photo into a watercolor painting", request_id: "gen_7Hc2k9"}' \ | curl -X POST https://live.dodopayments.com/moderation/screen \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ --data @- ``` Handle errors from an image screen the same way as a text screen: if the call throws, do not generate. ## Reading the Response The response returns the verdict and the evidence behind it: | Field | Description | | - | - | | `decision` | The verdict: `allow`, `flag`, or `deny`. | | `triggered` | The categories whose score crossed the threshold of the category. It can be empty on a `flag` from the general check. | | `compound_triggered` | `true` when real-person likeness and sexual content together crossed their combined threshold, the pattern of a sexual deepfake. | | `categories` | The probability, from 0 to 1, that the content falls in each category. | | `provenance` | How each score was measured: `targeted` by a check for that one category, or `broad` by the general check that covers all categories. | | `notes` | Human-readable reasons for the decision. The wording can change, so do not parse it. | | `normalized_applied` | `true` when the text was also screened with obfuscation removed, such as invisible or look-alike characters. | | `passes` | The number of yes/no questions the model answered for this screen. | | `latency_ms` | The time the screen took, in milliseconds. | | `request_id` | The `request_id` you sent, or `null`. | Base your logic on `decision` and `triggered`. Each category has its own threshold, so a single score cut-off in your code does not match the verdict. ### Categories Every response scores the content against 17 categories: | Category | Covers | | - | - | | `violent_crimes` | Violent crimes. | | `sex_related_crimes` | Sex-related crimes. | | `child_sexual_exploitation` | Child sexual exploitation. | | `suicide_and_self_harm` | Suicide and self-harm. | | `indiscriminate_weapons` | Chemical, biological, radiological, nuclear, or explosive weapons. | | `intellectual_property` | Copyright or trademark infringement. | | `defamation` | False depiction that is likely to injure the reputation of a real person. | | `non_violent_crimes` | Non-violent crimes. | | `hate` | Demeaning people because of a protected characteristic. | | `privacy` | Sensitive private information about a person. | | `specialized_advice` | Unqualified financial, medical, legal, or electoral advice. | | `sexual_content` | Sexually explicit or pornographic content. | | `non_consensual_intimate_imagery` | Undressing, nudifying, or sexualizing a real person. | | `minor_coded_language` | Age-coded language that suggests the subject is a minor. | | `real_person_likeness` | The likeness of a real, identifiable, named person. | | `living_artist_style` | Imitation of the signature style of a specific living artist. | | `prompt_injection` | An attempt to override or manipulate the instructions of the system. | ## Handling Errors Errors return the standard Dodo Payments error body with a `code` and a `message`. No error is a verdict, so none of them allow generation: | Status | `code` | Cause | What to do | | - | - | - | - | | `400` | `INVALID_REQUEST_PARAMETERS` | The request is malformed, or it has neither `text` nor `image`. | Fix the request. | | `400` | `MODERATION_INVALID_IMAGE` | The image cannot be decoded, is animated, or is too small. | Send a supported still image. | | `403` | `MODERATION_DISABLED` | Dodo Payments has turned off the Moderation API for your business. | Contact support to find out why. | | `403` | `MERCHANT_NOT_LIVE` | Live mode screens need a business with live mode and live payments enabled. | Complete verification for live payments, or test in test mode. | | `403` | `BUSINESS_ARCHIVED` | The business is archived. | Use an active business. | | `413` | `MODERATION_INPUT_TOO_LARGE` | `text` is over 8,000 characters, or `image` is over 6,991,530 base64 characters or the 5 MiB decoded limit. | Shorten the text or shrink the image. | | `413` | `INVALID_REQUEST_BODY` | The request body is over 8 MiB. | Shrink the image. | | `429` | `MODERATION_OVERLOADED` | Moderation is at capacity. This is a throughput limit, not a verdict. | Wait for the seconds in the `Retry-After` header, then retry. | | `503` | `MODERATION_UNAVAILABLE` | No verdict is available, for example because the moderation model did not answer within 5 seconds. | Do not generate. Retry later. | The SDKs retry a `429` or a `503` twice by default and wait for `Retry-After` between attempts. When the retries run out, the SDK raises an error, and your code must block the request. ## Testing Your Integration Test mode returns mock verdicts and never calls the moderation model, so you can test your routing without cost. Send requests to `https://test.dodopayments.com` with a test mode API key. The default mock verdict is `allow`. To get another outcome, put one of these strings anywhere in `text`: | String in `text` | Response | | - | - | | `dodo_mock_flag` | `200` with `decision` set to `flag` | | `dodo_mock_deny` | `200` with `decision` set to `deny` | | `dodo_mock_overloaded` | `429` `MODERATION_OVERLOADED` with `Retry-After: 1` | | `dodo_mock_not_ready` | `503` `MODERATION_UNAVAILABLE` | A mock verdict carries a note that says it is a mock, and all its category scores are `0`. Test mode applies the same request validation as live mode. For images, it checks the base64 encoding and the format, but not the frame count or the dimensions. Before you go live, confirm that your integration handles each case: **1. Deny Blocks Generation** Send `dodo_mock_deny` and confirm your model is not called. **2. Flag Follows Your Policy** Send `dodo_mock_flag` and confirm your product does what your policy says. **3. Overload Retries** Send `dodo_mock_overloaded` and confirm your code waits for `Retry-After` and does not generate without a verdict. **4. An Outage Blocks Generation** Send `dodo_mock_not_ready` and confirm your model is not called. **5. Every Generation Path Screens** Check that every code path that reaches your model calls the Moderation API first. ## Pricing and Billing The Moderation API costs **\$0.30 USD per 1,000 billable screens**. There is no free tier and no minimum. A billable screen is a live mode screen that returns a verdict. These screens are free and not counted: * Screens in test mode. * Screens that return an error, including `429` and `503`. Dodo Payments bills in full blocks of 1,000 screens. Each full block is charged within one hour, and screens that do not fill a block stay unbilled until they do. The fee is debited from your USD balance and appears in your [balance ledger](/api-reference/balance-ledger/list-ledger-entries) with the event type `moderation_fees`. Payouts show it under **Moderation Fees**. ### Tracking Usage To see your usage, call `GET /moderation/usage`. The response returns: | Field | Description | | - | - | | `unbilled_screens` | Billable screens that Dodo Payments has not charged for yet. | | `screens_to_next_block` | Billable screens still needed to fill the next block of 1,000. | | `daily` | Your billable screens per UTC day for the last 30 days. Days with no screens are omitted. | ```bash cURL theme={null} curl https://live.dodopayments.com/moderation/usage \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" ``` ```typescript Node.js theme={null} const usage = await client.moderation.retrieveUsage(); console.log(usage.unbilled_screens, usage.screens_to_next_block); ``` ```python Python theme={null} usage = client.moderation.retrieve_usage() print(usage.unbilled_screens, usage.screens_to_next_block) ``` Test mode records no screens, so the usage endpoint returns no test mode activity. ## Access and Privacy Screening requires an API key with **Write** access to **Moderation**. A key with **Read** access to Moderation can read usage. See [Authentication](/api-reference/introduction#authentication) for how to create a key and set its access level. Access is controlled by the `moderation` permission resource: `POST /moderation/screen` needs `moderation` write, and `GET /moderation/usage` needs `moderation` read. Among the predefined team roles, Developer has read and write access, and Finance has read access. Dodo Payments does not store the text or images you screen, and does not write them to logs. For each live mode screen, it keeps the time, the verdict, and your `request_id` for billing and usage reporting. Billed screens are deleted after 30 days. Screens that are not billed yet are kept until they are billed. > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Charge your own customers for each generation. > [card] [Credit-Based Billing](/features/credit-based-billing) > > Sell generation credits and deduct them per use. # Multi-Brand Setup Source: https://docs.dodopayments.com/features/multi-brands Run several brands under one verified business, each with its own name, logo, statement descriptor, and URL, and archive the brands you retire. ## Introduction Multi-Brand lets you run several brands under **one verified business**. Each brand has its own name, logo, statement descriptor, and URL. Your payout account, fees, and KYC stay shared at the business level, while each product, payment link, subscription, invoice, and transaction is filed under a specific brand. Use brands to test a new niche, run a localized site, or separate B2B and B2C product lines without opening another business account. A brand that needs its own legal entity, KYC, or payout account needs a separate business instead. See [Managing Multiple Businesses](/miscellaneous/accounts#managing-multiple-businesses). ## Merchant Dashboard Flow **1. Open Settings → Business** Go to **Settings → Business**. The **Brands Under \[Your Business]** panel lists your **Primary Brand** and any **Secondary Brands**. ![Brands panel in Business Settings showing primary and secondary brands with a plus button to add a new brand](https://mintcdn.com/dodopayments/3S7hokVaWJ76F6RN/images/multi-brands/brands-section.png?fit=max\&auto=format\&n=3S7hokVaWJ76F6RN\&q=85\&s=2ed50b75aa2c14dee5214b7abbbbc17a) **2. Click the + Button** In the Brands panel, click the **+** button in the top-right corner to open the new brand form. **3. Fill In the Brand Details** Complete the following fields: * **Brand Name** (required): At least 2 characters, and different from the names of your other brands. * **Support Email**: The address customers use to contact support for this brand. * **Brand Description** (required): At least 10 characters. Describe the brand, its products, and what makes it distinct. * **Brand Logo**: Represents the brand on checkout, invoices, and payment links. Accepted formats are PNG, JPEG, GIF, WebP, ICO, and SVG. Any other format is rejected with a `422` error. Click **Add brand** to create the brand. You can then assign products to it, and its payment links show its branding. To set the statement descriptor or change other details later, open the brand's `...` menu and select **Edit**. **4. Select the Brand on Products** When you create a product, choose its brand in the **Brand** field. **5. Find the Brand ID in Transactions** Transactions and subscriptions show a **Brand ID**, so you can tell which brand each one belongs to. ## Additional Points * **No payout changes:** Funds, payout cycles, and fees stay at the business level and flow to the business wallet and your bank account. * **Brand ID on webhooks:** Payment, subscription, refund, license key, credit ledger entry, credit balance low, entitlement grant, dunning attempt, and abandoned checkout payloads include a `brand_id`, so you can attribute each event to a brand. When an entity has no brand of its own, `brand_id` is the business's primary brand. Dispute payloads carry no `brand_id`, so use their `payment_id` to find the brand on the payment. Payout payloads are business-level and carry no `brand_id`. * **Suspensions:** If a brand is suspended, it can't take new payments, checkout sessions, or subscriptions. Other brands under the same business keep transacting. * **Invoices:** Each invoice shows the name and logo of the brand the payment belongs to. * Storefront, license keys, discount codes, payout settings, and other business-level features work the same as with a single brand. ## Archiving a Brand Archive a brand you no longer sell under. Archiving retires the brand and moves its products, live subscriptions, and product collections to another brand of the same business in one step. > [!WARNING] > > Archiving a brand is permanent. An archived brand can't be restored. ### Archive a Brand from the Dashboard **1. Open the Brand's Actions Menu** Go to **Settings → Business**. In the **Brands Under \[Your Business]** panel, open the `...` menu next to the secondary brand and select **Archive**. The primary brand has no **Archive** option. ![Brand actions menu showing the Edit and Archive options for a secondary brand](https://mintcdn.com/dodopayments/akjF3bAc8rAIIGgT/images/multi-brands/archive-brand-menu.png?fit=max\&auto=format\&n=akjF3bAc8rAIIGgT\&q=85\&s=f5d847f7ffb500dabb76d6662b083f61) **2. Confirm the Archive** Read the warning and select **Continue**. ![Dialog warning that the brand cannot be restored once archived](https://mintcdn.com/dodopayments/akjF3bAc8rAIIGgT/images/multi-brands/archive-brand-confirm.png?fit=max\&auto=format\&n=akjF3bAc8rAIIGgT\&q=85\&s=019cb0f7de415928e0676ed1147187ea) **3. Choose the Brand That Takes Over** In **Move products to**, select the brand that receives the products, live subscriptions, and collections. The primary brand is the default. Select **Move & Archive** to move the records and archive the brand in one action. ![Dialog to choose the brand that receives the archived brand's records](https://mintcdn.com/dodopayments/akjF3bAc8rAIIGgT/images/multi-brands/archive-brand-target.png?fit=max\&auto=format\&n=akjF3bAc8rAIIGgT\&q=85\&s=b6e9d6e759ee52cd4212bfd4563b7b91) **4. Check the Result** The confirmation names the brand that received the records. ![Confirmation that the brand is archived and its products moved to the target brand](https://mintcdn.com/dodopayments/akjF3bAc8rAIIGgT/images/multi-brands/archive-brand-done.png?fit=max\&auto=format\&n=akjF3bAc8rAIIGgT\&q=85\&s=085d39b165d0b475ac96de829d275a3e) The archived brand leaves the Brands panel. When the business has no other secondary brand, the **Secondary Brands** group disappears with it. ![Brands panel after the archive, showing only the primary brand](https://mintcdn.com/dodopayments/akjF3bAc8rAIIGgT/images/multi-brands/archive-brand-panel-after.png?fit=max\&auto=format\&n=akjF3bAc8rAIIGgT\&q=85\&s=3bcdf7ac26f1e03441b6c8375b093a25) ### What Happens When You Archive You choose a **target brand** to take over from the brand you archive. The dashboard always asks for one, and the API takes it as `move_products_to`. In one atomic action, Dodo Payments: * Moves every product to the target brand. * Moves every live subscription to the target brand, so renewals bill under it. * Moves every product collection to the target brand. * Archives and disables the original brand. Past records don't move. Payments, invoices, and ended subscriptions keep the brand they were created under, so past reporting stays accurate. The target brand must belong to the same business and must not be archived. Your primary brand is a valid target, and its brand ID is your business ID. You can omit the target only when the brand holds no products, no live subscriptions, and no product collections. > [!NOTE] > > The primary brand can't be archived, and the API rejects the request with `CANNOT_ARCHIVE_PRIMARY_BRAND`. It is the brand your business falls back to, so at least one brand always remains. ### An Archived Brand Is Read-Only The API rejects every change to an archived brand and every new record under it: | Action | Result | | - | - | | Editing the brand's details | Rejected with `BRAND_ARCHIVED` | | Submitting the brand for verification | Rejected with `BRAND_ARCHIVED` | | Creating a product or collection under the brand | Rejected with `BRAND_ARCHIVED` | | Creating a subscription for one of its products | Rejected with `BRAND_ARCHIVED` | Archived brands are hidden from brand pickers, so you can't assign new records to them. They stay available as analytics filters, which keeps your per-brand reporting complete for the period the brand was trading. See [Analytics](/features/analytics). ### Archiving Through the API To archive a brand, call the archive endpoint with the brand you are retiring and the brand that takes over: ```typescript Node.js theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY }); const response = await client.brands.archive('brnd_8dFiAW42v28JzhlVSocjq', { move_products_to: 'brnd_pRQ2zXk91mNvBcTgLwHsA', }); console.log(response.products_moved); ``` ```python Python theme={null} import os from dodopayments import DodoPayments client = DodoPayments(bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY")) response = client.brands.archive( id="brnd_8dFiAW42v28JzhlVSocjq", move_products_to="brnd_pRQ2zXk91mNvBcTgLwHsA", ) print(response.products_moved) ``` ```bash cURL theme={null} curl -X POST https://live.dodopayments.com/brands/brnd_8dFiAW42v28JzhlVSocjq/archive \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"move_products_to": "brnd_pRQ2zXk91mNvBcTgLwHsA"}' ``` The response reports what moved, so you can confirm the outcome. `moved_to_brand_id` is `null` when you archive without a target. ```json theme={null} { "brand_id": "brnd_8dFiAW42v28JzhlVSocjq", "archived_at": "2026-08-17T11:20:05Z", "moved_to_brand_id": "brnd_pRQ2zXk91mNvBcTgLwHsA", "products_moved": 12, "subscriptions_moved": 3, "collections_moved": 1 } ``` The endpoint returns `403` for the primary brand, `404` for an unknown brand, `409` for a brand that is already archived, and `422` for a missing or invalid `move_products_to` target. To list brands including the archived ones, set `include_archived` on the list endpoint. Archived brands are excluded by default. Every brand carries an `archived_at` field, which is `null` while the brand is active. ```bash cURL theme={null} curl "https://live.dodopayments.com/brands?include_archived=true" \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" ``` See the [Archive Brand](/api-reference/brands/archive-brand) API reference for the full request and response schema, and [Error Codes](/api-reference/error-codes) for the errors this endpoint returns. # One-Time Payments Source: https://docs.dodopayments.com/features/one-time-payment-products Sell fixed-price digital goods or services with a single upfront charge, no renewals. One-time payments let you sell lifetime access, downloads, or single-use services with a single charge. There are no renewals, proration rules, or billing cycles. > [card] [License Keys](/features/license-keys) > > Issue unique license keys after purchase. > [card] [Digital Delivery](/features/digital-product-delivery) > > Automatically deliver files and content after payment. > [card] [Payment Webhooks](/developer-resources/webhooks/intents/payment) > > React to payment succeeded and failed events. > [card] [Refunds API](/api-reference/refunds/post-refunds) > > Create full or partial refunds programmatically. ## What Are One‑Time Payments? One-time payments are fixed, upfront purchases ideal for: * **Software licenses**: Lifetime or major-version unlocks. * **Digital downloads**: E-books, templates, graphics, or plugins. * **Services**: Audits, onboarding packages, or one-off consulting. * **Courses and tickets**: Courses, workshops, or live sessions. ## Key Benefits * **Simple checkout**: No renewals or proration logic. * **Instant fulfillment**: Deliver licenses or files right away. * **Flexible pricing**: Discounts and taxes supported. * **Developer-first**: Clear APIs for creation, refunds, and webhooks. ## Creating One‑Time Products Create products in your Dodo Payments dashboard, then sell them via hosted checkout, payment links, or your API. ![One-Time Payment Products dashboard](https://mintcdn.com/dodopayments/r-ndtvzx3WhKqwER/images/products.png?fit=max\&auto=format\&n=r-ndtvzx3WhKqwER\&q=85\&s=fb41221c4f2af4de0155e71de1ac6904) ### Product Configuration Configure the fields in the dashboard to define how your product appears and sells. #### Product Details * **Product Name** (required): Display name shown in checkout and invoices. * **Product Description**: Clear value statement customers see before paying. * **Product Image**: PNG, JPG, or WebP up to 3 MB. * **Brand**: Associate the product with a specific brand for theming and emails. * **Tax Category** (required): Choose the correct category to determine tax rules. > [!TIP] > > Pick the most accurate tax category to ensure correct tax collection per region. #### Pricing * **Pricing Type**: Choose **One Time**. * **Price** (required): Fixed charge with currency. * **Discount Applicable (%)**: Optional percentage discount displayed in checkout and invoices. You can enter up to two decimal places, such as `10.5`. In the API, use `discount_bps` (basis points, so `1050` is 10.5%). > [!WARNING] > > Changing product pricing affects only new purchases. Existing customers aren't impacted. #### Advanced Settings These optional settings are in the **Pricing**, **Entitlements**, and **Meta Data** sections of the product form: * **Tax Inclusive Pricing** (in **Pricing**): Display prices inclusive of applicable taxes. * **License key** (in **Entitlements**): Issue a unique key after purchase. See [License Keys](/features/license-keys). * **Digital Files** (in **Entitlements**): Deliver files or content automatically. See [Digital Product Delivery](/features/digital-product-delivery). * **Meta Data**: Attach custom key-value pairs for internal tagging or integrations. See [Metadata](/api-reference/metadata). > [!TIP] > > Use metadata to store identifiers from your system (e.g., orderId) to reconcile events and receipts later. ## API Management > [accordion] Create Payments > > Use `POST /checkouts` to create a checkout session that collects a one-time payment for your products. > > > [card] [API Reference](/api-reference/checkout-sessions/create) > > > > View the Create Checkout Session API. > [accordion] Refund Payments > > Use `POST /refunds` to create full or partial refunds. > > > [card] [API Reference](/api-reference/refunds/post-refunds) > > > > Learn how to refund a payment. > [accordion] List and Retrieve Payments > > Use `GET /payments` to list payments and `GET /payments/{payment_id}` to retrieve one. Retrieve line items with `GET /payments/{payment_id}/line-items`. > > > [card] [List Payments](/api-reference/payments/get-payments) > > > > Browse the listing API. > > > [card] [Get Payment Detail](/api-reference/payments/get-payments-1) > > > > See the retrieval API. > > > [card] [Retrieve Line Items](/api-reference/payments/retrieve-line-items) > > > > Inspect purchased items for a payment. > [accordion] Payment Webhooks > > React to events like payment.succeeded or payment.failed in your backend. > > > [card] [Webhook Guide](/developer-resources/webhooks/intents/payment) > > > > Handle payment lifecycle events. ## Common Use Cases * **License-based tools**: Unlock features with a one-time key. * **Digital assets**: Themes, templates, icon sets, or media. * **Professional services**: Fixed-fee implementation or setup. * **Education**: Course tickets and one-off workshops. ## Integration Examples ### Checkout Sessions (Single Payment) Create a checkout session with a one-time product in the cart: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_one_time', quantity: 1 } ] }); ``` ## Best Practices * **Clarify deliverables**: Tell buyers exactly what they get and how it's delivered. * **Deliver instantly**: Use license keys or digital delivery for immediate access. * **Track with metadata**: Store your IDs for easy reconciliation. # Transferring Business Ownership Source: https://docs.dodopayments.com/features/ownership-transfer Make a teammate the Owner of your business. Confirm with an emailed code, and the new Owner accepts the request and completes identity verification. ## Introduction An ownership transfer makes another member of your team the **Owner** of the business. The new Owner gets full control of payouts, team management, business settings, and API keys. You stay on the team as an **Admin**. The business keeps everything else: its products, customers, payments, payouts history, and integrations. Customers see no change. > [!NOTE] > > To change the legal entity behind the business, such as moving from an individual to a registered company, use an [entity transfer](/features/entity-transfer) instead. Changing from one individual to a different individual is an ownership transfer. ## How It Works An ownership transfer moves through three steps. The current Owner starts it, the new Owner accepts it, and the transfer completes once the new Owner's identity verification (KYC) is approved. ```mermaid theme={null} flowchart LR A[Owner starts transfer] --> B[Pending: waiting for the new Owner] B -->|Accepts| C{New Owner has approved KYC?} B -->|Declines or 48 hours pass| D[Closed: Owner unchanged] C -->|Yes| E[Completed] C -->|No| F[Awaiting verification] F -->|KYC approved| E ``` | Status | What it means | | - | - | | **Pending** | The request is waiting for the new Owner. You are still the Owner. The request expires after **48 hours**. | | **Awaiting verification** | The new Owner accepted and is now the Owner. The transfer completes when their identity verification is approved. | | **Completed** | The new Owner holds the business and their identity verification is approved. | | **Declined**, **Expired**, or **Cancelled** | The transfer closed without a change. You stay the Owner and can start a new transfer. | ## Requirements Check these before you start: * **Only the Owner can start a transfer.** Admins and other roles can't. * **The new Owner must be a team member with an account.** [Invite them to the team](/features/team) first. A teammate whose invitation is still open can't be picked until they sign up. * **The new Owner can own at most 10 businesses**, including this one. Businesses they archived don't count. * **A business can have one open transfer at a time.** An open ownership transfer or [entity transfer](/features/entity-transfer) blocks a new one until it closes. ## Start an Ownership Transfer > [!WARNING] > > You can't cancel the transfer from the dashboard after you confirm the code. Only the new Owner can accept or decline it. Make sure you pick the right teammate before you confirm. **1. Open Change Role for the New Owner** Go to **Settings → Team**. In the row of the teammate who will become the Owner, open the actions menu and select **Change Role**. **2. Select the Owner Role** Under **Pre-Defined**, select **Owner**, then select **Continue**. ![Change Role panel with the Owner role selected, noting that assigning it starts an ownership transfer](https://mintcdn.com/dodopayments/GGJ2RbNuuzLQXnHx/images/ownership-transfer/change-role-owner.png?fit=max\&auto=format\&n=GGJ2RbNuuzLQXnHx\&q=85\&s=a3fe213bd5c7e1503bcea93a6a5ad5f6) **3. Enter a Reason** Read the summary of what the new Owner receives. Enter a **Reason for transfer** of up to 1,000 characters, then select **Transfer Ownership**. Dodo Payments emails a confirmation code to your login email address. ![Transfer ownership dialog naming the new Owner, with a reason entered and the Transfer Ownership button](https://mintcdn.com/dodopayments/GGJ2RbNuuzLQXnHx/images/ownership-transfer/confirm.png?fit=max\&auto=format\&n=GGJ2RbNuuzLQXnHx\&q=85\&s=7161d77724217fc4474f7b469f29a04d) **4. Enter the Code from Your Email** Enter the 6-digit code and select **Confirm Transfer**. The code expires after a short time, and too many wrong attempts mean you need to start again. ![Confirm the transfer dialog with a 6-digit code entered and a resend countdown](https://mintcdn.com/dodopayments/GGJ2RbNuuzLQXnHx/images/ownership-transfer/code.png?fit=max\&auto=format\&n=GGJ2RbNuuzLQXnHx\&q=85\&s=f5794a928cfa07c4c18953a5d15b3164) If you no longer have access to your email, use the **Contact support** link in the dialog. **5. Wait for the New Owner** Dodo Payments emails the new Owner a link to the request. You stay the Owner until they accept it. Select **Done** to close the dialog. ![Transfer Request Sent dialog showing the new Owner's email address](https://mintcdn.com/dodopayments/GGJ2RbNuuzLQXnHx/images/ownership-transfer/request-sent.png?fit=max\&auto=format\&n=GGJ2RbNuuzLQXnHx\&q=85\&s=7acea7aa01a9485601f4d402a06061d0) While the request is pending, the **Team** page shows an **Ownership transfer in progress** banner with the hours left before the request expires. Your row shows **Transfer pending** and the new Owner's row shows **Awaiting acceptance**. ![Team page with the Ownership transfer in progress banner and the Transfer pending and Awaiting acceptance badges](https://mintcdn.com/dodopayments/GGJ2RbNuuzLQXnHx/images/ownership-transfer/pending-banner.png?fit=max\&auto=format\&n=GGJ2RbNuuzLQXnHx\&q=85\&s=352c3318ba9679719df7b6c1a62ceccc) ## Accept or Decline a Transfer This section is for the teammate who receives the request. **1. Open the Request** Select the link in the ownership transfer email. The dashboard opens the request with the business, the current Owner, their reason, and the time left before it expires. ![Ownership transfer request page listing the business, current Owner, reason, expiry, and what happens on acceptance](https://mintcdn.com/dodopayments/GGJ2RbNuuzLQXnHx/images/ownership-transfer/accept.png?fit=max\&auto=format\&n=GGJ2RbNuuzLQXnHx\&q=85\&s=b49e9eeba47d95d5ade082fbc6517542) **2. Accept or Decline** Read **When you accept**, then select **Accept Ownership**. To refuse, select **Decline** and confirm. The current Owner stays the Owner and can start a new transfer later. **3. Complete Identity Verification** If you already have an approved identity verification (KYC) on Dodo Payments, the transfer completes as soon as you accept. If you don't, the dashboard takes you to **Verification**. You are already the Owner, and a reminder appears at the top of every page until your verification is approved. The transfer completes automatically after approval. See [Identity Verification](/miscellaneous/verification-process#identity-verification-kyc). If the request page says **This transfer is no longer open**, the request was accepted, declined, cancelled, or it expired. Ask the Owner to start a new transfer. ## What Happens After Acceptance * **The new Owner** gets full control of the business: payouts, compliance communication, team access, API keys, and business settings. * **The previous Owner** stays on the team with the **Admin** role. * **Auto payouts turn off.** Dodo Payments turns them on again after it reviews the business. * **Payments continue.** Your checkout, payment links, subscriptions, and API integrations keep working with no change. * **Both parties get an email** when the transfer is accepted, declined, expired, or completed. > [card] [Team](/features/team) > > Invite the new Owner to your team and manage roles. > [card] [Entity Transfer](/features/entity-transfer) > > Change the legal entity behind your business. > [card] [Verification Process](/miscellaneous/verification-process) > > Complete identity verification as the new Owner. > [card] [Help and Support](/miscellaneous/help-support) > > Get help if you can't access the Owner's email. # Pay What You Want Pricing Source: https://docs.dodopayments.com/features/pay-what-you-want Let customers choose their price above a minimum. Optionally show a suggested price. Optimized for one-time purchases. Pay What You Want (PWYW) lets customers decide how much they pay—at or above a merchant-defined minimum. It increases engagement, encourages community support, and provides flexible pricing for digital products. [Pay What You Want Pricing | Dodo Payments](https://www.youtube.com/embed/Lh0Q01b33NY) ## What Is Pay What You Want? PWYW is a pricing model where customers set their own price within guardrails you define. It's ideal for: * **Digital products and media**: Templates, e-books, courses, plugins. * **Experimental launches**: Early access, beta releases, time-boxed promos. * **Bundles and extras**: Add a PWYW tier to boost participation. ## Key Benefits * **Customer-driven pricing**: Buyers choose what they pay. * **Revenue floor**: Enforce a minimum to protect margins. * **Anchored expectations**: Optional suggested price to guide choices. * **Hosted checkout**: Checkout and receipts handled for you. * **Developer-first**: Clear APIs for creation, refunds, and webhooks. > [!WARNING] > > PWYW is available only for products with the **One Time** pricing type. The product's base currency must be USD, GBP, or EUR, and PWYW can't be combined with [Localized Pricing](/features/localized-pricing). ## Creating Pay What You Want Create a one-time product and enable PWYW in your Dodo Payments dashboard. The sections below map directly to the creation form. ### Product Creation #### Product Details * **Product Name** (required): Display name shown in checkout and invoices. * **Product Description**: Clear value statement customers see before paying. * **Product Image**: PNG, JPG, or WebP up to 3 MB. * **Brand**: Associate the product with a specific brand for theming and emails. * **Tax Category** (required): Choose the correct category to determine tax rules. > [!TIP] > > Pick the most accurate tax category to ensure correct tax collection per region. #### Pricing * **Pricing Type**: Choose **One Time**. * **Pay What You Want** (toggle): Enable to let buyers choose the amount. * **Minimum Price** (required): Lowest allowed amount a customer can pay. * **Suggested Price** (optional): Recommended amount shown on the product page. It can't be lower than the minimum price. > [!TIP] > > Use metadata to store identifiers from your system (e.g., orderId) so you can reconcile events and receipts later. #### Sharing a Link With a Fixed Amount When you share a checkout link for a PWYW product from **Products**, open **Advanced Settings** and set a **Payment amount** to charge exactly that value instead of letting the buyer choose. The amount must be at or above the product's Minimum Price, and it is carried on the link as the `paymentAmount` query parameter in major currency units (e.g., `12.5` for \$12.50). Leave the field empty to keep the buyer-chooses-amount behavior. ## API Management > [accordion] Create Checkout Sessions (PWYW) > > Use `POST /checkouts` to create one-time checkout sessions from products. Checkout will prompt buyers to enter an amount that meets your PWYW minimum. > > > [card] [API Reference](/api-reference/checkout-sessions/create) > > > > View the create checkout session API. > [accordion] Refund Payments > > Use `POST /refunds` to create full or partial refunds. Customers are refunded the exact amount they paid. > > > [card] [API Reference](/api-reference/refunds/post-refunds) > > > > Learn how to refund a payment. > [accordion] List and Retrieve > > Use `GET /payments` to list payments and `GET /payments/{payment_id}` to retrieve one. Retrieve line items with `GET /payments/{payment_id}/line-items`. > > > [card] [List Payments](/api-reference/payments/get-payments) > > > > Browse the listing API. > > > [card] [Get Payment Detail](/api-reference/payments/get-payments-1) > > > > See the retrieval API. > > > [card] [Retrieve Line Items](/api-reference/payments/retrieve-line-items) > > > > Inspect purchased items for a payment. > [accordion] Payment Webhooks > > React to events like payment.succeeded or payment.failed in your backend. > > > [card] [Webhook Guide](/developer-resources/webhooks/intents/payment) > > > > Handle payment lifecycle events. ## Common Use Cases * **Digital assets**: Themes, templates, icon sets, media, or plugins. * **Content and education**: E-books, courses, workshops with supporter pricing. * **Community and donations**: Fundraisers, open-source sponsorships, creator support. * **Launch experiments**: Beta access and time-boxed campaigns to gauge demand. ## Integration Examples ### Checkout Sessions (Single Payment, PWYW) Add a PWYW product to the cart. Checkout collects the buyer's amount (respecting your minimum) — no extra fields are required. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_pwyw_demo', quantity: 1 } ], return_url: 'https://yoursite.com/checkout/success' }); ``` To set the amount yourself instead of letting the buyer choose, pass `amount` on the cart item in the lowest denomination of the currency (for example, `1250` for \$12.50). The `amount` field is ignored for products without PWYW enabled. ## Best Practices * **Choose a sensible minimum**: Cover costs while keeping participation easy. * **Use a suggested price**: Anchor expectations to improve average order value. * **Explain value clearly**: Tell buyers what their contribution unlocks. * **A/B test campaigns**: Time-box offers and experiment with messaging. * **Monitor distribution**: Track paid amounts to refine minimum and suggested price. # Payment Methods Source: https://docs.dodopayments.com/features/payment-methods Complete guide to payment methods supported by Dodo Payments, including credit/debit cards, digital wallets, BNPL, UPI/Rupay, European options, and how to configure them for your checkout. Dodo Payments supports 40+ payment methods across 220+ countries. All methods are pre-configured and managed by Dodo Payments — no additional contracts, integrations, or merchant accounts needed. Turn on new methods instantly. ## Why Offer Multiple Payment Methods? > [card] Boost Conversion > > Local payment methods increase sales 20-30% in target markets. > [card] One Platform > > All methods managed through a single API and dashboard. > [card] Smart Routing > > The right options appear based on customer location, currency, and device. ## How Payment Methods Are Selected Dodo Payments automatically shows customers the payment methods available to them based on: * **Billing Country** — Regional methods like iDEAL (Netherlands) or UPI (India) only appear for customers in those countries * **Transaction Currency** — Payment methods are filtered by the currency they support * **Device Type** — Apple Pay only appears on compatible Apple devices and browsers * **Transaction Type** — Some methods don't support subscriptions or have minimum transaction amounts > [!NOTE] > > All payment methods are pre-configured and managed by Dodo Payments. No setup is required — they become available once your account is verified and live mode is enabled. ## Supported Payment Methods | Payment Method | Supported Countries | Supported Currencies | Subscriptions | | :- | :- | :- | :-: | | **Credit Cards** | Global | All currencies | Yes | | **Debit Cards** | Global | All currencies | Yes | | **Apple Pay** | Global, including India | All currencies, including INR | Yes | | **Google Pay** | Global (except India) | All currencies | Yes | | **Amazon Pay** | Global (except India) | USD, EUR, GBP, AUD, CHF, DKK, HKD, JPY, NOK, NZD, SEK, ZAR | No | | **Cash App Pay** | US | USD | Yes | | **ACH Direct Debit** | US | USD | No | | **SEPA Direct Debit** | Eurozone | EUR | No | | **Klarna** | US, Europe | USD, EUR, GBP, DKK, NOK, SEK, CZK, RON, PLN, CHF | Yes | | **Afterpay** | US, UK | USD, GBP | No | | **UPI** | India | INR | Yes\* | | **Rupay** | India | INR | Yes\* | | **iDEAL** | Netherlands | EUR | No | | **Bancontact** | Belgium | EUR | No | | **EPS** | Austria | EUR | No | | **Multibanco** | Portugal | EUR | No | | **BLIK** | Poland | PLN | No | | **Satispay** | Europe | EUR | Yes | | **PAYCO** | South Korea | KRW | No | | **Naver Pay** | South Korea | KRW | Yes | | **Kakao Pay** | South Korea | KRW | Yes | | **RevolutPay** | Global | GBP | No | | **Billie** | Global | GBP | No | | **Pix** | Brazil | BRL | Yes | | **Stablecoins** | Global (except India) | USD | No | | **WeChat Pay** | Global | USD, CNY | No | | **GCash** | Philippines | PHP | Yes | | **Alipay HK** | Hong Kong | HKD | No | | **FPS** | Hong Kong | HKD, CNY | No | | **Touch 'n Go** | Malaysia | MYR | No | > [!NOTE] > > \*All Indian-issued cards (Visa, Mastercard, Rupay, etc.) and UPI support subscriptions with RBI-compliant mandates. The 48-hour processing delay applies to all Indian-issued cards and UPI. See the [India Payment Methods](/features/payment-methods/india) page for details on mandate requirements. > [!WARNING] > > PayPal is temporarily unavailable for new transactions. We'll update this page when restored. ## Minimum Amounts Every payment method follows the minimum amount for the checkout currency. In USD, the minimum is \$0.50 for one-time payments and \$1.00 for subscriptions. Other currencies have their own minimums. See [Minimum Amounts](/features/adaptive-currency#minimum-amounts) for each currency. These methods also appear only within an amount range: | Payment Method | Appears When | | :- | :- | | **Klarna** | The checkout is in USD with a US billing address and the amount is above \$50.00 (\$50.01 minimum) | | **Afterpay** | The checkout is a one-time payment in USD with a US billing address and the amount is above \$50.00 (\$50.01 minimum) | | **Stablecoins** | The checkout is in USD and the amount is from \$0.50 to \$10,000 | | **PAYCO**, **Naver Pay**, **Kakao Pay** | The checkout is in KRW and the total is worth at least about \$1.00 | | **WeChat Pay** | The checkout is a one-time payment in USD or CNY and the amount is at most 1,000.00 CNY or the USD equivalent | ## Payment Method Categories > [card] [Credit & Debit Cards](/features/payment-methods/cards) > > Accept Visa, Mastercard, Amex, Discover, JCB, UnionPay, and regional networks like Cartes Bancaires and Interac. > [card] [Digital Wallets](/features/payment-methods/digital-wallets) > > Apple Pay, Google Pay, Amazon Pay, Cash App Pay, and RevolutPay for fast, secure one-tap checkout. > [card] [Buy Now Pay Later](/features/payment-methods/bnpl) > > Klarna, Afterpay, and Billie installment options to increase average order value and conversion. > [card] [ACH Direct Debit](/features/payment-methods/ach) > > Bank account debits for US customers paying in USD, available on one-time payments. > [card] [India](/features/payment-methods/india) > > UPI, Rupay cards, and Apple Pay in INR, with RBI-compliant subscription mandates for the Indian market. > [card] [Europe](/features/payment-methods/europe) > > iDEAL (Netherlands), Bancontact (Belgium), EPS (Austria), Multibanco (Portugal), and BLIK (Poland). > [card] [South Korea](/features/payment-methods/south-korea) > > Kakao Pay, Naver Pay, and PAYCO wallets plus Korean local cards, billed in KRW. > [card] [Pix](/features/payment-methods/pix) > > Instant bank transfers for the Brazilian market via QR code or copy-paste key. > [card] [Stablecoins](/features/payment-methods/stablecoins) > > Accept stablecoin payments from customers worldwide (excluding India), billed in USD. > [card] [WeChat Pay](/features/payment-methods/wechat) > > QR code payments for Chinese customers via WeChat, supporting USD and CNY. > [card] [Asia-Pacific](/features/payment-methods/asia-pacific) > > GCash (Philippines), Alipay HK and FPS (Hong Kong), and Touch 'n Go (Malaysia). ## Disable Payment Methods at the Business Level You can disable specific payment methods from your dashboard. This applies across all checkout sessions for your business without needing to configure each session individually. **1. Open Settings** Go to **Settings → Payment Methods** in your Merchant Dashboard. **2. Disable Methods** Toggle off any payment methods you don't want to offer. > [!TIP] > > Disable payment methods that have high fraud rates in your region, or limit options to only the methods your business supports operationally. > [!NOTE] > > Business-level settings act as a global filter. Per-checkout restrictions via `allowed_payment_method_types` further narrow the available methods within what's enabled at the business level. ## Restrict Payment Methods Per Checkout In addition to business-level settings, you can restrict which methods appear for individual checkout sessions using `allowed_payment_method_types`: > [tab] JavaScript > > ```javascript theme={null} > const session = await client.checkoutSessions.create({ > product_cart: [{ product_id: 'pdt_123', quantity: 1 }], > allowed_payment_method_types: [ > 'credit', > 'debit', > 'apple_pay', > 'google_pay' > ], > return_url: 'https://example.com/success' > }); > ``` > [tab] Python > > ```python theme={null} > session = client.checkout_sessions.create( > product_cart=[{"product_id": "pdt_123", "quantity": 1}], > allowed_payment_method_types=[ > "credit", > "debit", > "apple_pay", > "google_pay" > ], > return_url="https://example.com/success" > ) > ``` > [tab] cURL > > ```bash theme={null} > curl -X POST https://test.dodopayments.com/checkouts \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_cart": [{"product_id": "pdt_123", "quantity": 1}], > "allowed_payment_method_types": ["credit", "debit", "apple_pay", "google_pay"], > "return_url": "https://example.com/success" > }' > ``` ### Available Method Types | Type | Description | | :- | :- | | `credit` | Credit cards (Visa, Mastercard, Amex, Discover, JCB, UnionPay, etc.) | | `debit` | Debit cards | | `apple_pay` | Apple Pay | | `google_pay` | Google Pay | | `amazon_pay` | Amazon Pay | | `cashapp` | Cash App Pay | | `ach` | ACH Direct Debit (US) | | `klarna` | Klarna BNPL | | `afterpay_clearpay` | Afterpay / Clearpay | | `upi_intent` | UPI via QR code (India). See [India Payment Methods](/features/payment-methods/india) | | `ideal` | iDEAL (Netherlands) | | `bancontact_card` | Bancontact (Belgium) | | `eps` | EPS (Austria) | | `multibanco` | Multibanco (Portugal) | | `blik` | BLIK (Poland) | | `sepa` | SEPA Direct Debit (Eurozone) | | `satispay` | Satispay (Europe) | | `payco` | PAYCO (South Korea) | | `naver_pay` | Naver Pay (South Korea) | | `kakao_pay` | Kakao Pay (South Korea) | | `revolut_pay` | RevolutPay | | `billie` | Billie B2B BNPL | | `pix` | Pix (Brazil) | | `crypto_currency` | Stablecoins | | `we_chat_pay` | WeChat Pay | | `gcash` | GCash (Philippines) | | `ali_pay_hk` | Alipay HK (Hong Kong) | | `fps` | FPS (Hong Kong) | | `touch_n_go` | Touch 'n Go (Malaysia) | > [!WARNING] > > Always include `credit` and `debit` as fallbacks. If all specified payment methods are unavailable for a customer, checkout will fail. ### API Endpoints > [card] [Checkout Sessions](/api-reference/checkout-sessions/create) > > Create checkout with allowed methods. > [card] [Preview Checkout](/api-reference/checkout-sessions/preview) > > Preview pricing and taxes before creating a session. > [card] [Update Payment Method](/api-reference/subscriptions/update-payment-method) > > Restrict methods on a subscription's payment-method update page. ## Best Practices > [accordion] Match methods to your market > > Include regional payment methods for your target markets. iDEAL captures \~60% of online payments in the Netherlands; UPI dominates in India. Omitting these methods significantly hurts conversion. > [accordion] Always provide card fallbacks > > Include `credit` and `debit` as fallbacks even when targeting specific methods. Not all customers have access to every payment method. > [accordion] Consider transaction minimums > > Klarna and Afterpay appear on USD checkouts with a US billing address only when the amount is \$50.01 or more. Don't include them for products outside this range — they won't appear. All other payment methods follow the [minimum amount for the checkout currency](/features/adaptive-currency#minimum-amounts). > [accordion] Test across regions and devices > > Use test mode to verify payment method availability for different customer locations, currencies, and device types before going live. ## Troubleshooting > [accordion] Payment method not appearing > > Check these factors: > > 1. Is the method included in `allowed_payment_method_types`? > 2. Does the customer's location match the method's supported region? > 3. Does the method support the transaction currency? > 4. Is the transaction amount within the method's supported range (e.g., Klarna/Afterpay minimum \$50.01 on USD checkouts)? > 5. For subscriptions: does the method support recurring payments? > > **Solution:** Remove `allowed_payment_method_types` temporarily to see all eligible methods, then narrow down the issue. > [accordion] Unexpected methods appearing > > **Possible causes:** > > * `allowed_payment_method_types` not being passed correctly > * Parameter formatted incorrectly (must be an array of strings) > > **Solution:** Log your API request payload and verify the parameter structure. > [accordion] Regional method not available > > **Check:** > > * Customer billing address matches the method's region > * Currency is set correctly (e.g., EUR for iDEAL) > * Adaptive Currency is enabled if the customer is international > > **Solution:** Verify billing address country code and currency in your API request. > [accordion] Indian payment method issues > > UPI and Rupay subscriptions have unique requirements including 48-hour processing delays and RBI mandate limits. > > **See:** [India Payment Methods](/features/payment-methods/india) for complete guidance. ## Related Pages > [card] [Adaptive Currency](/features/adaptive-currency) > > Show prices in 80+ local currencies and accept payments in the customer's local currency. > [card] [Checkout Guide](/developer-resources/checkout-session) > > Complete checkout implementation guide. > [card] [Testing Process](/miscellaneous/testing-process) > > Test cards, UPI IDs, and wallet testing in test mode. > [card] [Subscriptions](/features/subscription) > > Recurring billing and payment method updates for subscriptions. ## Request a Payment Method We continuously add new payment methods. If you need a specific method not listed here, contact [support@dodopayments.com](mailto:support@dodopayments.com). # ACH Direct Debit Source: https://docs.dodopayments.com/features/payment-methods/ach Accept ACH Direct Debit from US customers paying in USD. Learn how bank debits work at checkout, how long they take to clear, and how to test them. ACH Direct Debit lets customers in the United States pay from their bank account instead of a card. It runs on the Automated Clearing House network and is offered on USD checkouts for one-time payments. ## Why Offer ACH Direct Debit? > [card] Lower Processing Cost > > ACH costs a flat 1.5% per payment, capped at \$15, instead of the card fee. See [pricing](https://dodopayments.com/pricing). > [card] No Card Required > > Reach US customers who prefer to pay from a bank account, or who don't want to use a card for a large purchase. > [card] Higher Value Orders > > Because the fee is capped at \$15, the saving over a card fee grows with order value. ACH suits large one-time purchases. ## Overview | Detail | Value | | :- | :- | | **Billing Currency** | USD | | **Supported Countries** | United States | | **Subscriptions** | No | | **Min Amount** | \$0.50 | | **Settlement** | Up to 4 business days | > [!WARNING] > > ACH Direct Debit is not instant. A payment can take **up to 4 business days** to succeed or fail. An authorized debit is not a settled payment: fulfill the order only after the payment reaches the succeeded state. ## How It Works ```mermaid theme={null} sequenceDiagram participant Customer participant Checkout participant Dodo participant ACH as ACH Network participant Bank Customer->>Checkout: Select ACH Direct Debit Checkout->>Customer: Ask for bank account details Customer->>Checkout: Enter details and authorize the debit Checkout->>Dodo: Create payment Dodo->>ACH: Submit debit request Note over ACH,Bank: Clearing takes up to 4 business days ACH->>Bank: Debit customer account Bank->>ACH: Confirm or return ACH->>Dodo: Final status Dodo->>Checkout: Payment succeeded or failed ``` ## Customer Experience 1. The customer selects **ACH Direct Debit** at checkout. 2. The customer enters the account holder name, routing number, account number, account type (checking or savings), and email address. Checkout checks that the routing number is valid. 3. The customer submits the form, which authorizes the debit from their US bank account under a mandate. 4. The payment is submitted to the ACH network and enters the processing state. Checkout completes without waiting for clearing. 5. Clearing completes over the following business days. 6. The payment moves to the succeeded state, or fails if the bank returns it. > [!NOTE] > > Because clearing is asynchronous, use [webhooks](/developer-resources/webhooks) to learn the final outcome instead of the checkout redirect. A redirect after checkout only means the customer authorized the debit. > > The payment emits `payment.processing` once the debit is submitted, then `payment.succeeded` or `payment.failed` when clearing completes. Fulfill only on `payment.succeeded`. ## Availability ACH Direct Debit appears at checkout when all of the following are true: * The **billing currency** is `USD`. * The **billing country** is `US`. * The transaction is a **one-time payment**. > [!NOTE] > > ACH Direct Debit is not available for subscriptions. For recurring payments, use cards or another method that supports subscriptions. See the [Payment Methods overview](/features/payment-methods). ## Configuration ```javascript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['ach', 'credit', 'debit'], billing_currency: 'USD', billing_address: { country: 'US', zipcode: '94102' }, return_url: 'https://example.com/success' }); ``` > [!NOTE] > > ACH Direct Debit requires a **USD** billing currency and a **US** billing address. If you price in another currency, enable [Adaptive Currency](/features/adaptive-currency) so US customers are billed in USD and ACH becomes available. ## API Method Type | Type | Method | Country | | :- | :- | :- | | `ach` | ACH Direct Debit | United States | ## Refunds and Disputes Refunds and disputes for ACH payments use the same APIs and dashboard flows as every other payment method. You don't need ACH-specific handling. > [!WARNING] > > A customer's bank can return an ACH debit after it appears to have gone through, and under Nacha rules a customer can return an unauthorized debit from a personal account for up to 60 calendar days after settlement. Don't issue a refund until the original payment has reached the succeeded state. ## Testing **1. Enable test mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. **2. Set currency and billing address** Set the billing currency to `USD` and the billing address country to `US`. **3. Include `ach` in allowed methods** Pass `ach` in `allowed_payment_method_types`, or omit the field to show every eligible method. **4. Enter the test bank details** Enter one of the test routing and account number pairs below. Then confirm that your webhook handler receives the final payment status. ### Test Bank Accounts The customer types the account and routing numbers into the checkout form. In test mode, use the routing number `110000000` with one of these account numbers to force an outcome: | Account Number | Routing Number | Behavior | | :- | :- | :- | | `000123456789` | `110000000` | The payment succeeds. | | `000222222227` | `110000000` | The payment fails due to insufficient funds. | | `000111111113` | `110000000` | The payment fails because the account is closed. | | `000111111116` | `110000000` | The payment fails because no account is found. | | `000333333335` | `110000000` | The payment fails because debits aren't authorized on the account. | | `000444444440` | `110000000` | The payment fails due to an invalid currency. | | `000555555559` | `110000000` | The payment succeeds, then triggers a dispute. | | `000000000009` | `110000000` | The payment stays in processing indefinitely. Use it to test a pending-state UI. | > [!NOTE] > > Test payments reach a final status much faster than live payments, so you don't need to wait days to verify your integration. The exception is `000000000009`, which stays in processing. ## Best Practices > [accordion] Don't fulfill on authorization > > An ACH authorization is not a payment. Wait for the payment to reach the succeeded state before you grant access or ship. The customer's bank can still return the debit. > [accordion] Set customer expectations at checkout > > Tell customers that bank payments don't clear immediately. This reduces support tickets that ask why an order is still pending. > [accordion] Provide card fallbacks > > Include `credit` and `debit` alongside `ach`, so customers who need immediate access to your product can choose a faster method. > [accordion] Use ACH for high-value one-time purchases > > The ACH fee is capped at \$15, so the saving is largest on large one-time purchases. ## Troubleshooting > [accordion] ACH not appearing at checkout > > **Check:** > > 1. Is the billing currency `USD`? > 2. Is the customer's billing country `US`? > 3. Is `ach` included in `allowed_payment_method_types`? > 4. Is this a one-time payment? ACH is not offered on subscriptions. > 5. Is the amount at least \$0.50? > > **Solution:** Remove `allowed_payment_method_types` temporarily to see all eligible methods, then check the billing currency and address country in your API request. > [accordion] ACH not appearing on a subscription checkout > > **Cause:** ACH Direct Debit is offered for one-time payments only. > > **Solution:** Use cards or another subscription-capable method for recurring billing. > [accordion] Payment stuck in processing > > **Cause:** This is expected. An ACH payment stays in the processing state for the whole clearing window, which is much longer than for a card payment. > > **Solution:** Wait for the final webhook. Don't retry the payment, because a retry can debit the customer twice. > [accordion] Payment failed after initially succeeding at checkout > > **Cause:** Checkout completed, but the customer's bank returned the debit during clearing, most often for insufficient funds or a closed account. The payment emits `payment.failed`. > > **Solution:** Treat the payment as failed, and ask the customer to pay with another method. Fulfill only on the succeeded state to avoid this. ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > See all supported payment methods. > [card] [Adaptive Currency](/features/adaptive-currency) > > Currency support and automatic conversion. > [card] [Checkout Guide](/developer-resources/checkout-session) > > Complete checkout implementation guide. > [card] [Webhooks](/developer-resources/webhooks) > > Handle delayed payment confirmations asynchronously. # Asia-Pacific Payment Methods Source: https://docs.dodopayments.com/features/payment-methods/asia-pacific Accept GCash in the Philippines on one-time payments and subscriptions, and Alipay HK, FPS, and Touch 'n Go on one-time payments, billed in local currency. Let customers in the Philippines, Hong Kong, and Malaysia pay with the wallet or bank transfer they use every day. Dodo Payments supports **GCash** (Philippines), **Alipay HK** and **FPS** (Hong Kong), and **Touch 'n Go** (Malaysia) on one-time payments. GCash also works on subscriptions. Each method is billed in its local currency, and the customer pays by scanning a QR code shown at checkout. > [!NOTE] > > This page covers the Philippines, Hong Kong, and Malaysia. For other Asian markets, see [India](/features/payment-methods/india) for UPI and Rupay, [South Korea](/features/payment-methods/south-korea) for Kakao Pay, Naver Pay, and PAYCO, and [WeChat Pay](/features/payment-methods/wechat) for Chinese customers. ## Why Asia-Pacific Wallets Matter > [card] Wallet-First Markets > > GCash is the most popular digital wallet in the Philippines, and Touch 'n Go is the largest e-wallet in Malaysia. > [card] Low Card Penetration > > Credit card use is low in the Philippines compared with card-first markets. Local wallets and bank transfers reach customers that a card-only checkout misses. > [card] Instant Settlement > > FPS runs 24 hours a day in Hong Kong, and funds reach the payee almost immediately, so checkout can confirm the payment while the customer waits. ## Supported Methods The table lists each method's market, billing currency, and minimum amount. The minimum is the checkout minimum for that currency, so it applies to every payment method on a checkout in that currency. | Method | Country | Billing Currency | Subscriptions | Min Amount | | :- | :- | :- | :-: | :- | | **GCash** | Philippines | PHP | Yes | 50.00 PHP | | **Alipay HK** | Hong Kong | HKD | No | 4.00 HKD | | **FPS** | Hong Kong | HKD, CNY | No | 4.00 HKD / 4.00 CNY | | **Touch 'n Go** | Malaysia | MYR | No | 4.00 MYR | > [!WARNING] > > **Alipay HK, FPS, and Touch 'n Go are one-time only.** They don't appear on subscription checkouts or support any other recurring charge. GCash is the only method on this page that works on subscriptions. Include `credit` and `debit` on subscription checkouts so customers in Hong Kong and Malaysia can still sign up. > [!NOTE] > > Customers pay in their local currency. Payments made with these four methods settle to your **USD** wallet. Card payments on the same checkout settle in USD. ### Method Details > [accordion] GCash (Philippines) > > GCash is the most popular e-wallet in the Philippines. At checkout, the customer selects **GCash**, clicks **Pay**, and scans the QR code with the GCash app to approve the payment. > > Offered on **one-time** and **subscription** checkouts billed to the **Philippines (`PH`)** in **PHP**. On a subscription, renewals are charged to the same GCash account, and a plan change or a payment method update keeps GCash. > [accordion] Alipay HK (Hong Kong) > > Alipay HK is the Hong Kong edition of Alipay. It serves the local market and settles in Hong Kong dollars. It is a separate method from the mainland China Alipay product. Checkout labels it **AlipayHK**. > > Offered on **one-time** checkouts billed to **Hong Kong (`HK`)** in **HKD**. Alipay HK settles in HKD only, so it does not appear on a CNY checkout, even when the billing country is Hong Kong. > [accordion] FPS (Hong Kong) > > FPS (Faster Payment System) is Hong Kong's real-time payment system, launched by the Hong Kong Monetary Authority. It connects banks and e-wallets, runs 24 hours a day, and supports Hong Kong dollars and Chinese yuan. The customer scans the QR code with a banking or e-wallet app, and the funds arrive almost immediately. > > Offered on **one-time** checkouts billed to **Hong Kong (`HK`)** in either **HKD** or **CNY**. > [accordion] Touch 'n Go (Malaysia) > > Touch 'n Go is the largest e-wallet in Malaysia. The customer scans the QR code with the Touch 'n Go app and confirms the payment there. > > Offered on **one-time** checkouts billed to **Malaysia (`MY`)** in **MYR**. ## Configuration ### API Method Types Pass these values in `allowed_payment_method_types`: | Type | Description | | :- | :- | | `gcash` | GCash wallet (Philippines) | | `ali_pay_hk` | Alipay HK wallet (Hong Kong) | | `fps` | FPS real-time bank transfer (Hong Kong) | | `touch_n_go` | Touch 'n Go wallet (Malaysia) | ### Example: Philippines Checkout ```javascript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['gcash', 'credit', 'debit'], billing_currency: 'PHP', billing_address: { country: 'PH', zipcode: '1226' }, return_url: 'https://example.com/success' }); ``` ### Example: Hong Kong Checkout ```javascript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['ali_pay_hk', 'fps', 'credit', 'debit'], billing_currency: 'HKD', billing_address: { country: 'HK', zipcode: '999077' }, return_url: 'https://example.com/success' }); ``` ### Example: Malaysia Checkout ```javascript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['touch_n_go', 'credit', 'debit'], billing_currency: 'MYR', billing_address: { country: 'MY', zipcode: '50450' }, return_url: 'https://example.com/success' }); ``` ### Requirements A method appears at checkout only when all of these are true: 1. The **billing country** matches the method's market: `PH` for GCash, `HK` for Alipay HK and FPS, `MY` for Touch 'n Go. 2. The **billing currency** matches the method: PHP, HKD (or CNY for FPS), or MYR. 3. For Alipay HK, FPS, and Touch 'n Go, the checkout is a **one-time payment**, not a subscription. GCash appears on both. 4. **[Adaptive Currency](/features/adaptive-currency)** is enabled. Without it, `billing_currency` is ignored, and checkout can't bill in PHP, HKD, CNY, or MYR. > [!WARNING] > > If Adaptive Currency is disabled, customers in these markets are not billed in their local currency, and none of these methods appear. ## Testing **1. Enable test mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. **2. Set the billing country and currency** Create a one-time checkout with the billing address country and billing currency for the method you are testing: | Method | Billing Country | Billing Currency | | :- | :- | :- | | GCash | `PH` | `PHP` | | Alipay HK | `HK` | `HKD` | | FPS | `HK` | `HKD` or `CNY` | | Touch 'n Go | `MY` | `MYR` | Include the method type in `allowed_payment_method_types`. To test GCash on a subscription, use a subscription product. Alipay HK, FPS, and Touch 'n Go are not offered on subscription checkouts. **3. Select the method and confirm** Select the payment method at checkout and click **Pay**. A QR code opens in a full-screen overlay with a 10-minute countdown, and checkout checks the payment status while the overlay is open. **4. Verify the checkout behavior** Confirm that the method appears only for the matching country and currency, and that the QR code renders. > [!NOTE] > > Test-mode QR codes come from the wallet provider's test environment and may behave differently from a live payment. ## Best Practices > [accordion] Lead with the local wallet > > In the Philippines and Malaysia, many customers expect to pay with a local wallet. List GCash or Touch 'n Go next to cards on checkouts for these markets. > [accordion] Offer both Hong Kong methods > > Alipay HK and FPS serve different customers: wallet users and bank-transfer users. Include both on HKD checkouts so each customer sees the method they prefer. > [accordion] Keep cards on subscription checkouts > > Alipay HK, FPS, and Touch 'n Go are one-time only, so a subscription checkout in Hong Kong or Malaysia that lists only these methods has no method to show. Include `credit` and `debit` for recurring plans. In the Philippines, list `gcash` next to cards. > [accordion] Match currency to region > > These methods require their local billing currency. If your catalog is priced in USD or EUR, enable Adaptive Currency so customers are quoted and billed in PHP, HKD, CNY, or MYR. ## Troubleshooting > [accordion] Method not appearing at checkout > > **Check:** > > 1. Is the billing country `PH`, `HK`, or `MY`, matching the method? > 2. Is the billing currency PHP, HKD, CNY, or MYR, matching the method? > 3. For Alipay HK, FPS, or Touch 'n Go, is this a one-time payment? These three don't appear on subscriptions. > 4. Is the method (`gcash`, `ali_pay_hk`, `fps`, or `touch_n_go`) included in `allowed_payment_method_types`? > 5. Is Adaptive Currency enabled? > 6. Does the amount meet the currency minimum in [Supported Methods](#supported-methods)? > > **Solution:** Remove `allowed_payment_method_types` temporarily to see every eligible method, then find the condition that fails. > [accordion] Alipay HK missing on a CNY checkout > > **Cause:** Alipay HK settles in HKD only. A checkout billed to Hong Kong in CNY offers FPS but never Alipay HK. > > **Solution:** Bill in HKD to offer Alipay HK, or include `fps` for CNY checkouts in Hong Kong. > [accordion] Wallet missing on a subscription > > **Cause:** Alipay HK, FPS, and Touch 'n Go are one-time only and are not offered for recurring billing. GCash is offered on subscriptions billed to `PH` in PHP. > > **Solution:** Use `credit` and `debit` for subscriptions in Hong Kong and Malaysia. If GCash is missing on a Philippines subscription, check the billing country, currency, and `allowed_payment_method_types`. > [accordion] Payment not confirming > > **Cause:** The customer must scan the QR code and approve the payment in a wallet or banking app. If the customer closes the app before approving, the payment stays incomplete. > > **Solution:** Use webhooks for the final payment status instead of the return redirect. See the [Webhooks guide](/developer-resources/webhooks). ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > See all supported payment methods. > [card] [Adaptive Currency](/features/adaptive-currency) > > Bill customers in their local currency, including PHP, HKD, CNY, and MYR. > [card] [Checkout Guide](/developer-resources/checkout-session) > > Complete checkout implementation guide. > [card] [Testing Process](/miscellaneous/testing-process) > > Test data and checkout testing guidance. # Buy Now Pay Later (BNPL) Source: https://docs.dodopayments.com/features/payment-methods/bnpl Offer Klarna, Afterpay, and Billie so customers can pay over time while the provider pays the full amount upfront. Covers eligibility, minimums, and testing. Buy Now Pay Later (BNPL) lets customers split a purchase into installments or pay later, while the BNPL provider pays the full amount upfront. Offering BNPL can raise average order value and conversion on eligible transactions. ## Why Offer BNPL? > [card] Higher AOV > > Customers tend to spend more when they can spread payments over time. > [card] Better Conversion > > Paying over time removes friction at checkout, especially for high-ticket items. > [card] No Credit Risk > > The BNPL provider takes the credit risk and collects the installments. The provider pays the full amount upfront. ## Supported Providers Dodo Payments offers three BNPL providers. Each has its own countries, currencies, and minimum amount. ### Klarna | Feature | Details | | :- | :- | | **Availability** | US and 18 European countries | | **Currencies** | USD, EUR, GBP, DKK, NOK, SEK, CZK, PLN, CHF | | **Minimum** | More than \$50 (\$50.01) on USD checkouts. For other currencies, Klarna's own limits apply | | **Subscriptions** | Yes | **Supported Countries:** Austria, Belgium, Czech Republic, Denmark, Finland, France, Germany, Greece, Ireland, Italy, Netherlands, Norway, Poland, Portugal, Spain, Sweden, Switzerland, United Kingdom, United States USD checkouts show Klarna only when the billing country is the US. **Payment Options:** * **Pay in 4**: Four interest-free payments. * **Pay in 30 days**: The full amount is due in 30 days. * **Financing**: Longer-term installment plans. Klarna decides which options a customer sees based on country, currency, and amount. ### Afterpay (Clearpay) | Feature | Details | | :- | :- | | **Availability** | US, UK | | **Currencies** | USD, GBP | | **Minimum** | More than \$50 (\$50.01) on USD checkouts. For GBP, Clearpay's own limits apply | | **Subscriptions** | No | USD checkouts show Afterpay only when the billing country is the US. **Payment Options:** * **Pay in 4**: Four interest-free payments, one every two weeks. > [!NOTE] > > In the UK, Afterpay operates as Clearpay and uses the same API type, `afterpay_clearpay`. ### Billie | Feature | Details | | :- | :- | | **Availability** | Global | | **Currencies** | GBP | | **Minimum** | None | | **Subscriptions** | No | **About Billie:** Billie is a business-to-business (B2B) BNPL provider. It lets business buyers pay on invoice terms instead of at checkout. **Payment Options:** * **Invoice Payment**: The buyer pays within the agreed payment terms. * **Flexible Terms**: Payment schedules suited to businesses. ## Configuration To offer BNPL, include the provider's type in `allowed_payment_method_types`, or omit the parameter to show every eligible method. ### API Method Types | Type | Provider | | :- | :- | | `klarna` | Klarna | | `afterpay_clearpay` | Afterpay / Clearpay | | `billie` | Billie (B2B) | ### Example This session offers Klarna and Afterpay to a US customer, with cards as a fallback: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: [ 'klarna', 'afterpay_clearpay', 'credit', 'debit' ], customer: { email: 'customer@example.com', name: 'Jane Smith' }, billing_address: { country: 'US', zipcode: '10001' }, return_url: 'https://example.com/success' }); ``` > [!WARNING] > > Always include `credit` and `debit` as fallbacks. Not every customer is eligible for BNPL, and transactions below a provider's minimum don't qualify. If no listed method is available, checkout fails. ## Transaction Amount Limits Dodo Payments applies these minimums to USD checkouts: | Provider | Minimum | Maximum | | :- | :- | :- | | Klarna | \$50.01 | — | | Afterpay | \$50.01 | — | For other currencies, the provider's own limits apply. When a transaction falls outside a provider's limits: * The BNPL option doesn't appear at checkout. * No error is returned. The option doesn't show. * Card payments remain available. This is expected. Don't include a BNPL method in `allowed_payment_method_types` if your product price is unlikely to fall within that provider's range. ## How Installments Work The BNPL provider approves the customer, pays the full amount, and collects the installments from the customer: ```mermaid theme={null} sequenceDiagram participant Customer participant Checkout participant Dodo participant BNPL Provider Customer->>Checkout: Select Klarna/Afterpay Checkout->>Dodo: Process payment Dodo->>BNPL Provider: Create installment plan BNPL Provider->>Customer: Approve/Deny based on credit BNPL Provider->>Dodo: Full payment (if approved) Dodo->>You: Payout (full amount) BNPL Provider->>Customer: Collect installments over time ``` **Key points:** * The BNPL provider pays the **full amount upfront**, and it reaches you in your regular payout. * The BNPL provider handles **credit risk and collections**. * The customer repays the provider directly, typically in **4 installments**. * If a customer misses an installment, the provider takes the loss, not you. ## Testing Use these details to test BNPL in test mode. ### Klarna Test Data | Field | Approved | Denied | | :- | :- | :- | | **Date of Birth** | 07-10-1970 | 07-10-1970 | | **First Name** | Test | Test | | **Last Name** | Person-us | Person-us | | **Email** | [customer@email.us](mailto:customer@email.us) | [customer+denied@email.us](mailto:customer+denied@email.us) | | **Street** | Amsterdam Ave | Amsterdam Ave | | **House Number** | 509 | 509 | | **City** | New York | New York | | **State** | New York | New York | | **Postal Code** | 10024-3941 | 10024-3941 | | **Phone** | +13106683312 | +13106354386 | > [!NOTE] > > On a USD checkout, the transaction must be more than \$50 (\$50.01) for Klarna to appear. ### Afterpay Testing **1. Select Afterpay** Choose Afterpay in checkout and click **Pay**. **2. Test a Successful Payment** Use any valid email address and shipping address. **3. Test Failed Authentication** To test a failure, close the Afterpay modal on the redirect page. The payment status moves from `requires_customer_action` to `requires_payment_method`. ## Best Practices > [accordion] Target high-ticket items > > BNPL works best for products priced \$100 to \$1,000, where paying over time matters most to customers. > [accordion] Show installment amounts > > "4 payments of \$25" persuades more than "\$100 with Klarna". Show the per-payment amount where you can. > [accordion] Don't force BNPL for low-value products > > On USD checkouts, BNPL doesn't appear for \$50 or less. Under \$100, most customers prefer cards. Promote BNPL on higher-priced items. > [accordion] Collect billing address > > BNPL providers use billing details for credit checks. Collect the full billing address at checkout. > [accordion] Set clear expectations > > Make clear to customers that the credit agreement is with Klarna or Afterpay, not with you. ## Limitations BNPL depends on the provider's approval and on the checkout's currency and country. ### No Subscriptions Afterpay and Billie **don't support recurring payments**. Klarna supports subscriptions. For other subscription products, use cards or another method that supports recurring payments. ### Credit-Based Approval BNPL providers run a credit check when the customer selects them, and not every customer is approved. Approval depends on: * The customer's credit history with the provider. * The transaction amount. * The customer's location. ### Currency & Country Mapping Each currency is limited to its matching region: | Currency | Supported Countries | | :- | :- | | **USD** | United States only | | **EUR** | Eurozone countries (Austria, Belgium, Finland, France, Germany, Greece, Ireland, Italy, Netherlands, Portugal, Spain) | | **GBP** | United Kingdom only | Klarna's other currencies (DKK, NOK, SEK, CZK, PLN, CHF) work in their own countries. > [!NOTE] > > For example, a USD transaction shows BNPL options only to customers in the US. A EUR transaction works only for customers in the Eurozone countries above. A GBP transaction works only for customers in the UK. | Provider | Supported Currencies | | :- | :- | | Klarna | USD, EUR, GBP, DKK, NOK, SEK, CZK, PLN, CHF | | Afterpay | USD (US), GBP (UK) | ## Troubleshooting > [accordion] BNPL not appearing at checkout > > **Check:** > > 1. Is the amount within the provider's range? On USD checkouts, Klarna and Afterpay need more than \$50 (\$50.01). > 2. Is the customer in a supported country? On USD checkouts, the billing country must be the US. > 3. Does the provider support the currency? > 4. Is the BNPL method included in `allowed_payment_method_types`? > 5. For subscriptions, is the provider Klarna? Afterpay and Billie are one-time only. > > **Solution:** Most often, the amount is below the minimum or above the maximum. Confirm that the amount falls within the provider's range. > [accordion] Customer denied by BNPL provider > > **Causes:** > > * Insufficient credit history with the provider. > * Too many active installment plans. > * Failed identity verification. > > **Solution:** Some denials are expected. Keep card payments available as a fallback. Don't show customers the specific reason for a denial. > [accordion] Payment stuck in pending > > **Cause:** The customer didn't finish the BNPL provider's authentication flow. > > **Solution:** Wait for the `payment.succeeded` or `payment.failed` webhook for the final status. If the payment doesn't complete, the customer can retry or use a different method. ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > All supported payment methods. > [card] [Checkout Guide](/developer-resources/checkout-session) > > Create and customize checkout sessions. > [card] [Testing Process](/miscellaneous/testing-process) > > Test data for every payment method. > [card] [Adaptive Currency](/features/adaptive-currency) > > Currency support and conversion. # Credit & Debit Cards Source: https://docs.dodopayments.com/features/payment-methods/cards Accept major credit and debit card networks worldwide with Dodo Payments. Covers 3D Secure, saved cards, tokenization, test cards, and regional networks. Cards are available on every Dodo Payments checkout, in every supported country and currency. Dodo Payments accepts the major card networks, replaces card numbers with tokens, and runs the checks that card payments need, so you don't handle raw card data. ## Supported Card Networks Dodo Payments accepts global networks and several regional networks. ### Global Networks | Network | Coverage | | :- | :- | | **Visa** | Global leader, 4B+ cards worldwide | | **Mastercard** | Global reach, strong security features | | **American Express** | Premium cardholders, higher spending | | **Discover** | US-focused, growing globally | | **JCB** | Leading in Japan, expanding across Asia | | **UnionPay** | Dominant in China | | **Diners Club** | Premium international travelers | ### Regional Networks | Network | Region | | :- | :- | | **Interac** | Canada's debit network | | **Cartes Bancaires** | France's national network | | **Korean Local Cards** | Korean domestic networks | | **Rupay** | India's national network | ## Configuration Cards use two values in `allowed_payment_method_types`: | Type | Description | | :- | :- | | `credit` | All credit cards | | `debit` | All debit cards | This session offers card payments only: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['credit', 'debit'], return_url: 'https://example.com/success' }); ``` > [!TIP] > > Include both `credit` and `debit` unless you have a specific reason to exclude one. Many customers prefer to pay by debit card. ## 3D Secure Authentication 3D Secure (3DS) asks the cardholder's bank to confirm the cardholder's identity, for example with a one-time code, a biometric check, or approval in the bank's app. This reduces fraud and chargebacks. ### When 3DS is Triggered Dodo Payments requests 3DS when: * The card network requires it. * A regional regulation requires it, such as PSD2 in Europe. * The transaction is flagged as high-risk. ### Force 3DS To require 3DS on every card payment for your business, turn on **3D Secure** under **Settings → Pricing**. To override that setting for one checkout session, pass `force_3ds`: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], force_3ds: true, return_url: 'https://example.com/success' }); ``` > [!NOTE] > > Requiring 3DS on every transaction reduces fraud but can lower conversion, because some customers abandon checkout during authentication. ### View the 3DS Result [Get Payment](/api-reference/payments/get-payments-1), [List Payments](/api-reference/payments/get-payments), and the `payment.*` webhooks return the 3DS result of each payment in three fields: | Field | Values | | - | - | | `three_ds_status` | `authenticated`, `attempt_acknowledged`, `exempted`, `failed`, `not_supported`, or `processing_error` | | `three_ds_flow` | `challenge` or `frictionless` | | `three_ds_version` | The 3DS protocol version, for example `2.2.0` | All three fields are `null` when the processor reports no 3DS data for the payment. In the dashboard, the payment detail page shows a **3D Secure** section with the **Authentication result**, **Authentication flow**, and **3DS version** when the payment has 3DS data. ### Handling Authentication Failures When a payment needs 3DS authentication, the payment moves through intermediate states before it succeeds or fails: | Status | Meaning | What to do | | - | - | - | | `requires_customer_action` | The customer must complete a 3DS challenge | Have the customer complete authentication during checkout | | `requires_payment_method` | The customer never provided a payment method (didn't enter details or abandoned the prompt). This is usually a drop-off, not a decline | Re-engage the customer to complete checkout. See [Abandoned Cart Recovery](/features/recovery/abandoned-cart-recovery) | If authentication doesn't complete, the payment fails with one of these decline codes: * `AUTHENTICATION_FAILURE`: the customer could not be authenticated. * `AUTHENTICATION_REQUIRED`: authentication is required but was not performed. * `AUTHENTICATION_TIMEOUT`: the customer did not respond in time. The [Transaction Failures](/api-reference/transaction-failures) reference lists the recommended action for each code. #### At Checkout vs. on Renewal * **At checkout (customer present):** The 3DS challenge appears during checkout. If it fails, ask the customer to retry or use another card. * **On subscription renewal (customer not present):** A 3DS challenge can't be shown in real time. If a renewal requires authentication and fails, the subscription moves to `on_hold`, or to `past_due` first if you set a [grace period](/features/subscription#grace-period). To recover it, prompt the customer to return and update their payment method. See [Handle Payment Failures](/developer-resources/handle-payment-failures) and [Subscription Dunning](/features/recovery/subscription-dunning). ## Saved Payment Methods Returning customers can pay with a card saved from an earlier checkout. > [card] Tokenized > > Original card numbers are never stored. > [card] PCI Compliant > > Dodo Payments handles PCI compliance. > [card] Customer-Scoped > > Each saved card belongs to one customer. ### Enable Saved Cards To show a returning customer's saved cards at checkout, pass `show_saved_payment_methods: true` with the existing `customer_id`. The default is `false`. ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], show_saved_payment_methods: true, customer: { customer_id: 'cus_existing_123' }, return_url: 'https://example.com/success' }); ``` ### One-Click Purchases To charge a saved card without showing checkout, pass its `payment_method_id` with `confirm: true` and the existing `customer_id`. The session charges the card directly and returns no `checkout_url`, so use webhooks to learn the payment result. ```javascript theme={null} // `client` is an initialized DodoPayments client. // Get the customer's saved payment methods const methods = await client.customers.retrievePaymentMethods('cus_123'); // Charge the first saved card const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], customer: { customer_id: 'cus_123' }, payment_method_id: methods.items[0].payment_method_id, confirm: true, return_url: 'https://example.com/success' }); ``` ## Testing Use these cards in test mode. For more test data, see [Testing Process](/miscellaneous/testing-process). > [tab] Successful Payments > > | Region | Brand | Card Number | Expiry | CVV | > | :- | :- | :- | :- | :- | > | US | Visa | `4242424242424242` | 06/32 | 123 | > | US | Mastercard | `5555555555554444` | 06/32 | 123 | > | India | Visa | `4576238912771450` | 06/32 | 123 | > | India | Mastercard | `5409162669381034` | 06/32 | 123 | > [tab] Declined Payments > > | Region | Brand | Card Number | Scenario | > | :- | :- | :- | :- | > | US | Visa | `4000000000000002` | Generic decline | > | US | Visa | `4000000000009995` | Insufficient funds | > | India | Visa | `4706131211212123` | Generic decline | > | India | Mastercard | `5105105105105100` | Generic decline | > [!WARNING] > > Test cards work only in test mode. In live mode, a payment made with a test card fails. ## Security & Compliance Dodo Payments applies these protections to card payments: | Feature | Description | | :- | :- | | **PCI DSS Level 1** | The highest level of PCI DSS certification | | **Tokenization** | Card numbers are tokenized on entry | | **Fraud Scoring** | Real-time risk assessment | | **CVV Validation** | Security code verification | | **3D Secure** | Cardholder authentication | ## Best Practices > [accordion] Accept all major networks > > Don't restrict card types unless you need to. Customers expect their preferred card to work. > [accordion] Display card logos > > Show Visa, Mastercard, and Amex logos on your site to build trust. > [accordion] Handle declines gracefully > > Show clear error messages. Don't show raw error codes to customers. > [accordion] Enable saved cards for returning customers > > Saved payment methods make repeat purchases faster for returning customers. ## Troubleshooting > [accordion] Card declined > > **Causes:** Insufficient funds, an expired card, an incorrect CVV, or the bank's fraud protection. > > **Solution:** Ask the customer to check their details or try a different card. Look up the decline's error code and its recommended action in the [Transaction Failures](/api-reference/transaction-failures) reference. See [Handle Payment Failures](/developer-resources/handle-payment-failures) to handle declines in code. > [accordion] 3DS authentication failed > > **Causes:** The customer abandoned the challenge, the bank's system was unavailable, or the challenge timed out. > > **Solution:** Retry, or ask the customer to contact their bank. See [Handling Authentication Failures](#handling-authentication-failures) for the payment states and decline codes involved. > [accordion] Card not supported > > **Causes:** The regional network isn't supported, or the card is a restricted prepaid card. > > **Solution:** Ask the customer to try a card from a major network. ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > All supported payment methods. > [card] [Upsells & Downsells](/features/upsells-and-downsells) > > One-click purchases with saved cards. > [card] [Testing Process](/miscellaneous/testing-process) > > Test data for every payment method. > [card] [Subscriptions](/features/subscription) > > Recurring billing with cards. # Digital Wallets Source: https://docs.dodopayments.com/features/payment-methods/digital-wallets Accept Apple Pay, Google Pay, Amazon Pay, Cash App Pay, and RevolutPay at checkout. Covers availability, Apple Pay domain verification, and testing. Digital wallets let customers pay with a card or account already saved on their device, without typing card details. The wallet sends a token instead of the card number, and the customer confirms the payment with a tap or biometric check. ## Supported Wallets Dodo Payments shows each wallet only when the checkout matches its country, currency, and payment type: | Wallet | Availability | Currencies | Subscriptions | Setup Required | | :- | :- | :- | :-: | :- | | **Apple Pay** | Global, including India | All, including INR | Yes | Domain verification for inline checkout | | **Google Pay** | Global (except India) | All | Yes | None | | **Amazon Pay** | Global (except India) | USD, EUR, GBP, AUD, CHF, DKK, HKD, JPY, NOK, NZD, SEK, ZAR | No | None | | **Cash App Pay** | US only | USD | Yes | None | | **RevolutPay** | Global | GBP | No | None | > [!WARNING] > > PayPal is temporarily unavailable for new transactions. ## Apple Pay Apple Pay lets customers pay with cards saved in Apple Wallet and confirm with Face ID or Touch ID. > [!NOTE] > > Apple Pay appears for subscriptions even when the first charge is \$0, such as a free trial, so the payment mandate is set up at signup. For one-time payments, Apple Pay appears only when the amount is greater than \$0. ### Requirements * **Devices:** iOS 17 or later, iPadOS 17 or later, or Safari 17 or later on macOS. In India, Apple requires iPhone XR or later on iOS 18 or later. * **Protocol:** The page must load over HTTPS. * **Domain:** For inline checkout, the domain must be verified with Apple. ### Apple Pay in India Customers in India can pay with Apple Pay on checkouts billed in INR. Apple Pay in India works under these conditions: * **Currency:** The checkout is billed in INR. A payment billed in INR must meet the [INR minimum](/features/payment-methods/india#supported-methods). * **Cards:** The customer has a card in Apple Wallet from an Indian bank that supports Apple Pay. Apple controls which banks and cards are eligible. * **Desktop:** In a desktop browser, customers can scan a code with their iPhone and confirm the payment on the phone. * **Subscriptions:** Apple Pay subscriptions in INR run on [RBI mandates](/features/payment-methods/india#subscriptions-with-rbi-mandates). Each renewal charge completes about 48 hours after the renewal date, as with other Indian-issued cards. To bill a customer in India in INR, follow the [India Payment Methods](/features/payment-methods/india) requirements for billing country and Adaptive Currency. ### Domain Verification > [!NOTE] > > Domain verification is required only for **inline (embedded) checkout**. Hosted checkout and payment links show Apple Pay without it. > [!WARNING] > > Apple Pay is not available in overlay checkout. To offer Apple Pay, use inline checkout, hosted checkout, or a payment link. To verify a domain for inline checkout, follow these steps in the dashboard: **1. Open Apple Pay Domains** Go to **Settings → Payment Methods**. On the **Apple Pay** row, click **Manage domains**. ![Manage domains button on the Apple Pay row in Payment Methods settings](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/manage-domains.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=a96c60ee0eef744336df955f5148c573) Open Apple Pay domains from the Apple Pay row **2. Download the Domain Association File** In the **Apple Pay domains** panel, click **Download file**. ![Apple Pay domains panel with the Download file button](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/wallet-domains-panel.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=fb37db780807c0e92ffaa57d2140b91d) Download the Apple Pay domain association file **3. Register Your Domain** Click **Register domain**, enter the domain where you embed checkout (for example, `shop.example.com`), and click **Continue**. ![Register a domain form with a domain entered](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/register-domain.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=9c2bf22e51c8ff188a4e11b36b24c136) Register the domain where you embed checkout **4. Host the File on Your Domain** Upload the file to your server at this path: ```text theme={null} https://shop.example.com/.well-known/apple-developer-merchantid-domain-association ``` Serve the file over HTTPS, without redirects, with `Content-Type: application/octet-stream` or `text/plain`. **5. Verify the Domain** Click **Verify domain**. Dodo Payments checks the hosted file and submits your domain to Apple. ![Verify your domain screen with the association file host path and Verify domain button](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/verify-domain.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=e9fcfe5b68320a0a22c644fb935c840b) Verify the hosted association file **6. Confirm It's Active** When the status shows **Active**, Apple Pay is live on that domain. To turn Apple Pay on or off for one domain, use its **Enabled** toggle. ![Apple Pay domains list showing domains with an Active status and Enabled toggles](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/domains-active.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=51a2bf473b1faf3db5776bbfa7140854) Verified domains show an Active status **7. Test the Integration** 1. Open checkout on an Apple device. 2. Confirm that the Apple Pay button appears. 3. Complete a test transaction. ### Configuration To limit a checkout session to Apple Pay and cards, pass `allowed_payment_method_types`: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['apple_pay', 'credit', 'debit'], return_url: 'https://example.com/success' }); ``` ## Google Pay Google Pay lets customers pay with cards saved in their Google account. ### Requirements * **Browsers:** Chrome on desktop and Android, and Firefox on desktop. Checkout doesn't show Google Pay in Safari or in any browser on iOS. On those browsers, customers can pay with Apple Pay or a card. * **Devices:** Android devices with the Google Pay app. * **Settings:** In Chrome, **Allow sites to check if you have payment methods saved** must be on. ### Configuration To limit a checkout session to Google Pay and cards, pass `allowed_payment_method_types`: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['google_pay', 'credit', 'debit'], return_url: 'https://example.com/success' }); ``` > [!NOTE] > > Google Pay needs no domain verification. ## Amazon Pay Amazon Pay lets customers check out with the payment methods saved in their Amazon account. ### Availability * **Region:** Global, except India. * **Currencies:** USD, EUR, GBP, AUD, CHF, DKK, HKD, JPY, NOK, NZD, SEK, ZAR. Which currencies a checkout offers depends on the processor that serves it. * **Subscriptions:** Not supported. ### Configuration To limit a checkout session to Amazon Pay and cards, pass `allowed_payment_method_types`: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['amazon_pay', 'credit', 'debit'], return_url: 'https://example.com/success' }); ``` ## Cash App Pay Cash App Pay lets US customers pay from their Cash App account. ### Availability * **Region:** US only. The billing country must be the US. * **Currency:** USD only. * **Subscriptions:** Supported. ### Configuration To limit a checkout session to Cash App Pay and cards, pass `allowed_payment_method_types`: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['cashapp', 'credit', 'debit'], return_url: 'https://example.com/success' }); ``` ## RevolutPay RevolutPay lets Revolut users pay from their Revolut account balance or linked cards. ### Availability * **Region:** Global. * **Currency:** GBP only. * **Subscriptions:** Not supported. ### Configuration To limit a checkout session to RevolutPay and cards, pass `allowed_payment_method_types`: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['revolut_pay', 'credit', 'debit'], return_url: 'https://example.com/success' }); ``` ## Testing In test mode, wallet payments run through the same checkout flow without moving real money. ### Apple Pay Testing **1. Use Test Mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. **2. Add a Card to Apple Wallet** Add a real card to Apple Wallet. In test mode, the card isn't charged. **3. Complete a Test Purchase** Open checkout on an Apple device and complete the Apple Pay flow. > [!WARNING] > > Apple Pay requires HTTPS. It doesn't appear on `localhost` unless the page is served over HTTPS. ### Google Pay Testing **1. Join the Test Card Group** [Join the Google Pay test card group](https://groups.google.com/g/googlepay-test-mode-stub-data) to have test cards added to your wallet. **2. Enable Test Mode** Use API keys created in test mode. **3. Complete a Test Purchase** Select one of the test cards in Google Pay to complete the transaction. ### Amazon Pay & Cash App Pay Use your test mode API keys and follow the standard checkout flow. Test transactions are simulated, and no real charge occurs. ## SDK Support Wallet availability depends on how you present checkout. ### Web SDKs Digital wallets work in: * Overlay Checkout, except Apple Pay. * Inline Checkout. Apple Pay requires [domain verification](#domain-verification). * Direct API integration with hosted checkout. ### Mobile SDKs (Checkout) The [Android](/developer-resources/sdks/android), [iOS](/developer-resources/sdks/ios), [React Native](/developer-resources/sdks/react-native), and [Flutter](/developer-resources/sdks/flutter) checkout SDKs open Dodo Payments hosted checkout in the platform's system browser (`SFSafariViewController` on iOS, Chrome Custom Tabs on Android), not in a WebView. Apple Pay and Google Pay work there the same way they do on the web. See the [Mobile Integration Guide](/developer-resources/mobile-integration) for setup. ## Best Practices > [accordion] Prioritize wallets on mobile > > Mobile customers expect Apple Pay and Google Pay. Show these options prominently on mobile checkouts. > [accordion] Complete domain verification early > > If you use inline checkout, verify your domain for Apple Pay during development, not on launch day. > [accordion] Always include card fallbacks > > Not every customer has a digital wallet. Include `credit` and `debit` in `allowed_payment_method_types`. > [accordion] Test on real devices > > Simulators don't fully replicate wallet behavior. Test on real iOS and Android devices before launch. > [accordion] Handle wallet unavailability > > A wallet doesn't appear on an unsupported device or when the customer has no saved cards. Keep other payment methods visible for these customers. ## Troubleshooting > [accordion] Apple Pay button not appearing > > **Check:** > > 1. For inline checkout, is the domain verified in **Manage domains**? > 2. Does the page load over HTTPS? > 3. Is the device on iOS 17, iPadOS 17, or Safari 17 or later? > 4. Does the customer have cards in Apple Wallet? > 5. Is `apple_pay` included in `allowed_payment_method_types`? > 6. Is the checkout an overlay? Apple Pay isn't available in overlay checkout. > > **Solution:** Complete domain verification and serve the page over HTTPS. Test on a real Apple device. > [accordion] Apple Pay domain stuck on Pending > > After you click **Verify domain**, Dodo Payments fetches the association file from your domain and submits the domain to Apple. A domain that stays on **Pending** usually has a file that Dodo Payments can't fetch as expected. > > **Check:** > > 1. The file is reachable at `https:///.well-known/apple-developer-merchantid-domain-association`. > 2. It is served over HTTPS with a valid certificate. > 3. It resolves without redirects. A redirect to `www`, to another host, or to an error page fails the check. > 4. It is served as `Content-Type: application/octet-stream` or `text/plain`, not `text/html`. > 5. It is the file downloaded from **Manage domains** for this business, not one reused from another account or provider. > > To confirm the file is publicly reachable, request the URL from outside your own network, such as in a private browsing window. Staging passwords, authentication walls, and firewall rules often let the request succeed for you but fail for Dodo Payments. > > **Solution:** Fix the hosting issue, then click **Verify domain** again. If the domain doesn't become **Active** after a successful check, contact [support@dodopayments.com](mailto:support@dodopayments.com) with the domain name. > [accordion] Google Pay button not appearing > > **Check:** > > 1. Is the customer using a supported browser? Google Pay doesn't appear in Safari or in any browser on iOS. > 2. Does the customer have cards in Google Pay? > 3. Is the Chrome setting **Allow sites to check if you have payment methods saved** on? > 4. Is `google_pay` included in `allowed_payment_method_types`? > > **Solution:** Check the browser and the customer's Google Pay setup. > [accordion] Wallet payment failed > > **Common causes:** > > * The card in the wallet is expired or invalid. > * The bank declined the transaction. > * A network connection problem interrupted the payment. > > **Solution:** Ask the customer to check the card in their wallet or to use a different payment method. > [accordion] Wrong device type > > Digital wallets appear only on compatible devices: > > * Apple Pay: Apple devices only. > * Google Pay: Chrome or Android devices. > > **Solution:** This is expected. Keep card payments available as a fallback. ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > All supported payment methods. > [card] [Overlay Checkout](/developer-resources/overlay-checkout) > > Open checkout as an overlay on your page. > [card] [Testing Process](/miscellaneous/testing-process) > > Test data for every payment method. > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > Open hosted checkout in the system browser, where Apple Pay and Google Pay work as on the web. # European Payment Methods Source: https://docs.dodopayments.com/features/payment-methods/europe Accept iDEAL, Bancontact, EPS, Multibanco, BLIK, SEPA Direct Debit, and Satispay. Learn which currency, country, and billing type each method needs. Accept iDEAL, Bancontact, EPS, Multibanco, BLIK, SEPA Direct Debit, and Satispay to reach European customers who prefer to pay from their bank or a local payment app instead of a card. In markets where a local method is the most common way to pay online, offering it can raise conversion. ## Why Local European Payment Methods? > [card] Higher Conversion > > iDEAL is the most-used online payment method in the Netherlands. Without it, you lose Dutch customers who won't pay another way. > [card] Bank Authentication > > For bank-authenticated methods, the customer approves the payment in their banking app or on their bank's site. > [card] Real-Time Settlement > > Most methods on this page confirm the payment during checkout. SEPA Direct Debit and Multibanco ATM payments confirm later. ## Supported Methods Each method is offered only when the checkout matches its currency and billing type: | Method | Country | Currency | Subscriptions | | :- | :- | :- | :-: | | **iDEAL** | Netherlands | EUR | No | | **Bancontact** | Belgium | EUR | No | | **EPS** | Austria | EUR | No | | **Multibanco** | Portugal | EUR | No | | **BLIK** | Poland | PLN | No | | **SEPA Direct Debit** | Eurozone | EUR | No | | **Satispay** | Europe (Italy) | EUR | Yes | ## iDEAL (Netherlands) iDEAL is the most-used online payment method in the Netherlands. It connects directly to all major Dutch banks, and the customer approves each payment with their own bank. ### How It Works The customer selects iDEAL, picks their bank, and authenticates there: ```mermaid theme={null} sequenceDiagram participant Customer participant Checkout participant Dodo participant iDEAL participant Bank Customer->>Checkout: Select iDEAL Checkout->>Dodo: Create payment Dodo->>iDEAL: Initiate payment iDEAL->>Customer: Redirect to bank selection Customer->>Bank: Select bank & authenticate Bank->>iDEAL: Payment confirmed iDEAL->>Dodo: Success callback Dodo->>Checkout: Payment complete ``` ### Supported Banks iDEAL works with all major Dutch banks, including: * ABN AMRO * ASN Bank * Bunq * ING * Knab * Rabobank * RegioBank * Revolut * SNS * Triodos Bank * Van Lanschot ### Configuration To offer iDEAL, include `ideal` in `allowed_payment_method_types` and bill in EUR: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['ideal', 'credit', 'debit'], billing_currency: 'EUR', billing_address: { country: 'NL', zipcode: '1012JS' }, return_url: 'https://example.com/success' }); ``` ## Bancontact (Belgium) Bancontact is Belgium's national payment scheme. Almost all Belgian banks use it for online payments. ### Features * Works with the Bancontact debit cards that Belgian customers already have * Supports payment in the Bancontact mobile app * Confirms the payment during checkout * Requires no extra registration from the customer ### Configuration To offer Bancontact, include `bancontact_card` and bill in EUR: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['bancontact_card', 'credit', 'debit'], billing_currency: 'EUR', billing_address: { country: 'BE', zipcode: '1000' }, return_url: 'https://example.com/success' }); ``` ## EPS (Austria) EPS (Electronic Payment Standard) lets Austrian customers pay by online bank transfer from their own bank. ### Features * Connects directly to Austrian banks * Confirms the payment during checkout * Has high trust among Austrian consumers ### Supported Banks EPS works with major Austrian banks, including: * Erste Bank * Bank Austria * Raiffeisen * BAWAG * Volksbank ### Configuration To offer EPS, include `eps` and bill in EUR: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['eps', 'credit', 'debit'], billing_currency: 'EUR', billing_address: { country: 'AT', zipcode: '1010' }, return_url: 'https://example.com/success' }); ``` ## Multibanco (Portugal) Multibanco is Portugal's interbank network. Customers can pay online, or pay a payment reference at an ATM. ### Payment Options Customers can complete a Multibanco payment in three ways: 1. **Online banking**: A bank transfer through the customer's internet banking. 2. **ATM payment**: The customer receives a payment reference and pays it at any Multibanco ATM. 3. **Mobile banking**: A payment in the customer's banking app. ### How ATM Payment Works For an ATM payment, the customer receives a payment reference like this one: ```text theme={null} Entity: 12345 Reference: 123 456 789 Amount: €50.00 ``` The customer pays with this reference at any Portuguese ATM or through online banking. The reference is valid for a limited time, which is shown to the customer with the reference. ### Configuration To offer Multibanco, include `multibanco` and bill in EUR: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['multibanco', 'credit', 'debit'], billing_currency: 'EUR', billing_address: { country: 'PT', zipcode: '1000-001' }, return_url: 'https://example.com/success' }); ``` > [!NOTE] > > A Multibanco ATM payment completes when the customer pays the reference, which can be well after checkout. Use webhooks to learn when the payment is confirmed. ## BLIK (Poland) BLIK is Poland's most popular mobile payment method. The customer pays with a one-time 6-digit code that they generate in their banking app. BLIK payments are billed in **PLN** (Polish złoty), not EUR. ### How It Works The customer generates a code in their banking app, enters it at checkout, and approves the payment in the app: ```mermaid theme={null} sequenceDiagram participant Customer participant Checkout participant Dodo participant BLIK participant BankApp Customer->>Checkout: Select BLIK Checkout->>Dodo: Create payment Customer->>BankApp: Generate 6-digit code Customer->>Checkout: Enter BLIK code Checkout->>Dodo: Submit code Dodo->>BLIK: Authorize payment BLIK->>BankApp: Confirmation request Customer->>BankApp: Approve payment BankApp->>BLIK: Payment confirmed BLIK->>Dodo: Success callback Dodo->>Checkout: Payment complete ``` ### Availability * **Billing currency:** PLN only * **Transaction type:** One-time payments only. BLIK isn't offered for subscriptions. * **Coverage:** All major Polish banks that support BLIK ### Configuration To offer BLIK, include `blik` and set `billing_currency` to `PLN`: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['blik', 'credit', 'debit'], billing_currency: 'PLN', billing_address: { country: 'PL', zipcode: '00-001' }, return_url: 'https://example.com/success' }); ``` > [!NOTE] > > BLIK requires a **PLN** billing currency, and Dodo Payments bills in PLN only when [Adaptive Currency](/features/adaptive-currency) is enabled. Enable Adaptive Currency so Polish customers are billed in PLN and BLIK becomes available. ## SEPA Direct Debit (Eurozone) SEPA Direct Debit lets customers in the Eurozone pay from their bank account instead of a card. It's offered on EUR checkouts for one-time payments, not for subscriptions, when the billing country is Austria, Belgium, Estonia, Finland, France, Germany, Ireland, Italy, Latvia, Lithuania, the Netherlands, Portugal, Slovakia, or Spain. > [!WARNING] > > **SEPA Direct Debit isn't instant. A payment takes up to 6 business days to confirm.** Unlike a card payment, the customer's authorization at checkout doesn't mean the money has cleared. Don't fulfill the order on the checkout redirect or on `payment.processing`. Wait for the `payment.succeeded` webhook. ### How It Works The customer authorizes the debit at checkout, and Dodo Payments then collects the funds from their bank account. The bank clears the debit asynchronously, so the payment stays in the `processing` state until it reaches a final outcome: ```mermaid theme={null} sequenceDiagram participant Customer participant Checkout participant Dodo participant Server as Your Server participant Bank Customer->>Checkout: Authorize SEPA debit Checkout->>Dodo: Create payment Dodo->>Checkout: Redirect (payment accepted, NOT settled) Dodo-->>Server: Webhook: payment.processing Note over Dodo,Bank: Bank clears the debit (up to 6 business days) Bank->>Dodo: Debit cleared Dodo-->>Server: Webhook: payment.succeeded Note over Server: Fulfill the order here ``` ### Payment Timeline A SEPA payment moves through these stages: | Stage | When | Payment status | What it means | | :- | :- | :- | :- | | **Authorization** | At checkout | `processing` | The customer approved the debit and was redirected back. The money has **not** moved yet, so don't fulfill. | | **Confirmation** | Up to **6 business days** later | `succeeded` | The bank cleared the debit. Fulfill the order now. | | **Failure** | Up to **6 business days** later | `failed` | The debit couldn't be collected, for example because of insufficient funds. Don't fulfill, and notify the customer. | Confirmation arrives days after the customer leaves your site, so your webhook handler, not the checkout redirect, must grant access. See [Handling the Confirmation Delay](#handling-the-confirmation-delay). ### Availability * **Billing currency:** EUR * **Transaction type:** One-time payments only. SEPA Direct Debit isn't offered for subscriptions. ### Configuration To offer SEPA Direct Debit, include `sepa` and bill in EUR: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['sepa', 'credit', 'debit'], billing_currency: 'EUR', billing_address: { country: 'DE', zipcode: '10115' }, return_url: 'https://example.com/success' }); ``` ### SEPA Test IBANs In test mode, enter one of these IBANs at checkout to force a specific outcome: | Test IBAN | Behavior | | :- | :- | | `DE89370400440532013000` | The payment succeeds. | | `DE08370400440532013003` | The payment succeeds after a delay of at least three minutes. | | `DE62370400440532013001` | The payment fails. | | `DE78370400440532013004` | The payment fails after a delay of at least three minutes. | | `DE35370400440532013002` | The payment succeeds, then is immediately disputed. | | `DE65370400440002222227` | The payment fails due to insufficient funds. | | `DE18370400440000066666` | The bank account is unusable, so the payment method can't be created. | To test country-specific behavior, use the success IBAN for another Eurozone country: | Country | Success IBAN | | :- | :- | | Austria | `AT611904300234573201` | | Belgium | `BE62510007547061` | | Estonia | `EE382200221020145685` | | Finland | `FI2112345600000785` | | France | `FR1420041010050500013M02606` | | Ireland | `IE29AIBK93115212345678` | | Luxembourg | `LU280019400644750000` | > [!NOTE] > > Use the delayed test IBANs to confirm that your webhook handler, not the checkout redirect, grants access. SEPA payments confirm long after the customer leaves checkout. ### Handling the Confirmation Delay SEPA settles up to 6 business days after checkout, so the browser redirect can't tell you whether a payment cleared. Drive fulfillment from webhook events instead. Switch on the event `type` and handle each stage: | Event Type | When it fires | What to do | | :- | :- | :- | | `payment.processing` | The customer authorized the debit at checkout and was redirected back. | **Don't fulfill.** Mark the order pending. Optionally, tell the customer that their payment is processing. | | `payment.succeeded` | The bank cleared the debit, up to 6 business days later. | Fulfill the order: grant access, provision the product, and send the receipt. | | `payment.failed` | The debit couldn't be collected. | Notify the customer and prompt a retry. Don't fulfill. | > [!TIP] > > Fulfill on **`payment.succeeded` from the webhook**, not on the checkout redirect or on `payment.processing`. The redirect happens as soon as the customer authorizes the debit, days before the money clears. The following Express handler verifies each event's signature with `client.webhooks.unwrap` before it acts on the event. For endpoint setup, see the [Webhooks guide](/developer-resources/webhooks). For every event, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). ```javascript Handling SEPA payment events expandable theme={null} import express from 'express'; import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, }); const app = express(); // markOrderPending, fulfillOrder, and markOrderFailed are your own order functions. app.post('/webhooks/dodo', express.raw({ type: 'application/json' }), async (req, res) => { let event; try { // Checks the webhook-id, webhook-signature, and webhook-timestamp headers. event = client.webhooks.unwrap(req.body.toString(), { headers: req.headers }); } catch { return res.status(400).send('Invalid signature'); } switch (event.type) { case 'payment.processing': { // SEPA debit authorized but NOT settled. This can last up to 6 business days. // Record the order as pending; do not grant access yet. await markOrderPending(event.data.payment_id); break; } case 'payment.succeeded': { // The debit cleared, so it's safe to fulfill now. await fulfillOrder(event.data.payment_id); break; } case 'payment.failed': { // The debit could not be collected (for example, insufficient funds). await markOrderFailed(event.data.payment_id); // Notify the customer and prompt a retry. break; } } res.json({ received: true }); }); ``` > [!WARNING] > > Set customer expectations at checkout. Access is granted only after the debit clears, so tell SEPA customers that their order is processing and that you'll notify them when the payment confirms. Otherwise, they may expect immediate access, as with a card payment. ## Satispay (Europe) Satispay is a European mobile payment network with its largest user base in Italy. Customers pay from the Satispay app without sharing card or bank details. Satispay payments are billed in **EUR**. ### Features * App-based payments that don't depend on card networks * Strong adoption in Italy, and growing use in other European markets * Support for both one-time payments and subscriptions ### Availability * **Billing currency:** EUR * **Transaction type:** One-time payments and subscriptions * **Amount:** From €0.50 to €999,999.99 per payment ### Configuration To offer Satispay, include `satispay` and bill in EUR: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['satispay', 'credit', 'debit'], billing_currency: 'EUR', billing_address: { country: 'IT', zipcode: '00100' }, return_url: 'https://example.com/success' }); ``` ## API Method Types Pass these values in `allowed_payment_method_types`: | Type | Method | Country | | :- | :- | :- | | `ideal` | iDEAL | Netherlands | | `bancontact_card` | Bancontact | Belgium | | `eps` | EPS | Austria | | `multibanco` | Multibanco | Portugal | | `blik` | BLIK | Poland | | `sepa` | SEPA Direct Debit | Eurozone | | `satispay` | Satispay | Europe (Italy) | ## Multi-Country European Checkout To sell in several European countries, include every regional method, plus cards as a fallback: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: [ 'ideal', // Netherlands 'bancontact_card', // Belgium 'eps', // Austria 'multibanco', // Portugal 'blik', // Poland (requires PLN billing currency) 'sepa', // Eurozone (one-time payments only) 'satispay', // Europe / Italy 'credit', // Fallback 'debit' // Fallback ], billing_currency: 'EUR', return_url: 'https://example.com/success' }); ``` Dodo Payments shows each customer only the methods that match their billing country and currency. A Dutch customer sees iDEAL, and a Belgian customer sees Bancontact. This session bills in EUR, so BLIK doesn't appear. ## Testing You can test European payment methods in test mode. The test flow simulates the bank authentication step. > [!NOTE] > > SEPA Direct Debit uses a different test flow. Instead of a simulated bank flow, you enter a test IBAN directly. See [SEPA Test IBANs](#sepa-test-ibans). > [!NOTE] > > Multibanco also uses a different test flow. Checkout shows a voucher instead of a bank flow, and the email you enter decides the result. See [Multibanco Test Emails](#multibanco-test-emails). **1. Enable Test Mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. **2. Set Appropriate Billing Address** Set the billing address country to match the payment method: * `NL` for iDEAL * `BE` for Bancontact * `AT` for EPS * `PT` for Multibanco * `PL` for BLIK (with PLN billing currency) * `IT` for Satispay **3. Complete the Test Flow** Follow the simulated bank authentication flow in test mode. ### Multibanco Test Emails After you click **Pay**, checkout shows a Multibanco voucher. In test mode, the email you enter decides the result: | Email | Result | | :- | :- | | Any email, for example `jenny@example.com` | Payment succeeds after about 3 minutes. | | `succeed_immediately@example.com` | Payment succeeds within a few seconds. | | `expire_immediately@example.com` | Payment fails within a few seconds. | | `expire_with_delay@example.com` | Payment fails after about 3 minutes. | | `fill_never@example.com` | Payment never completes. | To see the success page, use `succeed_immediately@example.com`, wait a few seconds, and tap **Done**. ## Best Practices > [accordion] Always include regional methods for target markets > > If you sell to Dutch customers, include iDEAL. Leaving it out is like not accepting Visa in the US: you lose a significant share of sales. > [accordion] Match currency to region > > Most European payment methods require EUR, so make sure your pricing supports EUR transactions. The one exception is BLIK, which is offered only with **PLN** (Polish złoty) billing. > [accordion] Handle redirects gracefully > > Most European methods redirect the customer to their bank or payment app. Make sure your return URL handling works for customers who abandon the flow midway. > [accordion] Provide card fallbacks > > Not every customer in Europe can use these regional methods, for example tourists and expats. Include `credit` and `debit` as fallbacks. If no method is available, the checkout session fails. > [accordion] Consider Multibanco timing > > A Multibanco ATM payment can take hours to complete. Don't block fulfillment on immediate payment. Use webhooks for asynchronous confirmation. > [accordion] Account for the SEPA 6-day delay > > SEPA Direct Debit takes up to **6 business days** to confirm. Don't fulfill on the checkout redirect or on `payment.processing`. Grant access only from the `payment.succeeded` webhook, and tell customers at checkout that their order is pending. See [Handling the Confirmation Delay](#handling-the-confirmation-delay). ## Troubleshooting > [accordion] European method not appearing > > **Check:** > > 1. Does the customer's billing country match the method's country? > 2. Is the billing currency EUR, or PLN for BLIK? > 3. Is the method included in `allowed_payment_method_types`? > 4. Is the checkout for a one-time payment? iDEAL, Bancontact, EPS, Multibanco, BLIK, and SEPA Direct Debit aren't offered for subscriptions. > > **Solution:** Country-specific methods appear only for their own country. A customer with billing country `DE` (Germany) doesn't see iDEAL, which is Netherlands-only. > [accordion] Bank authentication failed > > **Causes:** > > * The customer cancelled during bank authentication. > * The bank's authentication system was temporarily unavailable. > * The customer entered incorrect credentials. > > **Solution:** The customer should retry. If the failure persists, suggest a different payment method. > [accordion] Redirect not completing > > **Causes:** > > * The customer closed the browser during the bank redirect. > * A network issue interrupted authentication. > * The return URL is misconfigured. > > **Solution:** Check that your return URL is correct and reachable, and that it handles both success and failure states. > [accordion] Multibanco payment pending > > **Cause:** The customer received a payment reference but hasn't paid yet. > > **Solution:** This is expected for ATM payments. Wait for the webhook confirmation. The reference expires after the limited time shown to the customer. > [accordion] SEPA payment stuck in processing > > **Cause:** SEPA Direct Debit clears asynchronously through the customer's bank. > > **Solution:** This is expected. A `payment.processing` state can last up to **6 business days** before the debit clears. Wait for the final `payment.succeeded` webhook (fulfill) or `payment.failed` webhook (don't fulfill). Don't treat the checkout redirect as confirmation. See [Handling the Confirmation Delay](#handling-the-confirmation-delay). ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > See all supported payment methods. > [card] [Adaptive Currency](/features/adaptive-currency) > > Currency support and automatic conversion. > [card] [Checkout Guide](/developer-resources/checkout-session) > > Complete checkout implementation guide. > [card] [Webhooks](/developer-resources/webhooks) > > Handle payment confirmations asynchronously. # India Payment Methods Source: https://docs.dodopayments.com/features/payment-methods/india Accept UPI, Indian-issued cards, and Apple Pay in INR from customers in India. Understand RBI subscription mandates, the 48-hour delay, and mandate limits. Accept UPI, Indian-issued cards (Visa, Mastercard, and RuPay), and Apple Pay from customers in India. UPI carries more than 80% of India's digital payment transactions by volume. Dodo Payments supports subscriptions on UPI and Indian-issued cards through RBI-compliant mandates. ## Why India Payment Methods Matter > [card] UPI Dominance > > UPI processes more than 20 billion transactions a month, and many Indian customers don't have an international card. > [card] Low-Value Payments > > UPI suits high-volume, lower-value transactions. > [card] Subscription Support > > Unlike most alternative payment methods, UPI and Indian-issued cards, including Visa, Mastercard, and RuPay, support recurring payments through RBI mandates. ## Supported Methods The table lists each method and whether it supports subscriptions: | Method | Type | Subscriptions | | :- | :- | :-: | | **UPI** | QR code | Yes\* | | **RuPay Credit** | Card | Yes\* | | **RuPay Debit** | Card | Yes\* | | **Apple Pay** | Digital wallet | Yes\* | \*Subscriptions require RBI-compliant mandates with special processing rules. The 48-hour processing delay applies to recurring charges on all Indian-issued cards, UPI, and Apple Pay. A payment billed in INR must be at least ₹5.00 and at least the equivalent of the USD minimum: \$0.50 for one-time payments and \$1.00 for subscriptions. See [Minimum Amounts](/features/adaptive-currency#minimum-amounts). ## Configuration ### API Method Types Pass these values in `allowed_payment_method_types`: | Type | Description | | :- | :- | | `upi_intent` | UPI via QR code | | `credit` | Credit cards, including RuPay | | `debit` | Debit cards, including RuPay | | `apple_pay` | Apple Pay, on Apple devices. See [Apple Pay in India](/features/payment-methods/digital-wallets#apple-pay-in-india) | > [!WARNING] > > Checkout offers UPI only as `upi_intent`. If `allowed_payment_method_types` lists `upi_collect` but not `upi_intent`, UPI doesn't appear at checkout. ### Example: India-Focused Checkout This session offers UPI, cards, and Apple Pay to a customer in India, billed in INR: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: [ 'upi_intent', 'credit', 'debit', 'apple_pay' ], billing_currency: 'INR', customer: { email: 'customer@example.com', name: 'Priya Sharma', phone_number: '+919876543210' }, billing_address: { country: 'IN', zipcode: '560001' }, return_url: 'https://example.com/success' }); ``` ### Requirements for UPI UPI appears at checkout only when all of these are true: 1. The **billing country** is India (`IN`). 2. The **billing currency** is INR. 3. For subscriptions from merchants outside India, **Adaptive Currency** is enabled. One-time checkouts don't need it if the product is priced in INR. > [!WARNING] > > If you're a merchant outside India and Adaptive Currency is disabled, your customers can't pay for subscriptions with UPI. ## Subscriptions with RBI Mandates Subscriptions paid with UPI or Indian-issued cards run on RBI (Reserve Bank of India) mandates, which add rules that other payment methods don't have. ### How RBI Mandates Work The customer authorizes a mandate when they subscribe. Each renewal charge then waits 48 hours after a pre-debit notification before the bank debits the funds: ```mermaid theme={null} sequenceDiagram participant Customer participant Your App participant Dodo participant Bank Customer->>Your App: Subscribe Your App->>Dodo: Create subscription Dodo->>Bank: Create mandate Bank->>Customer: Authorize mandate Customer->>Bank: Approve (billing amount or mandate floor) Bank->>Dodo: Mandate active Note over Dodo,Bank: On renewal date... Dodo->>Bank: Initiate charge Note over Bank: 48-hour window starts Bank->>Customer: Pre-debit notification Note over Bank: After 48 hours... Bank->>Dodo: Debit completed Dodo->>Your App: payment.succeeded webhook ``` ### Mandate Types The mandate type depends on how the subscription amount compares with the mandate floor: | Subscription Amount | Mandate Type | Limit | | :- | :- | :- | | **Below the mandate floor** | On-demand mandate | Mandate floor (default ₹15,000) | | **At or above the mandate floor** | Fixed-amount mandate | Exact subscription amount | The amount registered with the customer's bank is `max(mandate_floor, billing_amount)`. When the billing amount is below the floor, the floor becomes the customer-facing **authorization ceiling**. **Plan changes:** If an upgrade produces a charge above the existing mandate limit, the charge fails and the customer must authorize again. ### Configurable Mandate Floor Set the mandate floor for INR e-mandates with the `mandate_min_amount_inr_paise` field, in **INR paise** (₹1 = 100 paise). > [!WARNING] > > This setting only affects e-mandates registered for Indian-issued cards (Visa, Mastercard, RuPay) on INR subscriptions. UPI subscriptions follow their own AutoPay flow and aren't affected. You can override the system default of ₹15,000 at three levels: | Level | Where to set | Scope | | - | - | - | | **Per request** | `mandate_min_amount_inr_paise` on a checkout session | One transaction | | **Merchant** | Business-level default, if one is configured | All your INR subscriptions | | **System** | — | ₹15,000 default | Dodo Payments uses the first value that's set: the per-request override, then the merchant setting, then the system default. To set the floor, pass `mandate_min_amount_inr_paise` in the request body when you [create a checkout session](/api-reference/checkout-sessions/create). ```typescript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_inr_monthly', quantity: 1 }], customer: { email: 'customer@example.com' }, billing_address: { country: 'IN', zipcode: '560001' }, mandate_min_amount_inr_paise: 2_000_000, // ₹20,000 ceiling return_url: 'https://yoursite.com/return' }); ``` The field accepts these values: | Field | Type | Validation | Applies to | | - | - | - | - | | `mandate_min_amount_inr_paise` | `integer` (INR paise) | `>= 1` | Indian-card INR subscriptions on non-Airwallex connectors | > [!NOTE] > > A higher floor lets you make larger one-off charges later, such as plan upgrades or usage-based overages, without asking customers to authorize again. A lower floor keeps the customer's authorization closer to the actual billing amount, but leaves less room for future variable charges. ### The 48-Hour Processing Delay A renewal charge on an Indian card or UPI completes about 48 hours after the renewal date. This is the most important difference from international card payments: **1. Charge Initiated (Day 0)** On the scheduled renewal date, Dodo Payments initiates the charge with the bank. **2. Pre-Debit Notification** The customer's bank notifies them about the upcoming debit. **3. 48-Hour Window** During this period, the customer can cancel the mandate in their banking app. **4. Debit Completed (\~48-51 Hours)** After 48 hours, plus up to 3 more hours for bank processing, the bank debits the funds. **5. Webhook Sent** Dodo Payments sends the `payment.succeeded` webhook after the actual debit, not when the charge is initiated. > [!WARNING] > > **Don't grant benefits when the charge is initiated.** Wait for the `payment.succeeded` webhook, which arrives about 48–51 hours after the scheduled charge date. ### Handling the 48-Hour Window Grant access from the payment webhook, not from the renewal date: ```javascript theme={null} // grantPremiumAccess and revokePremiumAccess are your own access-control functions. // DON'T do this: async function handleSubscriptionRenewal(subscription) { // Bad: Granting access immediately when charge is initiated grantPremiumAccess(subscription.customer.customer_id); } // DO this: async function handlePaymentWebhook(event) { if (event.type === 'payment.succeeded') { // Good: Only grant access after payment is confirmed grantPremiumAccess(event.data.customer.customer_id); } if (event.type === 'payment.failed') { // Handle failed payment (mandate cancelled, insufficient funds) revokePremiumAccess(event.data.customer.customer_id); } } ``` ### Webhook Events for Indian Subscriptions Handle these events for subscriptions paid with UPI or Indian-issued cards: | Event | When | Action | | :- | :- | :- | | `subscription.active` | Mandate authorized | Record subscription start | | `payment.succeeded` | \~48h after charge date | Grant/continue access | | `payment.failed` | Debit failed | Notify customer, pause access | | `subscription.on_hold` | Payment failed | Prompt for payment method update | | `subscription.active` | Reactivated after payment | Restore access | ## Testing ### UPI Test IDs In test mode, enter these UPI IDs to simulate each outcome: | Status | UPI ID | | :- | :- | | Success | `success@upi` | | Failure | `failure@upi` | ### Indian Card Test Numbers Use these Indian-issued test cards: | Brand | Scenario | Card Number | Expiry | CVV | | :- | :- | :- | :- | :- | | Visa | Success | `4576238912771450` | 06/32 | 123 | | Visa | Declined | `4706131211212123` | 06/32 | 123 | | Mastercard | Success | `5409162669381034` | 06/32 | 123 | | Mastercard | Declined | `5105105105105100` | 06/32 | 123 | ## Best Practices > [accordion] Plan for the 48-hour delay > > Build your application to handle the gap between charge initiation and the actual payment. Consider: > > * Grace periods for subscription access > * Clear communication to customers about processing time > * Webhook-driven fulfillment, not date-driven fulfillment > [accordion] Handle mandate cancellations > > Customers can cancel mandates in their banking apps at any time. Monitor `subscription.on_hold` webhooks, and prompt customers to subscribe again or update their payment method. > [accordion] Set appropriate mandate amounts > > For variable pricing, such as usage-based billing, check whether an on-demand mandate at the mandate floor (₹15,000 by default) covers your largest charge. If charges might exceed it, raise the floor with [`mandate_min_amount_inr_paise`](#configurable-mandate-floor). Otherwise, customers must authorize a new mandate. > [accordion] Offer UPI prominently > > For Indian customers, make UPI the primary payment option. Many prefer it to cards because it's familiar and has less friction. ## Troubleshooting > [accordion] UPI not appearing at checkout > > **Check:** > > 1. Is the billing country set to `IN`? > 2. Is the billing currency set to `INR`? > 3. If you're a merchant outside India, is Adaptive Currency enabled? > 4. Is `upi_intent` included in `allowed_payment_method_types`? > > **Solution:** Set `country: "IN"` in the billing address and `billing_currency: "INR"`. If Adaptive Currency is disabled, the API ignores `billing_currency`, so price the product in INR instead. > [accordion] Subscription charge failed after upgrade > > **Cause:** The new charge amount exceeds the existing mandate limit: the mandate floor (₹15,000 by default), or the subscription amount if that's higher. > > **Solution:** The customer must update their payment method to set up a new mandate with the correct limit. > [accordion] Subscription on hold but customer claims they didn't cancel > > **Cause:** The customer may have cancelled the mandate during the 48-hour window, or their bank declined the debit. > > **Solution:** The customer needs to authorize the mandate again or update their payment method. > [accordion] Payment deduction delayed beyond 48 hours > > **Cause:** Bank API delays can extend processing by 2–3 hours. > > **Solution:** This is expected. Build your system to handle delays of up to about 51 hours in total. > [accordion] Mandate cancelled but subscription still active > > **Cause:** An edge case in RBI regulations: cancelling a mandate during the processing window doesn't cancel the subscription right away. > > **Solution:** The next charge fails, and the subscription moves to `on_hold`. Monitor webhooks for `payment.failed`. ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > See all supported payment methods. > [card] [Subscriptions](/features/subscription) > > Complete subscription documentation including RBI mandates. > [card] [Webhooks](/developer-resources/webhooks) > > Webhook handling for payment events. > [card] [Testing Process](/miscellaneous/testing-process) > > All test data including UPI IDs and Indian cards. # Pix Source: https://docs.dodopayments.com/features/payment-methods/pix Accept Pix from Brazilian customers on one-time payments and subscriptions billed in BRL. Learn about the QR code flow, Pix Automático mandates, renewal timing, IOF, testing, and configuration. Let Brazilian customers pay from their banking app by scanning a QR code or pasting a Pix code. Pix is Brazil's instant payment system, created by the Central Bank of Brazil (Banco Central do Brasil). It moves money in real time, 24 hours a day, including weekends and holidays. Dodo Payments offers Pix on one-time payments and subscriptions billed in BRL. Subscriptions run on Pix Automático: the customer authorizes a recurring mandate in their banking app, and each renewal is debited after a 3-day notice. ## Why Offer Pix? > [card] Dominant in Brazil > > Pix is the most-used payment method in Brazil, ahead of credit cards and boleto. The Central Bank of Brazil reports that Pix carried 54.7% of all payment transactions in the second half of 2025. > [card] Instant Settlement > > Pix transfers complete in seconds, at any hour and on any day of the year, so there is no bank processing window to wait for. > [card] Low Friction > > The customer scans a QR code or pastes a Pix code in their banking app. They don't enter card numbers or bank details. ## Overview The minimum is the checkout minimum for BRL, so it applies to every payment method on a BRL checkout. A BRL payment must also be at least the equivalent of \$0.50 for one-time payments and \$1.00 for subscriptions. See [Minimum Amounts](/features/adaptive-currency#minimum-amounts). | Detail | Value | | :- | :- | | **Billing Currency** | BRL | | **Supported Countries** | Brazil | | **Subscriptions** | Yes, through Pix Automático | | **Min Amount** | 0.50 BRL | | **Max Amount** | BRL equivalent of US\$3,000 per payment | | **IOF** | 3.5%, paid by the customer on top of the amount | | **One-Time Confirmation** | Seconds | | **Renewal Confirmation** | 3 days after the billing date, up to 7 days with retries | ## How It Works ```mermaid theme={null} sequenceDiagram participant Customer participant Checkout participant Dodo participant Pix participant Bank Customer->>Checkout: Select Pix and enter CPF Checkout->>Dodo: Create payment Dodo->>Pix: Generate QR code Pix->>Customer: Display QR code / Pix code Customer->>Bank: Scan QR or paste code in banking app Bank->>Pix: Payment confirmed Pix->>Dodo: Success callback Dodo->>Checkout: Payment complete ``` ## Customer Experience 1. The customer selects **Pix** at checkout and enters their CPF (the 11-digit Brazilian taxpayer ID) or CNPJ (the 14-digit company ID) in the **CPF or CNPJ** field. 2. Checkout shows the IOF fee and the total the customer's bank will debit. See [Brazilian IOF Tax](#brazilian-iof-tax). 3. The customer confirms the payment. A QR code opens in a full-screen overlay, with the Pix code and a **Copy the code** button below it. 4. The customer opens their banking app, selects Pix, and scans the QR code or pastes the Pix code. 5. The payment confirms within seconds. 6. Checkout detects the completed payment and redirects the customer to your success page. > [!NOTE] > > The Pix QR code expires after a limited time. If the customer doesn't pay in time, they need to start a new checkout from your site. ## Subscriptions with Pix Automático A Pix subscription starts with a one-time Pix payment that also enrolls the customer in a recurring mandate. Renewals are then debited from the customer's bank account without a QR code. ### How Pix Automático Works The customer authorizes the mandate in their banking app when they pay for the first time. Each renewal then waits 3 days after a pre-debit notification before the bank debits the funds: ```mermaid theme={null} sequenceDiagram participant Customer participant Your App participant Dodo participant Bank Customer->>Your App: Subscribe Your App->>Dodo: Create checkout session Dodo->>Customer: QR code / Pix code Customer->>Bank: Scan QR and approve the recurring mandate Bank->>Dodo: First payment succeeded, mandate active Dodo->>Your App: payment.succeeded webhook Note over Dodo,Bank: On the billing date... Dodo->>Bank: Initiate charge Dodo->>Your App: payment.processing webhook Bank->>Customer: Pre-debit notification Note over Bank: After 3 days... Bank->>Dodo: Debit completed Dodo->>Your App: payment.succeeded webhook ``` In their banking app, the customer sees the mandate under the name **Dodo Payments Inc**, because Dodo Payments is the Merchant of Record. ### Mandate Terms Dodo Payments sets the mandate terms. There is no API or dashboard setting for a Pix mandate, and the `mandate_min_amount_inr_paise` field applies only to Indian-issued cards. | Term | Value | | :- | :- | | **Charge frequency** | One charge per month | | **Amount** | A maximum amount per charge, authorized by the customer | | **Expiry** | None. The mandate stays active until the customer revokes it. | The mandate allows one debit per month, so the subscription's billing interval must be a month or longer. A renewal that falls in the same month as a previous Pix charge fails with the error `You can only schedule one Pix payment per billing cycle`. > [!WARNING] > > Don't offer Pix on daily or weekly subscription plans. The first payment succeeds, but renewals fail. Remove `pix` from `allowed_payment_method_types` on those checkouts. ### The 3-Day Renewal Delay A Pix renewal completes about 3 days after the billing date. This is the main difference from a one-time Pix payment, which confirms in seconds: **1. Charge Initiated (Day 0)** On the billing date, Dodo Payments initiates the charge against the mandate. The payment enters the `processing` state and Dodo Payments sends the `payment.processing` webhook. **2. Pre-Debit Notification** The customer's bank notifies them of the upcoming debit, with the exact amount and an option to cancel it. The bank sends this notification; you don't need to do anything. **3. Debit (Day 3)** The bank debits the customer's account. If the debit fails for a temporary reason, such as insufficient funds, the bank retries once a day for the next 3 days. The payment stays in `processing` during the retries. **4. Final Status (Day 3 to Day 7)** The payment moves to `succeeded` or `failed`, and Dodo Payments sends the matching webhook. A failed renewal follows the usual [Payment Retries](/features/recovery/payment-retries) and [Dunning](/features/recovery/subscription-dunning) flow. Use the `payment.succeeded` and `payment.failed` webhooks for the final status of a renewal. Don't treat a renewal in `processing` as failed: it can stay there for up to 7 days. While the renewal is in `processing`, the subscription stays `active`. Dodo Payments waits a maximum of 8 days after it creates the payment. For what occurs after the wait, see [On Hold State](/features/subscription#on-hold-state). ### Trials On a subscription with a trial, the customer authorizes the mandate in their banking app without paying. The first charge after the trial follows the same 3-day renewal flow, so it completes about 3 days after the trial ends. ### Customer Cancellation The customer can stop a Pix subscription from their banking app in two ways: * **Cancel a single debit.** During the 3-day notification window, the customer can decline the upcoming debit. That renewal fails with the error `The Pix payment attempt of this PaymentIntent has been canceled by the customer`, and the mandate stays active for later renewals. * **Revoke the mandate.** The customer can cancel the mandate itself. Every later renewal then fails with the error `Only active mandates can be used with PaymentIntents`, and the subscription follows the failed-renewal flow. In both cases, to keep the subscription, the customer must [update their payment method](/features/subscription#update-payment-method-for-active-subscription) through a new checkout, which creates a new mandate. ## Brazilian IOF Tax IOF (Imposto sobre Operações Financeiras) is a Brazilian tax of 3.5% on international transactions. The customer pays it on top of every Pix payment, including each subscription renewal. For a 100 BRL payment, the customer's bank debits 103.50 BRL, and the payment amount stays 100 BRL. Checkout shows the IOF fee and the total due before the customer confirms. There is no option to absorb the IOF on the customer's behalf. ## Amount Limits A single Pix payment can be at most the BRL equivalent of US\$3,000. A payment above this limit fails with the error `Amount must be no more than $3,000.00 usd`. ## Configuration ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['pix', 'credit', 'debit'], billing_currency: 'BRL', return_url: 'https://example.com/success' }); ``` Pix appears on one-time and subscription checkouts billed in BRL. Dodo Payments bills in BRL only when [Adaptive Currency](/features/adaptive-currency) is enabled, so enable it before you offer Pix. A subscription checkout needs no extra parameter: the mandate is created as part of the first payment. ## API Method Type | Type | Method | Country | | :- | :- | :- | | `pix` | Pix | Brazil | ## Testing **1. Enable Test Mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. **2. Set Billing Currency to BRL** Enable Adaptive Currency. Then create a checkout session with `billing_currency: 'BRL'` and `pix` in `allowed_payment_method_types`. **3. Enter Test CPF and Scan the QR Code** In the **CPF or CNPJ** field, enter `00000000000` (11 zeros). Checkout shows a test QR code. Scan it with your phone's camera; a Pix or banking app isn't needed. The QR code opens a test page where you can simulate a successful or failed payment. ## Best Practices > [accordion] Set billing currency to BRL > > Pix works only on checkouts billed in BRL, and Dodo Payments bills in BRL only when Adaptive Currency is enabled. Enable Adaptive Currency so customers in Brazil are quoted and billed in BRL. > [accordion] Provide card fallbacks > > Some Brazilian customers prefer to pay by card. Include `credit` and `debit` as fallback payment methods. > [accordion] Offer Pix on monthly or longer subscription plans > > A Pix mandate allows one debit per month. Leave `pix` out of `allowed_payment_method_types` on daily and weekly plans, where renewals fail. > [accordion] Wait for the webhook on renewals > > A Pix renewal stays in `processing` for about 3 days, and up to 7 with retries. Keep the customer's access during this window and act on `payment.succeeded` or `payment.failed`. > [accordion] Handle QR code expiration > > Pix QR codes expire after a limited time. If a customer comes back after the code expires, create a new checkout session for them. ## Troubleshooting > [accordion] Pix not appearing at checkout > > **Check:** > > 1. Is the billing currency `BRL`? > 2. Is `pix` included in `allowed_payment_method_types`? > 3. Is the customer's billing country Brazil (`BR`)? With Adaptive Currency, a Brazilian billing address sets the billing currency to BRL. > 4. Is Adaptive Currency enabled? > 5. Does the amount meet the 0.50 BRL minimum and the USD minimum? > > **Solution:** Pix is offered only on BRL checkouts. Check the currency and billing address in your API request. > [accordion] QR code expired > > **Cause:** The customer didn't complete the payment within the expiration window. > > **Solution:** The customer needs to start a new checkout from your site. To send them a new payment link, create a new checkout session. > [accordion] One-time payment pending > > **Cause:** Most Pix payments confirm within seconds, but a bank can occasionally delay a transfer. > > **Solution:** Use the `payment.succeeded` and `payment.failed` webhooks for the final payment status instead of the return redirect. If a one-time payment doesn't confirm within a few minutes, treat it as failed. > [accordion] Renewal stuck in processing > > **Cause:** This is expected. A Pix renewal waits 3 days after the pre-debit notification, and bank retries can extend this to 7 days. > > **Solution:** Wait for `payment.succeeded` or `payment.failed`. A renewal in `processing` is neither paid nor failed. > [accordion] Renewal failed with an inactive mandate > > **Cause:** The customer revoked the Pix mandate in their banking app. The renewal fails with the error `Only active mandates can be used with PaymentIntents`. > > **Solution:** The subscription follows the failed-renewal flow. To continue, the customer must update their payment method through a new checkout, which creates a new mandate. > [accordion] Renewal failed with one Pix payment per billing cycle > > **Cause:** The subscription bills more than once a month, but the Pix mandate allows one debit per month. > > **Solution:** Remove `pix` from `allowed_payment_method_types` on daily and weekly plans. Existing customers on those plans need to switch to a card. > [accordion] Payment above the Pix limit > > **Cause:** The amount is above the BRL equivalent of US\$3,000. The payment fails with the error `Amount must be no more than $3,000.00 usd`. > > **Solution:** Offer `credit` and `debit` as fallbacks for high-value checkouts. ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > See all supported payment methods. > [card] [Adaptive Currency](/features/adaptive-currency) > > Bill customers in their local currency, including BRL. > [card] [Subscriptions](/features/subscription) > > Subscription states, trials, plan changes, and the on-hold flow. > [card] [Payment Retries](/features/recovery/payment-retries) > > How failed renewals are retried before dunning starts. > [card] [Checkout Guide](/developer-resources/checkout-session) > > Complete checkout implementation guide. > [card] [Webhooks](/developer-resources/webhooks) > > Handle payment confirmations asynchronously. > [card] [Testing Process](/miscellaneous/testing-process) > > Test data and checkout testing guidance. # South Korea Payment Methods Source: https://docs.dodopayments.com/features/payment-methods/south-korea Accept Kakao Pay, Naver Pay, and PAYCO from South Korean customers alongside cards, billed in KRW. Learn about availability, subscriptions, and configuration. Let South Korean customers pay with the wallets and cards they use every day. Dodo Payments supports the Korean wallets **Kakao Pay**, **Naver Pay**, and **PAYCO**, alongside **Korean local cards** and international cards, all billed in **KRW** (South Korean won). At checkout, each wallet redirects the customer to the wallet provider to approve the payment. ## Why Korean Payment Methods Matter > [card] Widely Used Wallets > > Digital wallets such as Kakao Pay and Naver Pay made up 35% of South Korean e-commerce spending in 2025, second only to credit cards, according to the Worldpay Global Payments Report 2026. > [card] Domestic Card Networks > > Many Korean cards run on domestic networks. Supporting Korean local cards avoids declines on cards that international card networks can't process. > [card] Higher Conversion > > Familiar local methods reduce checkout friction and abandonment for customers in South Korea. ## Supported Methods The table lists each method's type, subscription support, and minimum amount. | Method | Type | Subscriptions | Min Amount | | :- | :- | :-: | :- | | **Kakao Pay** | Wallet | Yes | \~\$1.00 | | **Naver Pay** | Wallet | Yes | \~\$1.00 | | **PAYCO** | Wallet | No | \~\$1.00 | | **Korean Local Cards** | Card | Yes | 50 KRW | | **Credit & Debit Cards** | Card (international) | Yes | 50 KRW | The wallet minimum is approximate because the wallets appear only when the KRW total is worth at least \$1.00 at the current exchange rate. Cards follow the KRW checkout minimum of 50 KRW. A KRW payment must also be at least the equivalent of \$0.50 for one-time payments and \$1.00 for subscriptions. See [Minimum Amounts](/features/adaptive-currency#minimum-amounts). > [!NOTE] > > Wallet availability depends on the transaction type. **Kakao Pay** and **Naver Pay** are offered on both one-time payments and subscriptions. **PAYCO** is offered on one-time payments only. All three require a **KRW** billing currency. ## Configuration ### API Method Types Pass these values in `allowed_payment_method_types`: | Type | Description | | :- | :- | | `kakao_pay` | Kakao Pay wallet | | `naver_pay` | Naver Pay wallet | | `payco` | PAYCO wallet | | `credit` | Credit cards, including Korean local cards | | `debit` | Debit cards, including Korean local cards | ### Example: South Korea-Focused Checkout This session offers the three Korean wallets and cards to a customer billed in KRW: ```javascript theme={null} // `client` is an initialized DodoPayments client. const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: [ 'kakao_pay', 'naver_pay', 'payco', 'credit', 'debit' ], billing_currency: 'KRW', billing_address: { country: 'KR', zipcode: '06236' }, return_url: 'https://example.com/success' }); ``` ### Requirements The Korean wallets appear at checkout only when all of these are true: 1. The **billing currency** is KRW. 2. The KRW total is worth at least \$1.00. 3. **Adaptive Currency** is enabled. Dodo Payments bills in KRW only when Adaptive Currency is enabled. > [!WARNING] > > If Adaptive Currency is disabled, customers in South Korea aren't billed in KRW, and the Korean wallets don't appear. KRW is a zero-decimal currency: the smallest unit is one won, with no minor units. Send and read KRW amounts as whole won, without multiplying or dividing by 100. For example, an amount of `15000` is ₩15,000. ## Best Practices > [accordion] Offer wallets prominently > > Show the Korean wallets next to cards on checkouts for South Korea. Kakao Pay and Naver Pay are among the most widely used payment wallets in South Korea. > [accordion] Include card fallbacks > > Include `credit` and `debit` so customers without a wallet, and customers who pay with Korean local cards, can complete checkout. > [accordion] Match currency to region > > Korean payment methods require KRW, and Dodo Payments bills in KRW only when Adaptive Currency is enabled. Enable Adaptive Currency so Korean customers are quoted and billed in KRW. > [accordion] Choose wallets by transaction type > > Kakao Pay and Naver Pay work on one-time and subscription checkouts. PAYCO works on one-time checkouts only. Include all three, and checkout shows the wallets that fit each checkout. ## Troubleshooting > [accordion] Korean wallets not appearing at checkout > > **Check:** > > 1. Is the billing currency `KRW`? > 2. Is Adaptive Currency enabled? > 3. Is the wallet (`kakao_pay`, `naver_pay`, or `payco`) included in `allowed_payment_method_types`? > 4. Is the KRW total worth at least \$1.00? > > **Solution:** Verify that `billing_currency` is `"KRW"`. To see every eligible method, remove `allowed_payment_method_types` temporarily. > [accordion] Wallet missing for a subscription > > **Cause:** PAYCO is offered for one-time payments only. For recurring billing, use Kakao Pay or Naver Pay. > > **Solution:** Include `kakao_pay` and `naver_pay` in `allowed_payment_method_types` for subscription checkouts. > [accordion] Korean card declined on the international network > > **Cause:** Some Korean cards run on domestic networks that international card networks can't process. > > **Solution:** Keep `credit` and `debit` enabled so customers can pay with Korean local cards. ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > See all supported payment methods. > [card] [Credit & Debit Cards](/features/payment-methods/cards) > > Card networks, including Korean local cards. > [card] [Adaptive Currency](/features/adaptive-currency) > > Bill customers in their local currency, including KRW. > [card] [Asia-Pacific](/features/payment-methods/asia-pacific) > > GCash (Philippines), Alipay HK and FPS (Hong Kong), and Touch 'n Go (Malaysia). > [card] [Testing Process](/miscellaneous/testing-process) > > Test data and checkout testing guidance. # Stablecoins Source: https://docs.dodopayments.com/features/payment-methods/stablecoins Accept stablecoin payments from customers worldwide, except India, on USD checkouts. Learn about supported stablecoins, networks, limits, and configuration. Let customers anywhere except India pay with a stablecoin from their crypto wallet. Stablecoin payments are billed in USD, so you receive fiat currency while the customer pays with the stablecoin and network they choose. ## Why Offer Stablecoins? > [card] Global Reach > > Accept payments from customers in any supported country, including customers who don't have a card. > [card] No Chargebacks > > Stablecoin payments have no dispute process, so they can't turn into chargebacks. > [card] USD Settlement > > You receive USD, so you don't hold crypto or manage price volatility. ## Overview | Detail | Value | | :- | :- | | **Billing Currency** | USD | | **Supported Countries** | Global (except India) | | **Subscriptions** | No | | **Min Amount** | \$0.50 | | **Max Amount** | \$10,000 | | **Settlement** | USD | ## How It Works ```mermaid theme={null} sequenceDiagram participant Customer participant Checkout participant Dodo participant StablecoinProcessor participant Blockchain Customer->>Checkout: Select Stablecoins Checkout->>Dodo: Create payment Dodo->>StablecoinProcessor: Generate payment request Checkout->>StablecoinProcessor: Redirect customer to payment page Customer->>StablecoinProcessor: Connect wallet, pick token and network Customer->>Blockchain: Send stablecoins from wallet Blockchain->>StablecoinProcessor: Transaction confirmed StablecoinProcessor->>Dodo: Payment confirmed (USD) ``` ## Customer Experience 1. The customer selects **Stablecoins** at checkout and submits the order. 2. Checkout redirects the customer to the stablecoin provider's payment page. 3. The customer connects a crypto wallet and chooses a stablecoin and network. 4. The customer approves the transfer, and the blockchain confirms the transaction. 5. The customer is redirected to your success page. > [!NOTE] > > Stablecoin payments are billed in USD. The stablecoin amount on the payment page is calculated from the USD price at the time of payment. ## Supported Currencies & Networks The customer can pay with these stablecoins: | Currency | Networks | | :- | :- | | **USDC** | Ethereum, Solana, Polygon, Base, Tempo | | **USDP** | Ethereum, Solana | | **USDG** | Ethereum | All three stablecoins are available to customers everywhere except India. ## Configuration ```javascript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['crypto_currency', 'credit', 'debit'], return_url: 'https://example.com/success' }); ``` Stablecoins appear only when the billing currency is USD, the billing country is not India, the checkout is a one-time payment, and the amount is from \$0.50 to \$10,000. If Adaptive Currency bills the customer in a local currency, stablecoins don't appear. ## API Method Type | Type | Method | Country | | :- | :- | :- | | `crypto_currency` | Stablecoins | Global (except India) | ## Testing **1. Enable test mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. **2. Create a test checkout** Create a one-time USD checkout session with `crypto_currency` in `allowed_payment_method_types`. **3. Complete the test flow** Select **Stablecoins**, and complete the test payment on the provider's payment page with test tokens, such as USDC on the Polygon Amoy test network. Your test wallet also needs the network's own test token, such as POL, to pay the transaction cost. ## Best Practices > [accordion] Always include card fallbacks > > Not every customer has a stablecoin wallet. Include `credit` and `debit` as fallback payment methods. > [accordion] Set clear expectations on confirmation time > > Blockchain confirmation can take minutes, depending on the network. Tell customers that the payment may not confirm immediately. > [accordion] Use webhooks for payment status > > The hosted payment page shows the customer the exact amount to send. Use webhooks for payment status updates instead of the redirect to your success page. ## Troubleshooting > [accordion] Stablecoins not appearing at checkout > > **Check:** > > 1. Is `crypto_currency` included in `allowed_payment_method_types`? > 2. Is the amount from \$0.50 to \$10,000? > 3. Is the billing currency USD, and the billing country not India? > 4. Is this a one-time payment? Stablecoins are not offered on subscriptions. > > **Solution:** Check the payment method type, billing currency, and billing country in your API request. > [accordion] Payment not confirming > > **Cause:** Blockchain confirmation times vary. Some networks take longer than others. > > **Solution:** Wait for the webhook. Don't treat the payment as failed until you receive `payment.failed`. ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > See all supported payment methods. > [card] [Checkout Guide](/developer-resources/checkout-session) > > Complete checkout implementation guide. > [card] [Webhooks](/developer-resources/webhooks) > > Handle payment confirmations asynchronously. > [card] [Testing Process](/miscellaneous/testing-process) > > Complete testing guide for all payment methods. # WeChat Pay Source: https://docs.dodopayments.com/features/payment-methods/wechat Accept WeChat Pay from Chinese customers on one-time payments. Learn about USD and CNY billing, the QR code payment flow, testing, and configuration. Let Chinese customers pay by scanning a QR code with the WeChat app. WeChat Pay is the payment wallet inside WeChat, China's leading mobile app, and Dodo Payments offers it on one-time payments billed in USD or CNY. ## Why Offer WeChat Pay? > [card] 800M+ Users > > WeChat has over 1 billion monthly active users, and WeChat Pay has over 800 million users. > [card] Mobile-First > > The customer approves the payment inside the WeChat app, a flow that Chinese customers already know. > [card] Dual Currency > > Bill in USD or CNY, depending on the customers you sell to. ## Overview | Detail | Value | | :- | :- | | **Billing Currency** | USD, CNY | | **Subscriptions** | No | | **Min Amount** | \$0.50 / 4.00 CNY | | **Max Amount** | 1,000.00 CNY, or the USD equivalent | | **Settlement** | USD | ## How It Works ```mermaid theme={null} sequenceDiagram participant Customer participant Checkout participant Dodo participant WeChat Customer->>Checkout: Select WeChat Pay Checkout->>Dodo: Create payment Dodo->>WeChat: Initiate payment WeChat->>Customer: Display QR code Customer->>WeChat: Scan QR in WeChat app WeChat->>Dodo: Payment confirmed Dodo->>Checkout: Payment complete ``` ## Customer Experience 1. The customer selects **WeChat** at checkout and clicks **Pay**. 2. A QR code opens in a full-screen overlay on the checkout page. 3. The customer opens WeChat on their phone and scans the QR code. If the customer is already paying on their phone, checkout shows steps to take a screenshot of the QR code and scan it from the WeChat photo album. 4. The customer confirms the payment in the WeChat app. 5. Checkout detects the completed payment and redirects the customer to your success page. > [!NOTE] > > Customers pay in USD or CNY, and you receive settlement in USD. ## Configuration ```javascript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], allowed_payment_method_types: ['we_chat_pay', 'credit', 'debit'], return_url: 'https://example.com/success' }); ``` WeChat Pay appears on one-time checkouts billed in USD or CNY. To bill in CNY, enable [Adaptive Currency](/features/adaptive-currency) and pass `billing_currency: 'CNY'`. Checkout shows WeChat Pay only when the amount is 1,000.00 CNY or less. For a USD checkout, Dodo Payments converts the amount to CNY before this check. For example, if 1 USD is 7.20 CNY, checkout shows WeChat Pay for USD amounts up to \$138.88. The exchange rate changes. Thus, the USD limit also changes. ## API Method Type | Type | Method | Currencies | | :- | :- | :- | | `we_chat_pay` | WeChat Pay | USD, CNY | ## Testing **1. Enable test mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. **2. Create a test checkout** Create a one-time checkout session with `we_chat_pay` in `allowed_payment_method_types`. **3. Scan the QR code** Checkout shows a test QR code. Scan it with your phone's camera; the WeChat app isn't needed. The QR code opens a test page where you can authorize or fail the payment. ## Best Practices > [accordion] Target Chinese customers > > WeChat Pay is used mostly by Chinese consumers. Include it when your customers include Chinese buyers, or when you sell to the Chinese market. > [accordion] Always include card fallbacks > > Not every customer has WeChat. Include `credit` and `debit` as fallback payment methods. Checkout does not show WeChat Pay for amounts above 1,000.00 CNY. Thus, customers must use a different method for these orders. > [accordion] Optimize for mobile > > Scanning is easiest when checkout is open on a computer or tablet and the customer scans with their phone. On a phone, checkout guides the customer to screenshot the QR code and scan it from the WeChat photo album, so keep your checkout page responsive. > [accordion] Consider both currencies > > WeChat Pay supports USD and CNY. Choose the billing currency that suits your customers: USD if you price in USD, or CNY to show Chinese customers a price in their own currency. Settlement is in USD either way. ## Troubleshooting > [accordion] WeChat Pay not appearing at checkout > > **Check:** > > 1. Is `we_chat_pay` included in `allowed_payment_method_types`? > 2. Is the billing currency USD or CNY? > 3. Does the amount meet the minimum (\$0.50 or 4.00 CNY)? > 4. Is the amount 1,000.00 CNY or less? For a USD checkout, is the amount at most the USD equivalent of 1,000.00 CNY? > 5. Is this a one-time payment? WeChat Pay is not offered on subscriptions. > > **Solution:** Check the payment method type, currency, and amount in your API request. > [accordion] QR code not scanning > > **Cause:** The QR code may have expired, or the customer's WeChat version is outdated. The QR code expires after a limited time. > > **Solution:** If the QR code expired, the customer needs to start a new checkout from your site, or you can create a new checkout session for them. If the code is still valid, ask the customer to update WeChat to a current version. > [accordion] Payment not confirming > > **Cause:** WeChat Pay usually confirms within seconds, but network delays can occur. > > **Solution:** Use webhooks for the payment confirmation. If the payment doesn't confirm within a few minutes, the customer may need to try again. ## Related Pages > [card] [Payment Methods Overview](/features/payment-methods) > > See all supported payment methods. > [card] [Checkout Guide](/developer-resources/checkout-session) > > Complete checkout implementation guide. > [card] [Webhooks](/developer-resources/webhooks) > > Handle payment confirmations asynchronously. > [card] [Asia-Pacific](/features/payment-methods/asia-pacific) > > GCash (Philippines), Alipay HK and FPS (Hong Kong), and Touch 'n Go (Malaysia). > [card] [Testing Process](/miscellaneous/testing-process) > > Complete testing guide for all payment methods. # Payouts Process Source: https://docs.dodopayments.com/features/payouts/payout-structure Learn how Dodo Payments schedules payouts, applies your minimum payout threshold, deducts fees, and sends your earnings to your linked bank account. ## Introduction The **Payouts** page shows the earnings that go out in your next payout, net of fees, refunds, and taxes. It also holds your payout schedule, your minimum payout threshold, your linked bank accounts, and your payout history. ![Payouts page showing balance eligible for payout, schedule settings, linked bank accounts, and payout history](https://mintcdn.com/dodopayments/eH3qSTsrWihVdlv7/images/payouts/payout-page.png?fit=max\&auto=format\&n=eH3qSTsrWihVdlv7\&q=85\&s=c4011d2daa64e6e6730a37c806c159e0) ## Key Features * The **Payout Balance** card shows the balance eligible for your next payout in your settlement currency, the currency that Dodo Payments pays your payout in. For example, if your payouts settle in EUR, the card shows EUR. The balance is split into **Available** and **Incoming**. When part of your balance is held in a reserve, the card also shows a **Reserved** row. See [Reserved Balance](#reserved-balance). * Balances in other wallet currencies are converted to your settlement currency for display. * The **Minimum Payout** stays in USD. When your balance is in another currency, the note that your balance is below the minimum payout labels the minimum "(USD)". * The **Payout Schedule & Settings** card shows your **Minimum Payout**, **Payout Cycle** (the current billing period), **Payout Frequency**, and **Next Payout** date. Click **Manage** to change your payout frequency and minimum payout in **Settings → Payouts**. * **Next Payout** comes from your payout schedule, which skips weekends and bank holidays. It shows `-` when no payout is due, for example when your balance is below your minimum payout. The date is never in the past: a payout that missed its date and is still due shows today's date and runs on the next payout run. > [!NOTE] > > The displayed amount is **for reference only**. The final payout amount depends on the exchange rate at the time of transfer. Charges from your own bank or from intermediary banks can reduce the credited amount further. See [Payout Currency and Bank Conversion](#payout-currency-and-bank-conversion). ## Payout Cycles Each payout cycle has fixed billing periods and payout dates: **1. Bi-Monthly (Default)** **Billing Period 1:** 1st to 15th of the month\ **Payout Date 1:** 18th of the same month **Billing Period 2:** 16th to the end of the month\ **Payout Date 2:** 4th of the following month **2. Weekly** **Billing Period 1:** 1st to 7th\ **Payout Date 1:** 11th of the same month **Billing Period 2:** 8th to 14th\ **Payout Date 2:** 18th of the same month **Billing Period 3:** 15th to 21st\ **Payout Date 3:** 25th of the same month **Billing Period 4:** 22nd to the end of the month\ **Payout Date 4:** 4th of the following month **3. Monthly** **Billing Period:** 1st to the end of the month\ **Payout Date:** 11th of the following month **Note:** * A payout is initiated only when all verifications are approved and your payable balance meets your payout threshold for the billing period. * The default payout cycle for all businesses is **bi-monthly**. Your current cycle appears as **Payout Frequency** on the **Payouts** page. * Businesses with higher transaction volumes can request **weekly** payouts by contacting [support@dodopayments.com](mailto:support@dodopayments.com). * Certain high-risk businesses may be placed on a **monthly** payout cycle at our discretion. ### Change Your Payout Cycle You can move your payout cycle to a **less frequent** cycle from the dashboard. The order is weekly, bi-monthly, and then monthly. You can't move back to your current cycle or to any more frequent cycle afterwards. ![Payout Settings page with the Customise Payouts card, the Linked Bank Accounts card, and the Settlement Currencies card](https://mintcdn.com/dodopayments/BxNFH14Y2X6lXkp3/images/payouts/payout-settings.png?fit=max\&auto=format\&n=BxNFH14Y2X6lXkp3\&q=85\&s=61f30056ea3f798117ba944eabf057d2) **1. Open Payout Settings** Go to **Settings → Payouts**, or click **Manage** on the **Payout Schedule & Settings** card of the **Payouts** page. **2. Select a New Frequency** Under **Customise Payouts**, open the **Payout Frequency** list. It shows only the cycles you can move to. Select one and click **Save**. **3. Confirm the Change** In the **Change payout frequency?** dialog, click **Change**. > [!NOTE] > > Team members whose [role](/features/team#roles-and-permissions) has no **Write** access to any resource, such as Analyst or Finance, see payout settings as read-only. An API key cannot change the payout cycle. After the change, Dodo Payments sends a **Payout schedule changed** in-app notification. It shows the old cycle, the new cycle, and the date of your next payout. ## Why Payouts Show as Inactive If your dashboard shows **Payouts Inactive**, no payout is scheduled on your payout cycle while the account stays in that state. This differs from a payout that is scheduled but not yet sent. The **Payouts** page also shows a banner: "Payouts to your bank account are currently inactive. Review our Merchant Acceptance Policy to understand what might be affecting your account." The banner links to the [Merchant Acceptance Policy](/miscellaneous/merchant-acceptance) and does not name a specific reason. Most often, payouts have not been enabled yet. Live payments and payouts are enabled separately, so your account can take live payments while payouts still show as inactive. Payouts also require an approved **Bank Verification**, an approved **Business Verification** for registered entities, and a completed **Monitoring Review**. **1. Check Your Verification Forms** Open the **Verification** section of your dashboard. A form that is still in draft, under review, or on hold is the usual reason. Complete it to move your account forward. See [Verification Process](/miscellaneous/verification-process) for what each state means and how to respond to a form placed on hold. **2. Check the Threshold and the Cycle** When payouts are active, a payout is initiated only when your eligible balance meets your [payout threshold](#minimum-payout-threshold) and your next payout date arrives. A balance below the threshold carries forward to the next cycle. **3. Contact Support If Every Form Is Approved** If all forms are approved and payouts remain inactive, email [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email address. > [!NOTE] > > Active payouts do not mean a payout was **sent**. An active account with a balance under the threshold, or one that has not reached its next payout date, shows no scheduled payout. ### If Payouts Were Previously Active Payouts that have been running can return to inactive. The dashboard shows the same **Payouts Inactive** label, so check your verification status before you assume your account was never enabled. The usual reasons are: * **An open information request.** As part of ongoing monitoring, our compliance team may ask for additional information. An unanswered request can pause payout processing until you respond. See [Additional Information Requests](/miscellaneous/verification-process#additional-information-requests). * **A review in progress.** Payouts can be held while a compliance review of your account is completed, in line with our [Review and Monitoring Policy](/miscellaneous/review-monitoring-policy). Open the **Verification** section of your dashboard and complete any outstanding form. If nothing is outstanding, email [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email address. ## Payout Processing and Bank Timelines 1. The payout dates above are **initiation dates**. The payout is created at 00:00 UTC on that date. 2. After a payout is sent, the time it takes to reach your bank account depends on the receiving bank and the payout rail. 3. If a payout date falls on a weekend or a US Federal Reserve bank holiday, the payout moves to the next business day. The billing period does not change. The **Next Payout** date on the **Payouts** page already reflects the move. ### When Your Payout Date Moves When the bank holiday calendar moves your next payout date, Dodo Payments sends a **Payout date moved** in-app notification that names both dates, for example "Payouts scheduled for 2026-10-05 now run on 2026-10-06." * The notice covers only your **next** payout date, not later ones. * It is sent only while your payouts are active. * Every team member with in-app notifications receives it, subject to your payout notification settings in [Communication Preferences](/features/communication-preferences). * When the new date is later than the old one, the **Payouts** page shows the move as a banner until you dismiss it, and the next payout card on **Home** shows a "Moved to" note under it. ### If a Payout Shows Success but Has Not Arrived A payout with the status **Success** has been sent to your bank. A payout that shows **Initiated** or **In Progress** has not been sent yet. See [Payout Status](#payout-status). After a payout is sent, the receiving bank and the payout rail decide when the funds appear, and a cross-border transfer can pass through intermediary banks first. To locate a payout that shows **Success** but is not in your account: **1. Check Which Account Received It** On the **Payouts** page, check your **Active Bank Account**. If you changed the active account recently, a payout processed before the change is credited to the previous account. **2. Ask Your Bank to Trace the Transfer** Give your bank the payout amount, the currency, and the payout date. Your bank can search for incoming and pending transfers that have not yet been credited to your account. **3. Contact Support If Your Bank Can't Find It** Email [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email address. Include the payout amount, the payout date, and the payout ID if you have it. Payout IDs begin with `pyt_`. ## Payout Currency and Bank Conversion Payout balances are held in your USD, GBP, and EUR wallets. After a transfer leaves Dodo Payments, two things outside our control can change the amount credited to your account: * **Conversion by your bank.** If your account is credited in a different currency from the one the transfer is sent in, your bank converts the transfer on arrival at **its own exchange rate**. It may also apply its own receiving or conversion charges. * **Intermediary bank charges.** Cross-border transfers can pass through correspondent banks, which may deduct their own charges. Both happen at the banks, not at Dodo Payments. As a result, the amount credited to your account can be lower than the payout amount in your dashboard, and these charges do not appear on your payout invoice. > [!NOTE] > > Payout routes and currencies vary by country. Contact [support@dodopayments.com](mailto:support@dodopayments.com) to confirm how your payouts are sent and credited before you link a bank account. ## Minimum Payout Threshold | Currency | Default Threshold | Lowest Threshold You Can Set | | - | - | - | | USD | \$100 | \$50 | > [!NOTE] > > If your payable balance does not meet the threshold, it carries forward to the next payout cycle. > [!WARNING] > > **INR native wallet discontinued:** Support for the INR native wallet and INR-denominated payouts has been discontinued. Payouts are consolidated through the USD, GBP, and EUR wallets only. INR remains supported as a transaction currency for UPI, RuPay, and Indian-card subscriptions. Scheduled payouts do not include an INR balance, and an INR balance does not count toward your threshold. Dodo Payments can move an INR balance to your USD wallet, less a currency conversion fee. The moved amount is then included in your next payout. To request this, contact [support@dodopayments.com](mailto:support@dodopayments.com). > [!WARNING] > > The threshold applies to your combined balance across the USD, GBP, and EUR wallets, converted to USD. A payout is initiated only when that combined balance is equal to or greater than your threshold. A single wallet reaching the amount on its own does not trigger a payout. The exception is a wallet linked through [Settlement Currencies](#settlement-currencies). A linked wallet is not part of the combined balance, and it must reach the threshold on its own. ## Flexible Minimum Payout Threshold You can set the balance that must build up before Dodo Payments initiates a payout. The threshold is set in USD. **Configuration:** * **Allowed values:** \$50 or any higher amount * **Effective from:** Your current payout cycle * **Note:** A payout that is already scheduled for the cycle keeps its existing amount ### How to Edit Your Threshold **1. Navigate to Payout Settings** Go to **Settings → Payouts**, or click **Manage** on the **Payout Schedule & Settings** card of the **Payouts** page. **2. Enter New Threshold** Under **Customise Payouts**, enter a value of **50 or more** in **Minimum Payout** (for example, `250`). **3. Save Changes** Click **Save**. The dashboard confirms with **Minimum payout updated**. > [!NOTE] > > The threshold is compared against your combined USD, EUR, and GBP wallet balances, converted to USD. A wallet linked through [Settlement Currencies](#settlement-currencies) is not part of the combined balance. It is compared on its own. ## Payout Accounts The **Linked Bank Accounts** card on the **Payouts** page lists the bank accounts that receive your payouts. To add, activate, or delete an account, click **Manage Accounts**, which opens **Settings → Payouts**. You can link up to **six payout accounts**; deleted accounts don't count toward the limit. Each account is registered for a **currency** and a **transfer method**. * **Add an account** with **Add Bank Account**, choosing the currency and transfer method you want to be paid in. * **Save a draft** if you do not have every detail on hand, and finish the submission later. You can no longer edit an account after you submit it. * **Resubmit** an account placed on hold. The hold or failure reason appears on the account so you know what to correct. * The **first approved account is activated automatically**. Payouts are sent to your **Active Bank Account**, unless you use [Settlement Currencies](#settlement-currencies). * **Choose Other for an unlisted bank.** If your bank is not in the list, select **Other** and type the bank name. * **Confirm a bank code before you submit.** For some countries, including Nepal, the local transfer form lists bank codes instead of bank names. If you can't match your bank to a code, email [support@dodopayments.com](mailto:support@dodopayments.com) with your bank's name and country. Support confirms the code. Wait for the confirmation before you submit, because you can't edit an account after you submit it. > [!NOTE] > > In **Settings → Payouts**, open the menu on an approved account and click **Set As Active** to make it your active account. By default, it replaces your current active account and becomes your primary account. If multi-currency payouts are enabled for your business, it replaces only the active account in the same currency. Payouts go to the new account from your next payout cycle, and a payout already processed is still credited to the previous account. You can **Delete** any account that is not active. ### Settlement Currencies With settlement currencies, you can get paid in the currency that you earn, instead of one converted payout. You link a USD, EUR, or GBP wallet to an approved bank account. The balance of that wallet then goes to that account. > [!NOTE] > > Settlement currencies are available only when Dodo Payments turns on multi-currency payouts for your business. To request this, contact [support@dodopayments.com](mailto:support@dodopayments.com). The **Settlement Currencies** card appears in **Settings → Payouts** only when the feature is on. ![Add a settlement currency dialog with the Currency and Bank Account fields](https://mintcdn.com/dodopayments/BxNFH14Y2X6lXkp3/images/payouts/add-settlement-currency.png?fit=max\&auto=format\&n=BxNFH14Y2X6lXkp3\&q=85\&s=0ac39e8bdf16340620f060299fd20a90) **1. Open the Settlement Currencies Card** Go to **Settings → Payouts**, then find the **Settlement Currencies** card. **2. Add a Settlement Currency** Click **Add settlement currency**. Select the **Currency** and an approved **Bank Account**, then click **Add Currency**. **3. Set Your Primary Account** To change the account that receives your other balances, open the menu on an active account and click **Make primary**. * Each wallet links to one bank account, and each bank account takes one wallet. * A linked wallet is paid out in its own currency. Dodo Payments does not convert it and charges no conversion fee. If the bank account is in a different currency, your bank converts the transfer on arrival. See [Payout Currency and Bank Conversion](#payout-currency-and-bank-conversion). * **Other balances** are the wallets that you did not link. Dodo Payments converts them to the currency of your **Primary** account and sends them there. A currency conversion fee applies to this conversion. * Each linked wallet must reach your minimum payout on its own. The threshold is not converted: a threshold of 300 means 300 USD, 300 EUR, or 300 GBP. * Linked wallets are not part of the combined balance. Only the unlinked wallets and the primary account's wallet are converted to USD and compared against the threshold together. For example, if you link EUR, the EUR wallet is compared on its own, and the USD and GBP wallets are compared together. * You can have up to three active accounts at a time, and only one active account for each account currency. Your primary account must be one of them. * To stop a link, click the unlink icon on the wallet, then click **Unlink** to confirm. The wallet balance then goes to your primary account. To unlink the wallet of your primary account, first make a different account primary. * If multi-currency payouts are turned off for your business, only your primary account receives payouts. Your other accounts become inactive but stay approved, and Dodo Payments removes their wallet links. > [!NOTE] > > Bank verification during business onboarding uses the same payout accounts flow, so the account you submit while onboarding appears on the **Payouts** page as your first payout account. See [Account Verification](/miscellaneous/verification-process). > [!WARNING] > > Bank account details must match your verified identity or registered entity name. Dodo Payments cannot process payouts to mismatched or third-party accounts. See [Account Verification](/miscellaneous/verification-process) for the full name-matching rules. ### Which Accounts You Can Use The account must belong to you: the verified individual or the registered entity on your Dodo Payments account. Within that rule, you have more options than many merchants expect: * **The account's country does not have to match your ID's country.** The country that issued your identity document decides whether you can onboard. Your payout account can be in a different country, provided it is held in your own name. See [How Your Eligible Country Is Determined](/miscellaneous/accepted-countries-and-territories#how-your-eligible-country-is-determined). * **A joint personal account is eligible.** If you are one of the named account holders and your name matches your identity verification, a joint account can receive payouts. Compliance may ask for supporting documents before approving it, such as a bank confirmation letter or a recent statement showing the account holders and account identifiers. * **A registered entity must use the entity's account.** If you onboarded as a registered entity, payouts go to an account in the company's legal name, not to a director's personal account. ### How Your Transfer Method Affects Currency and Cost A payout account is registered for a specific **currency and transfer method**. That choice decides the currency your bank credits you in and whether a per-wire fee is deducted. A USD SWIFT account does not guarantee that you keep USD: if the receiving account cannot hold USD, your bank converts the transfer on arrival at its own rate. | Transfer method | Typically credited in | Per-wire fee | | - | - | - | | International SWIFT wire | USD | USD SWIFT payout fee, deducted from the payout | | Local bank transfer | Your local currency | None; processed as a domestic transfer | | Payoneer receiving account | The account's currency | None where the account provides local routing and account numbers, since it is sent as a domestic transfer | * **To be paid in your local currency,** register the account with your local bank details and the **Local** transfer method instead of **Swift**. This avoids the wire fee. * **To hold USD,** register a USD account that can receive and hold USD, so your bank has no reason to convert the transfer on arrival. * **Some bank countries offer only a USD SWIFT account.** When no local transfer option covers your bank's country, the bank form offers **USD** as the only currency and **SWIFT** as the only transfer method. * **Payoneer is treated as a regular bank account.** Enter its details in the bank form as you would for any other account. There is no separate Payoneer integration. > [!NOTE] > > See the [pricing page](https://dodopayments.com/pricing) for current payout and USD SWIFT wire fees. For **Swift** transfers, intermediary and beneficiary bank fees may also apply and are deducted from the payout amount. See [Payout Currency and Bank Conversion](#payout-currency-and-bank-conversion). > [!NOTE] > > Available transfer methods vary by country, and not every method is offered for every account. Your dashboard shows the methods available to you when you add an account. If you are unsure which option suits your setup, contact [support@dodopayments.com](mailto:support@dodopayments.com) before you link an account. ## Reserved Balance Dodo Payments can hold back a share of your settled payments as a reserve for a set period. When a reserve is held, the **Payout Balance** card on the **Payouts** page shows a **Reserved** row under **Incoming**. * The reserved amount is still your money. It is not a fee. * It is released back into your balance automatically. * It is already excluded from your **Available** and **Incoming** amounts, so it is not deducted a second time from your payout. If no reserve is held on your account, the **Reserved** row does not appear. In [Reports](/features/reports), reserve holds and releases appear under **Other movements**. ## Payout Deductions The following amounts are deducted from your sales before payout: **Taxes:** The tax calculated on each payment is deducted from the sales amount. Dodo Payments remits it to the tax authority. **Fees:** Dodo Payments transaction fees are deducted from each payment. A payout fee is deducted from each payout. Under standard pricing, the payout fee is \$5 for payouts below \$1,000 (or the GBP or EUR equivalent). **Refunds and Disputes:** Refunded amounts, disputed amounts, and their fees are deducted from your balance when they occur. See [Balances](/features/account-summary-payout-wallet) for each ledger entry. > [!NOTE] > > Charges from your own bank or from intermediary banks are not deducted here and do not appear on your payout invoice. See [Payout Currency and Bank Conversion](#payout-currency-and-bank-conversion). > [!TIP] > > For detailed fee information, see our [Pricing Page](https://dodopayments.com/pricing). ## Payout Status Your **Payout History** shows one of the following statuses for each payout: | Dashboard status | API `status` | Description | Webhook event | | - | - | - | - | | Initiated | `not_initiated` | The payout is created and waits for processing | `payout.created` | | In Progress | `in_progress` | The payout is being processed | `payout.in_progress` | | On Hold | `on_hold` | The payout team has put the payout on hold | `payout.on_hold` | | Success | `success` | The payout was sent to your bank account | `payout.success` | | Failed | `failed` | The payout failed. The payout amount and payout fee are credited back to your balance as **Payout Reversal** and **Payout Fees Reversal** | `payout.failed` | Every status change emits a webhook, so you can reconcile payouts in your own systems without polling. See [Payout Webhooks](/developer-resources/webhooks/intents/payout) for the payload and delivery details. To receive email or in-app notifications for the same changes, see [Communication Preferences](/features/communication-preferences). ## Payout Invoice Each payout has a self-billed invoice that records the amount Dodo Payments pays to your business. Your business appears under **Billed From**, and the Dodo Payments payout entity appears under **Billed to**. The invoice shows **Paid** after the payout succeeds and **Unpaid** before that. To download it, open **Payout History**, click the payout in the **Details** column, and in the **Payout Details** panel click **Download → Download Invoice**. The **Payout Details** panel also breaks the payout down by ledger entry type, such as **Payments**, **Tax Deducted**, and **Payment Fees**. When the entries a payout settles do not add up to the payout amount, the difference appears as **Unattributed Balance**, listed last, directly above the total. A positive amount means the payout drew on balance left over from an earlier period. A negative amount means the entries came to more than the payout, and the remainder funds a later payout. ### Invoice Structure ![Payout invoice showing invoice ID, billed to and billed from details, payout line item, and total](https://mintcdn.com/dodopayments/5D2vY2CKcFOZLLyz/images/payouts/payout-process/Invoice%20-%20Payout.png?fit=max\&auto=format\&n=5D2vY2CKcFOZLLyz\&q=85\&s=03746005d9b9e88a63c83d1c392ebe78) > [card] [Balances & Wallets](/features/account-summary-payout-wallet) > > View your USD, GBP, and EUR wallet balances, the transaction ledger, and payout-related activity. # Product Collections Source: https://docs.dodopayments.com/features/product-collections Group related products together for unified checkout experiences, plan selection, and upgrade/downgrade paths within the Customer Portal. > [!NOTE] > > Product Collections group related products (e.g., Starter, Pro, Enterprise plans) under one umbrella. Display all options in a single checkout, define upgrade/downgrade paths, and let customers switch plans directly from the Customer Portal. ![Screenshot of the Product Collection checkout page showing multiple products displayed](https://mintcdn.com/dodopayments/2YrxTqbaYgAm54C_/images/product-collection/checkout-page.png?fit=max\&auto=format\&n=2YrxTqbaYgAm54C_\&q=85\&s=1890932384bc32c8126c7993f3581855) ## Key Highlights Product Collections let you: * Group related products (plans, tiers, pricing options) for organized management. * Include multiple products, such as Starter, Pro, and Lifetime, each with its own pricing model. * Display all products in one checkout view, so customers compare and choose their preferred plan. * Enable customers to upgrade or downgrade between products in the same collection via the Customer Portal. * Control which products are visible, in what order, and which is pre-selected at checkout. ## Creating a Product Collection Create and manage collections from the dashboard or via API. **1. Create the collection** Define the collection with a name and optional description. Upload an image to represent it in checkout. ![Screenshot of the Product Collection creation form in the dashboard showing fields for name, description, and image upload](https://mintcdn.com/dodopayments/2YrxTqbaYgAm54C_/images/product-collection/collection-form.png?fit=max\&auto=format\&n=2YrxTqbaYgAm54C_\&q=85\&s=4740b9da84da8c24177a9592549222af) **Collection fields:** * **Name** (required): Display name (e.g., "SaaS Plans", "License Tiers"). * **Description** (optional): Brief explanation shown in checkout. * **Image** (optional): Visual branding for the collection. **2. Add products to the collection** Add existing products to your collection. Organize them into groups for better structure. ![Screenshot of the Product Collection products page showing a list of products and the ability to add them to the collection](https://mintcdn.com/dodopayments/2YrxTqbaYgAm54C_/images/product-collection/collection-form-products.png?fit=max\&auto=format\&n=2YrxTqbaYgAm54C_\&q=85\&s=41b2da4d40e8dd9a12d059f4fa3f285f) **Product organization:** * **Groups**: Optionally organize products into named groups (e.g., "Monthly Plans", "Annual Plans"). * **Ungrouped products**: Products without a group appear at the collection level. * **Ordering**: Drag and drop to set the display order. > [!WARNING] > > Each product can belong to only one collection. If a product is already in another collection, remove it first. **3. Configure ordering and visibility** Control the display order and visibility of products within the collection. **Configuration options:** * **Product status**: Enable or disable individual products within the collection. * **Display order**: Drag and drop to set the sequence products appear in checkout. > [!NOTE] > > The first product in the collection is automatically pre-selected at checkout. Reorder products to change which one is selected by default. ## Collection Checkout Collections enable a unified checkout experience where customers view and select from all available products in one place. ### Checkout Types | Type | Description | Use Case | | - | - | - | | **Collection Checkout** | Displays all active products within a collection | Subscription plan selection, tiered pricing | | **Single Product Checkout** | Displays only one specific product | Direct purchase, promotional links | ### Collection Checkout Experience When using a collection checkout: 1. All active products in the collection are displayed. 2. The first product in the collection order is automatically pre-selected. 3. Each product shows its name, description, and pricing. 4. The customer selects one product to purchase. 5. Checkout proceeds with the chosen product's pricing and billing settings. ![Screenshot of the Product Collection checkout page showing multiple products displayed](https://mintcdn.com/dodopayments/2YrxTqbaYgAm54C_/images/product-collection/checkout-page.png?fit=max\&auto=format\&n=2YrxTqbaYgAm54C_\&q=85\&s=1890932384bc32c8126c7993f3581855) > [!TIP] > > Collection checkout is ideal for subscription businesses where customers compare plans side-by-side before purchasing. ### API Integration Create a checkout session for a collection: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_collection_id: 'pdc_abc123', product_cart: [], // Required: pass an empty array for collection checkout return_url: 'https://yoursite.com/return' }); window.location.href = session.checkout_url; ``` > [!WARNING] > > When using `product_collection_id`, discount codes cannot be pre-applied at session creation. Customers can still enter codes during checkout if enabled. ## Customer Portal Integration Customers can upgrade or downgrade between products within the same collection directly from the Customer Portal. > [!TIP] > > Already have subscription products? Add them to a Product Collection to enable upgrade/downgrade flows in the Customer Portal. No need to recreate your products. ### Plan Management Actions | Action | Description | Merchant Control | | - | - | - | | **View Current Plan** | Display current product name, price, and renewal date. | Always available. | | **Upgrade Plan** | Move to a higher-tier product in the same collection. | Configurable (default: disabled). | | **Downgrade Plan** | Move to a lower-tier product in the same collection. | Configurable (default: disabled). | | **Cancel** | Cancel the subscription entirely. | Always available. | ![Screenshot of the Product Collection customer portal plan change interface showing the plan management actions](https://mintcdn.com/dodopayments/2YrxTqbaYgAm54C_/images/product-collection/portal.png?fit=max\&auto=format\&n=2YrxTqbaYgAm54C_\&q=85\&s=9b9d302907688238f6b84c10b85504aa) ### Upgrade/Downgrade Rules * Upgrades and downgrades are only available between products within the same collection. * Proration for Customer Portal plan changes follows the default upgrade and downgrade behavior in **Settings → Subscriptions**, and each collection can override those defaults. Plan changes made through the [Change Plan API](/api-reference/subscriptions/change-plan) use the `proration_billing_mode` sent with the request. * Email notifications are sent to the business on every upgrade, downgrade, or cancellation. ![Screenshot of the Product Collection customer portal plan change interface showing the plan management actions](https://mintcdn.com/dodopayments/2YrxTqbaYgAm54C_/images/product-collection/portal-change-plan.png?fit=max\&auto=format\&n=2YrxTqbaYgAm54C_\&q=85\&s=e4fe60146a7d8436753a36a79f902a6d) > [!NOTE] > > Customers cannot change to products outside their current collection. Create separate collections for distinct product lines. ## Subscription Settings Configure how subscriptions and plan changes work across your business from **Settings → Subscriptions** in your dashboard. ![Screenshot of the subscription settings page showing Allow Multiple Subscriptions and Allow Subscription Updates toggles](https://mintcdn.com/dodopayments/2YrxTqbaYgAm54C_/images/product-collection/business-settings.png?fit=max\&auto=format\&n=2YrxTqbaYgAm54C_\&q=85\&s=9ed2f332336aab522b5238ce7218d8ae) ### Available Settings The page groups the settings into three sections: **Subscription Behavior**, **Billing and Renewals**, and **Customer Portal**. The default upgrade and downgrade behavior follows them, and shows only when **Allow Subscription Updates** is on. | Section | Setting | Description | Default | | - | - | - | - | | Subscription Behavior | **Allow Multiple Subscriptions** | Customers can hold more than one active subscription at the same time. | Enabled | | Subscription Behavior | **Prevent Trial Misuse** | Customers who have already redeemed a trial are degraded to a paid, no-trial purchase instead of receiving a fresh trial. | Disabled | | Billing and Renewals | **Subscription Grace Period** | Keeps subscription benefits active for a set number of days while a renewal payment is unpaid. See [Grace Period](/features/subscription#grace-period). | Disabled | | Billing and Renewals | **Payment Method Reminder** | Days before billing starts that a [Card-Optional at Zero Price](/features/subscription#card-optional-at-zero-price) subscription's customer is emailed to add a payment method (1 to 30 days). | 3 days | | Billing and Renewals | **Collect Plan Change Payments by Payment Link** | An immediate upgrade sends the customer to a checkout page to pay, instead of charging their saved payment method. See [Collecting Plan Change Payments by Payment Link](/features/customer-portal#collecting-plan-change-payments-by-payment-link). | Disabled | | Billing and Renewals | **Bill Usage at Pause** | A paused usage-based subscription is invoiced for its owed usage at the moment it is paused, instead of carrying the usage to the next regular invoice. | Enabled | | Customer Portal | **Allow Subscription Updates** | Customers can upgrade or downgrade their existing subscriptions anytime via Customer Portal. | Disabled | | Customer Portal | **Allow Immediate Cancellation** | Customers can end their subscription and lose access straight away. | Enabled | | Customer Portal | **Allow Cancellation at Next Billing Date** | Customers can cancel at the end of the period they have already paid for. | Enabled | | Customer Portal | **Offer a Discount When a Customer Cancels** | Offers a discount on the next billing cycle to a customer who starts to cancel. Shows only when the retention offer is available for your business. See [Retention Offer](/features/customer-portal#retention-offer). | Disabled | | Customer Portal | **Allow Subscription Pause** | Customers can pause and resume their own subscriptions from the Customer Portal. | Disabled | > [!NOTE] > > Plan changes via Customer Portal are disabled by default. Enable "Allow Subscription Updates" in **Settings → Subscriptions** to let customers upgrade or downgrade between products in the same collection. > [!NOTE] > > The two cancellation settings are independent, so you can let customers see out the period they have already paid for while keeping instant cancellation to yourself, or the reverse. Turning one off hides that option in the Customer Portal and rejects requests for it through the Customer Portal API. Your own merchant-side cancellations are unaffected. See [Cancelling a Subscription](/features/customer-portal#cancelling-a-subscription). > [!NOTE] > > "Allow Subscription Pause" governs the Customer Portal only — you can pause and resume from the dashboard or the API whichever way it is set. "Bill Usage at Pause" applies to usage-based subscriptions only, and is recorded per billing cycle, so changing it mid-cycle does not change how the cycle in progress settles. See [Pausing and Resuming Subscriptions](/features/subscription#pausing-and-resuming-subscriptions). > [!NOTE] > > For details on how trial redemptions are matched and recorded, see [Preventing Trial Misuse](/features/subscription#preventing-trial-misuse). > [!NOTE] > > "Payment Method Reminder" only matters for subscriptions with [Card-Optional at Zero Price](/features/subscription#card-optional-at-zero-price) enabled — it has no effect on subscriptions that already require a card. See [What Happens Without a Card](/features/subscription#what-happens-without-a-card) for the full sequence, including what happens if the reminder is ignored. > [card] [Subscription Plan Changes](/features/subscription#subscription-plan-changes) > > Learn more about proration modes and plan change behavior. ## Managing Collections Manage collections through the dashboard or programmatically via API. ### Dashboard Operations * **Create**: Set up new collections with products and groups. * **Update**: Modify name, description, image, and product organization. * **Reorder**: Drag and drop to change product display order. * **Enable/Disable products**: Control which products appear in checkout. * **Archive**: Hide a collection without permanently deleting it (can be unarchived later). ![Screenshot of the Product Collection dashboard showing the collection management operations](https://mintcdn.com/dodopayments/2YrxTqbaYgAm54C_/images/product-collection/collection-dashboard.png?fit=max\&auto=format\&n=2YrxTqbaYgAm54C_\&q=85\&s=0fee5cdfe68c770b7cdb1d0f8e817b5b) ### API Management Use the following endpoints to create, update, retrieve, archive, and organize product collections programmatically, including managing nested groups and products. > [accordion] Listing Product Collections > > Fetch all product collections associated with your account using a `GET` request to the `/product-collections` endpoint. Supports pagination, filtering by brand, and including archived collections. > > > [card] [List Product Collections API](/api-reference/product-collections/list-product-collections) > > > > View detailed request and response structure in the List Product Collections API documentation. > [accordion] Creating a Product Collection > > Create a new product collection by sending a `POST` request to the `/product-collections` endpoint with the required `name` and `groups` of products, plus optional details such as description and brand. > > > [card] [Create Product Collection API](/api-reference/product-collections/create-product-collection) > > > > View detailed request and response structure in the Create Product Collection API documentation. > [accordion] Retrieving a Product Collection > > Get detailed information about a specific product collection — including its groups and product items — using a `GET` request to the `/product-collections/{id}` endpoint. > > > [card] [Get Product Collection API](/api-reference/product-collections/get-product-collection) > > > > View detailed request and response structure in the Get Product Collection API documentation. > [accordion] Updating a Product Collection > > Modify a product collection's details (name, description, brand, etc.) by sending a `PATCH` request to the `/product-collections/{id}` endpoint. > > > [card] [Update Product Collection API](/api-reference/product-collections/update-product-collection) > > > > View detailed request and response structure in the Update Product Collection API documentation. > [accordion] Uploading Collection Images > > Associate an image with a collection by uploading it via a pre-signed URL. Request an upload URL from the `/product-collections/{id}/images` endpoint, then `PUT` the image to the returned URL within 60 seconds. > > > [!WARNING] > > > > The pre-signed URL expires in 60 seconds, so the image must be uploaded within that timeframe. > > > [card] [Update Collection Images API](/api-reference/product-collections/update-product-collection-images) > > > > View detailed request and response structure in the Update Collection Images API documentation. > [accordion] Archiving a Product Collection > > Archive a collection by sending a `DELETE` request to the `/product-collections/{id}` endpoint. This hides the collection from new use but does not permanently remove it. > > > [card] [Archive Product Collection API](/api-reference/product-collections/archive-product-collection) > > > > View detailed request and response structure in the Archive Product Collection API documentation. > [accordion] Unarchiving a Product Collection > > Restore an archived collection by sending a `POST` request to the `/product-collections/{id}/unarchive` endpoint. > > > [card] [Unarchive Product Collection API](/api-reference/product-collections/unarchive-product-collection) > > > > View detailed request and response structure in the Unarchive Product Collection API documentation. > [accordion] Managing Groups within a Collection > > Groups let you organize products inside a collection (for example, "Monthly Plans" vs. "Annual Plans"). Use the groups endpoints to add, update, or remove groups within a collection. > > * **Create a group**: `POST /product-collections/{id}/groups` > > * **Update a group**: `PATCH /product-collections/{id}/groups/{group_id}`. To clear a group's name, send `group_name: null`. A collection can have only one group without a name, so the API returns `422` if another group in the collection already has no name. > > * **Delete a group**: `DELETE /product-collections/{id}/groups/{group_id}` > > > [card] [Create Group](/api-reference/product-collections/create-group) > > > > Add a new group to a product collection. > > > [card] [Update Group](/api-reference/product-collections/update-group) > > > > Modify a group's name or attributes. > > > [card] [Delete Group](/api-reference/product-collections/delete-group) > > > > Remove a group from a collection. > [accordion] Managing Products within a Group > > Manage the individual product items inside a group — add new products, update existing items (such as display order), or remove them entirely. > > * **Add products to a group**: `POST /product-collections/{id}/groups/{group_id}/items` > > * **Update a group item**: `PATCH /product-collections/{id}/groups/{group_id}/items/{item_id}` > > * **Delete a group item**: `DELETE /product-collections/{id}/groups/{group_id}/items/{item_id}` > > > [card] [Add Products to Group](/api-reference/product-collections/add-group-items) > > > > Add one or more products to a group within a collection. > > > [card] [Update Group Item](/api-reference/product-collections/update-group-item) > > > > Update a product item within a group. > > > [card] [Delete Group Item](/api-reference/product-collections/delete-group-item) > > > > Remove a product item from a group. ## Best Practices * **Group logically**: Organize products by billing interval (monthly/annual) or feature tier (starter/pro/enterprise). * **Order strategically**: Place your most popular or recommended plan first, as it will be pre-selected at checkout. * **Use clear naming**: Product names should clearly communicate value differences. * **Enable both directions**: Allow both upgrades and downgrades to give customers flexibility. * **Consider proration**: Choose a proration mode that aligns with your business model. * **Test thoroughly**: Verify checkout and plan change flows in test mode before going live. > [card] [Products](/features/products) > > Create one-time, subscription, or usage-based products to add to collections. > [card] [Checkout](/features/checkout) > > Display collection products in a unified checkout experience. > [card] [Customer Portal](/features/customer-portal) > > Let customers upgrade or downgrade within the same collection. > [card] [Subscriptions](/features/subscription) > > Manage recurring plans with proration and plan changes. > [card] [Pricing as Code](/developer-resources/terraform-provider) > > Define collections and their plans with Terraform. # Products Source: https://docs.dodopayments.com/features/products Create one-time, subscription, or usage-based products. Manage pricing, media, and automated fulfillment in one place. Products are the foundation of Dodo Payments. Whether you sell a one-time download, a recurring subscription, or usage-based access, you start by creating a product. Each product defines how it's priced, presented at checkout, and fulfilled after purchase. > [card] [One-Time](/features/one-time-payment-products) > > Charge once for lifetime access or a single deliverable. > [card] [Subscriptions](/features/subscription) > > Bill on a schedule with trials, proration, and add-ons. > [card] [Usage-Based](/features/usage-based-billing/introduction) > > Meter consumption and bill by actual usage. ## Create a Product Create products from the dashboard or via API. Choose the pricing model upfront—One-Time, Subscription, or Usage-Based—then configure the details. The pricing model is immutable; create a new product if you need a different model. **1. Name and Description** Provide a clear title and a concise, value-oriented description. Markdown is supported in descriptions. > [!TIP] > > Keep the first sentence customer-facing and outcome-oriented; it appears prominently in checkout. ![Products dashboard showing product creation form](https://mintcdn.com/dodopayments/r-ndtvzx3WhKqwER/images/products.png?fit=max\&auto=format\&n=r-ndtvzx3WhKqwER\&q=85\&s=fb41221c4f2af4de0155e71de1ac6904) **2. Pricing Model and Price** Select the pricing model: * **One-Time**: Fixed price paid once. * **Subscription**: Recurring price with interval and optional trial. * **Usage-Based**: Price derived from metered events. Then set pricing: * **Price**: Base amount and currency. You can set the base price in any currency Dodo Payments supports, except for [Pay What You Want](/features/pay-what-you-want) products, whose base currency must be USD, GBP, or EUR. USD, GBP, EUR, and INR are pinned to the top of the currency selector for quick access. * **Discount Applicable (%)**: Optional percentage discount shown in checkout and invoices. You can enter up to two decimal places, such as `10.5`. In the API, set the discount in basis points with `discount_bps`, so `1050` is 10.5%. The legacy `discount` field is deprecated and rounds to a whole percent. * For subscriptions, set **Repeat every** (e.g., 1 month or 1 year), **Trial days**, and an optional **Trial amount** for a [paid trial](/features/subscription#paid-trials). A non-zero subscription price must meet the [subscription minimum](/features/adaptive-currency#minimum-amounts) for the currency the customer pays in: \$1.00 for USD. Currencies other than USD, EUR, and GBP must also be worth at least \$1.00. A price of exactly \$0 is also supported, and you can let customers start a \$0 subscription without a card; see [Card-Optional at Zero Price](/features/subscription#card-optional-at-zero-price). Negative amounts aren't supported. > [!NOTE] > > With [Adaptive Currency](/features/adaptive-currency) turned on, customers outside your base currency are billed in their local currency, so you can author prices in whichever currency best fits your market. With it off, they pay in your base currency. > [!TIP] > > Want a fixed price per currency or country instead of a live FX conversion? Set a `pricing_mode` on the product and attach [Localized Pricing](/features/localized-pricing) rules, such as €9.99 in EUR or ₹999 in India. > [!WARNING] > > Editing a price changes what new customers pay. Existing subscriptions are never repriced; each keeps the price it was created with. To move an existing subscriber onto a different price, change their plan explicitly with the [Change Plan API](/api-reference/subscriptions/change-plan); proration settings apply to that plan change, not to price edits. **3. Product Media** Upload images to showcase the product on checkout and invoices. Supported formats: PNG, JPG, WebP, up to 3 MB. Reorder or replace images at any time. **4. Automated Entitlements** In the **Entitlements** section, attach fulfillment that activates automatically after payment: * **License Keys**: Issue and validate unique keys. * **Digital Files**: Grant secure file access. * **Feature Flags**: Unlock a capability that your app checks. * **Platform Access**: Grant access on Discord, GitHub, Telegram, Figma, Framer, or Notion. Add or remove benefits as your offer evolves. Existing subscribers gain or lose access accordingly. ## Variants and Pricing Options Instead of variants under one product, create separate products for each pricing option (for example, Monthly and Yearly). Then group them into a Product Collection to present all options in a single checkout and enable plan switching in the Customer Portal. ![Checkout page showing multiple product options in a collection](https://mintcdn.com/dodopayments/2YrxTqbaYgAm54C_/images/product-collection/checkout-page.png?fit=max\&auto=format\&n=2YrxTqbaYgAm54C_\&q=85\&s=1890932384bc32c8126c7993f3581855) ### Why This Approach? * **Clear pricing models**: Each product has a single, well-defined pricing model (one-time, subscription, or usage-based). * **Predictable APIs**: Simpler integrations without nested variant logic. * **Easier reporting**: Track revenue and metrics per product without variant aggregation. * **Flexible checkout**: Display multiple products side-by-side, letting customers compare and choose. ### How Product Collections Work 1. **Create products**: Set up individual products for each plan (e.g., Starter Monthly, Starter Annual, Pro Monthly, Pro Annual). 2. **Group into a collection**: Add related products to a Product Collection. 3. **Unified checkout**: Customers see all options in one checkout and select their preferred plan. 4. **Plan switching**: Customers can upgrade or downgrade between products in the same collection via the Customer Portal. > [card] [Product Collections](/features/product-collections) > > Group related products together for unified checkout experiences and upgrade/downgrade paths. ## Managing Products You can manage products through the dashboard or programmatically via API. The API provides full control over product creation, updates, retrieval, image uploads, and archiving. To keep your products and prices in a Git repository and review each change in a pull request, use the [Terraform provider](/developer-resources/terraform-provider). ### Dashboard Management * **Update**: Edit name, description, images, price, fields, and benefits at any time (pricing model is immutable). * **Archive**: Hide a product from new purchases without disrupting existing customers. You can unarchive later. * **Drafts**: An in-progress product is saved as a draft so you can return to it later. Drafts are kept separately for test mode and live mode, so an unfinished product in one mode never bleeds into the other. Use **Clear Draft** to discard it and start fresh. > [!TIP] > > Product and collection form pages include header action buttons, so you can save without scrolling to the bottom of a long form. ### API Management The following instructions allow you to create, update, manage, and retrieve products, including uploading images. > [accordion] Creating a Product > > Send a `POST` request to the `/products` endpoint with details such as name, description, price, currency, and whether it is a recurring product. > > For recurring products, set the `price` object to a recurring price (`type: recurring_price`) and specify `payment_frequency_interval` and `subscription_period_interval` (`Day`, `Week`, `Month`, or `Year`) along with their corresponding counts. > > > [!WARNING] > > > > `subscription_period` defines when the subscription expires, not the billing cycle. For a subscription that renews until the customer cancels it, set the period to 20 years (the recommended value and the maximum). If the subscription period equals the payment frequency, the subscription expires after a single charge. > > > [card] [Create Product API](/api-reference/products/post-products) > > > > View detailed request and response structure in the Create Product API documentation. > [accordion] Updating a Product > > Send a `PATCH` request to the `/products/{id}` endpoint. You can update properties such as name, price, and description while keeping other details unchanged. > > Ensure that the `id` in the endpoint is the `product_id` of an existing product. > > > [card] [Update Product API](/api-reference/products/patch-products) > > > > View detailed request and response structure in the Update Product API documentation. > [accordion] Retrieving Products > > Fetch a list of products stored in your account using a `GET` request to the `/products` endpoint. This allows you to retrieve product details, including active and archived products. > > > [card] [Retrieve Products API](/api-reference/products/get-products) > > > > View detailed request and response structure in the Retrieve Products API documentation. > [accordion] Uploading Product Images > > Associate an image with a product by uploading it to AWS S3 using a pre-signed URL provided by the API. First, request an image upload URL from the `/products/{id}/images` endpoint, then use the provided URL to upload the image within 60 seconds. > > > [!WARNING] > > > > The pre-signed URL expires in 60 seconds, so the image must be uploaded within that timeframe. > > Once the pre-signed URL is received from the API, upload the image using the `PUT` method. This ensures secure and temporary access to AWS S3 for uploading the image. > > **Supported libraries for uploading to S3:** > > * **Node.js**: `axios`, `node-fetch` > * **Python**: `requests`, `boto3` > * **Go**: `net/http` > * **PHP**: `GuzzleHttp` > * **Ruby**: `rest-client` > > If the upload is successful, AWS S3 will return a `200 OK` status, indicating that the image has been stored successfully. > > > [card] [Upload Product Image API](/api-reference/products/put-products-images) > > > > View detailed request and response structure in the Upload Product Image API documentation. > [accordion] Archiving a Product > > Hide a product from new purchases without deleting it permanently using a `DELETE` request to the `/products/{id}` endpoint. > > > [card] [Archive Product API](/api-reference/products/archive-product) > > > > View detailed request and response structure in the Archive Product API documentation. > [accordion] Unarchiving a Product > > Restore an archived product by sending a `POST` request to the `/products/{id}/unarchive` endpoint. This reactivates the product and makes it available for use again. > > > [card] [Unarchive Product API](/api-reference/products/unarchive-product) > > > > View detailed request and response structure in the Unarchive Product API documentation. > [accordion] Checkout and Fulfillment > > Create payment or subscription flows from products, and fulfill automatically via benefits and webhooks. > > > [card] [Checkout Sessions](/developer-resources/checkout-session) > > > > Create checkout sessions for one-time or subscription purchases. > > > [card] [Payment Webhooks](/developer-resources/webhooks/intents/payment) > > > > React to payment lifecycle events. > > > [card] [Subscription Webhooks](/developer-resources/webhooks/intents/subscription) > > > > Handle subscription created, renewed, and canceled events. ## Best Practices * **Start with clarity**: Separate products for each pricing option (Monthly vs Yearly). * **Use trials thoughtfully**: Pair trials with onboarding to drive activation. * **Automate fulfillment**: Use benefits and webhooks to deliver instantly. * **Tag with metadata**: Store your system IDs for reconciliation. ## Related > [card] [Product Analytics](/features/analytics-and-reporting#product-level-analytics) > > Track revenue, customers, retention, subscribers, and MRR for each individual product. > [card] [Localized Pricing](/features/localized-pricing) > > Set fixed per-currency or per-country prices on a product instead of relying on live exchange rates. > [card] [Pricing as Code](/developer-resources/terraform-provider) > > Manage products and prices with Terraform, and review each change in a pull request. # Purchasing Power Parity Source: https://docs.dodopayments.com/features/purchasing-power-parity Charge less in price-sensitive countries automatically. Set one percentage per country, opt a product in, and Dodo Payments applies it at checkout. Purchasing Power Parity (PPP) charges a customer a share of your list price, based on the country they buy from. A \$20 product can sell for **\$6.00 in India** without a discount code and without a second price list. ## What Is Purchasing Power Parity? The same price is not equally affordable everywhere. \$20 is a small purchase in the United States and a large one in the Philippines. PPP pricing corrects for that difference. Dodo Payments keeps one percentage for each country. The percentage is the **share of your list price the customer pays**. India is 30, so a customer in India pays 30% of the price. The United States is 100, so nothing changes there. You turn PPP on for each product price you want it to apply to. Products you do not opt in keep their normal price everywhere. > [!NOTE] > > PPP requires [Adaptive Currency](/features/adaptive-currency). Turn on Adaptive Currency first. ## Key Benefits * **Reach price-sensitive markets** — Sell at a local price without lowering your home price. * **No banner and no script** — The price is correct at checkout. Nothing is added to your website. * **No discount codes to manage** — Nothing to create, rotate, or revoke. * **Per-product control** — Opt in a starter plan and leave an enterprise plan alone. * **Works everywhere** — One-time, subscription, and usage-based products. ## Enable Purchasing Power Parity **1. Enable Adaptive Currency** Go to **Settings → Pricing** and turn on **Adaptive Currency**. PPP does nothing without it. ![Adaptive Currency and Purchasing Power Parity in Pricing settings](https://mintcdn.com/dodopayments/IwVqFRrixZtmLsQJ/images/ppp/adaptive-currency-toggle.png?fit=max\&auto=format\&n=IwVqFRrixZtmLsQJ\&q=85\&s=ee1991adaee0be2fa451d7d30dc2e895) **2. Review your country percentages** Under **Purchasing Power Parity**, click **Edit** to open **Country Prices**. Change the percentage for any country, then click **Save Changes**. Set **Example product price** to see what each country pays. The **Your Price** column updates as you type. Use the search box to find a country by name or code. ![Country Prices dialog with a percentage and resulting price for each country](https://mintcdn.com/dodopayments/IwVqFRrixZtmLsQJ/images/ppp/country-percentages.png?fit=max\&auto=format\&n=IwVqFRrixZtmLsQJ\&q=85\&s=65667f71738c7853304c7b98de9a8e56) > [!NOTE] > > These percentages are business-wide. Every product with Purchasing Power Parity enabled uses them. **3. Turn PPP on for a product** Open the product. In the **Pricing** section, tick **Purchasing Power Parity**, then save the product. Products you do not tick keep their normal price everywhere. ![Purchasing Power Parity ticked in the product Pricing section](https://mintcdn.com/dodopayments/IwVqFRrixZtmLsQJ/images/ppp/product-toggle.png?fit=max\&auto=format\&n=IwVqFRrixZtmLsQJ\&q=85\&s=aed79a5480257284519b903c2e1965eb) > [!WARNING] > > You cannot enable this while Adaptive Currency is off. Turn on Adaptive Currency first. **4. Confirm at checkout** > [!TIP] > > Open a test checkout with a billing country that has a percentage below 100. Confirm the reduced price appears. ## How the Price Is Calculated The country percentage multiplies your list price: ``` price paid = list price × country percentage ÷ 100 ``` A \$20.00 product, for a customer in India at 30: ``` 2000 × 30 ÷ 100 = 600 → $6.00 ``` Dodo Payments applies the percentage to the base price, before currency conversion. [Adaptive Currency](/features/adaptive-currency) then converts the result to the customer's currency. > [!NOTE] > > Dodo Payments reads the country from the customer's **billing country** at checkout. ### Country Percentages Each country has one percentage between **30 and 100**: * **100** means the customer pays your full price. There is no reduction. * **30** is the lowest value you can set. The largest reduction is therefore 70%. The default values come from World Bank price level index data. Dodo Payments rounds each value to the nearest 5, applies a floor of 30, and caps it at 100. Every supported country has a value. You can change any of them. These are a few of the default values, to show the range: | Country | Percentage | A \$20 product sells for | | :- | :-: | :- | | United States | 100 | \$20.00 | | United Kingdom | 85 | \$17.00 | | Germany | 75 | \$15.00 | | Japan | 60 | \$12.00 | | Brazil | 45 | \$9.00 | | South Africa | 40 | \$8.00 | | Philippines | 35 | \$7.00 | | India | 30 | \$6.00 | > [!NOTE] > > The full list covers 217 countries. Open the country table in your dashboard to see every value. ## Enable via API PPP is enabled per product, with the `purchasing_power_parity` field. The default is `false`. > [!NOTE] > > Country percentages are managed in the dashboard only. They are not part of the public API. ```typescript theme={null} theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode', }); const product = await client.products.create({ name: 'Starter Plan', tax_category: 'saas', price: { type: 'one_time_price', currency: 'USD', price: 2000, discount_bps: 0, purchasing_power_parity: true, }, }); ``` ```python theme={null} theme={null} import os from dodopayments import DodoPayments client = DodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), environment="test_mode", ) product = client.products.create( name="Starter Plan", tax_category="saas", price={ "type": "one_time_price", "currency": "USD", "price": 2000, "discount_bps": 0, "purchasing_power_parity": True, }, ) ``` ```go theme={null} theme={null} package main import ( "context" "os" "github.com/dodopayments/dodopayments-go" "github.com/dodopayments/dodopayments-go/option" ) func main() { client := dodopayments.NewClient( option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), ) _, err := client.Products.New(context.TODO(), dodopayments.ProductNewParams{ Name: dodopayments.F("Starter Plan"), TaxCategory: dodopayments.F(dodopayments.TaxCategorySaas), Price: dodopayments.F[dodopayments.PriceUnionParam]( dodopayments.PriceOneTimePriceParam{ Type: dodopayments.F(dodopayments.PriceOneTimePriceTypeOneTimePrice), Currency: dodopayments.F(dodopayments.CurrencyUsd), Price: dodopayments.F(int64(2000)), PurchasingPowerParity: dodopayments.F(true), }, ), }) if err != nil { panic(err) } } ``` > [!WARNING] > > The request fails with `422 ppp_not_enabled_for_business` if Adaptive Currency is off for your business. Turn it on first. > [card] [API Reference](/api-reference/products/post-products) > > See the full product create and update endpoints. ## Important Behaviors | Behavior | Detail | | :- | :- | | **Requires Adaptive Currency** | PPP does nothing while Adaptive Currency is off. | | **Off by default** | Every price starts at `purchasing_power_parity: false`. | | **Localized prices win** | A product with a matching [Localized Pricing](/features/localized-pricing) rule is never adjusted by PPP. The exact amount you set applies. | | **Applied before conversion** | The percentage applies to your base price. Adaptive Currency converts the result. | | **Before discounts** | A [discount code](/features/discount-codes) applies to the reduced price, so the two reductions combine. | | **Fixed fees only for usage-based** | PPP applies to the fixed fee of a usage-based product, never to metered usage. | | **Not for Pay What You Want** | The customer chooses the amount, so PPP does not apply. See [Pay What You Want](/features/pay-what-you-want). | | **Percentage range** | A country percentage is between 30 and 100. The largest reduction is 70%. | | **No webhook of its own** | The reduced amount appears on the payment or subscription like any other price. | ## Best Practices * **Opt in one product first.** Confirm the checkout price before you opt in your catalogue. * **Watch the discount stack.** A discount code applies on top of the PPP price. A 30% country plus a 20% code leaves 24% of your list price. * **Leave enterprise plans out.** A negotiated plan rarely needs a country adjustment. * **Set your own values where it matters.** The default numbers are a starting point, not a rule. * **Check the effect on subscriptions.** A subscriber who signs up at the reduced price renews at that price. *** ## Related > [card] [Adaptive Currency](/features/adaptive-currency) > > Required for PPP. Converts the reduced price to the customer's currency. > [card] [Charm Pricing](/features/charm-pricing) > > Round the converted price to a clean ending such as 49.99. Runs after PPP. > [card] [Localized Pricing](/features/localized-pricing) > > Set an exact price per country or currency. Overrides PPP. > [card] [Discount Codes](/features/discount-codes) > > Percentage and fixed-amount codes. They apply on top of the PPP price. # Abandoned Cart Recovery Source: https://docs.dodopayments.com/features/recovery/abandoned-cart-recovery Detect abandoned or failed checkouts automatically and send email sequences, with an optional discount, that bring customers back to complete the purchase. > [!NOTE] > > Abandoned Cart Recovery (ACR) detects checkouts that were abandoned or whose payment failed, and emails the customer a link to complete the purchase. You can add an automatic discount to each recovery. ## What Is Abandoned Cart Recovery? ACR identifies customers who started a checkout but didn't complete it, whether the payment failed or they left before paying, and sends them a sequence of recovery emails. It covers one-time purchases and the first payment of a new subscription, including a free trial. * **Failed payments**: The customer attempted payment, but it was declined or failed with an error. * **Incomplete checkouts**: The customer visited checkout but never attempted payment. ## How ACR Works **1. Detection** Dodo Payments looks for payments that are at least 60 minutes old and haven't succeeded. It skips payments that are still processing or were cancelled, payments without a customer email address, and one-time payments with a zero total. If the customer has made a newer successful payment, no abandoned checkout is recorded. **2. Classification** Each abandoned checkout is classified by reason: * **Payment Failed**: The customer attempted payment, but it failed. * **Checkout Incomplete**: The customer visited checkout but never attempted payment. **3. Email Sequence** Based on the classification, Dodo Payments sends up to 3 recovery emails at the delays you configure. Each email contains a unique recovery link and an unsubscribe link. The email also supports one-click unsubscribe (RFC 8058), so mail apps that support it can show their own unsubscribe button. **4. Recovery** When the customer clicks the recovery link, a checkout opens with their original cart. They complete payment in a fresh checkout session. ## Status Lifecycle Each abandoned checkout moves through these states: | Status | Description | | - | - | | `abandoned` | Checkout detected as abandoned, no emails sent yet | | `recovering` | At least one recovery email has been sent | | `recovered` | Customer completed payment through the recovery link | | `exhausted` | All emails were sent and seven days passed with no recovery, or a newer checkout superseded this one | | `opted_out` | Customer unsubscribed from recovery emails | ## Configuring ACR Turn on and configure ACR in **Settings → Recovery** in your dashboard. ![ACR settings page showing enable toggle, discount configuration, and email sequence editor](https://mintcdn.com/dodopayments/tvJ2MmXYymW0IZ3R/images/recovery/acr-settings.png?fit=max\&auto=format\&n=tvJ2MmXYymW0IZ3R\&q=85\&s=564184c25e7ec3e98f1ec07264ebba5d) Abandoned Cart Recovery settings in the dashboard ### Global Settings These settings apply to every abandoned checkout: | Setting | Description | Default | | - | - | - | | **Enable Abandoned Cart Recovery** | Master toggle for ACR | Off | | **Give customers a discount code** | Generate a discount code for each abandoned checkout and include it in the recovery emails | Off | | **Discount Percentage (%)** | Percentage discount applied to the recovery checkout for this customer | 10 | | **Valid for (days)** | How many days the generated discount code stays valid | 5 | ### Email Sequences ACR has two email sequences, **Payment Failed** and **Checkout Incomplete**, each with up to 3 emails. The dashboard lists them as **Emails sent to customer when payment fails** and **Emails sent to customer when checkout is incomplete**. ![Email sequence editor showing subject, body, timing, and enable toggle for each email in the sequence](https://mintcdn.com/dodopayments/tvJ2MmXYymW0IZ3R/images/recovery/acr-email-config.png?fit=max\&auto=format\&n=tvJ2MmXYymW0IZ3R\&q=85\&s=3f2bd0fbdf6b2b6bfe898c17bf2693a4) ACR email sequence configuration Each email has these settings: | Setting | Description | | - | - | | **Enable this email** | Turns the email on or off without deleting it | | **Send after** | How long after abandonment detection to send this email, in days and hours | | **Subject Line** | The email subject. It supports the placeholders listed after this table. | | **Email Body Text** | Plain text shown inside the standard recovery email layout, above the order summary. Line breaks are kept. HTML and placeholders are not rendered. | | **Reply-to email** | The address that receives customer replies. If you leave it empty, your store contact email is used. | In **Subject Line**, Dodo Payments replaces these placeholders: `{store_name}`, `{store_owner_name}`, `{store_contact_email}`, `{discount_code}`, `{recovery_link}`, and `{unsubscribe_link}`. Both sequences use the same default delays: | Email # | Default Delay | | - | - | | 1 | 1 hour | | 2 | 24 hours | | 3 | 72 hours | ### Example Recovery Emails ACR sends a different email for each abandonment reason. These examples show what the customer sees. > [tab] Payment Failed > > ![Recovery email for a failed payment showing store name, message about payment failure, order summary with product details, discount, and a Resume Checkout button](https://mintcdn.com/dodopayments/tvJ2MmXYymW0IZ3R/images/recovery/acr-failed-email.png?fit=max\&auto=format\&n=tvJ2MmXYymW0IZ3R\&q=85\&s=a8da91be6212c9fdd2b373572e3c1912) > > Recovery email sent when a payment attempt fails > [tab] Checkout Incomplete > > ![Recovery email for an incomplete checkout showing store name, message about saved cart, order summary with product details, discount, and a Resume Checkout button](https://mintcdn.com/dodopayments/tvJ2MmXYymW0IZ3R/images/recovery/acr-abandoned-email.png?fit=max\&auto=format\&n=tvJ2MmXYymW0IZ3R\&q=85\&s=05adcd350e1ceefa7854c86a37c862b9) > > Recovery email sent when a customer leaves without attempting payment ## Recovery Discounts When **Give customers a discount code** is on and the percentage is above 0, ACR generates a unique, single-use discount code for each abandoned checkout at detection. The codes start with `ACR-`. Each discount: * Is restricted to the products from the original checkout * Expires after the number of days in **Valid for (days)**, counted from detection * Is limited to one redemption * Is hidden from your dashboard discount list (internal use only) > [!TIP] > > Start with a modest discount (5-10%) and measure its effect on conversion before you increase it. ## Customer Recovery Experience When a customer clicks **Resume Checkout** in a recovery email, Dodo Payments opens a new checkout session with the same cart: the same products, add-ons, and quantities, and the amount the customer entered for a Pay What You Want product. If you turned on the discount, its code is already applied. If the customer opens the link again while that session is still valid, the same session reopens. ## Analytics Track ACR performance under **Analytics → Recovery** in your dashboard. ![Recovery analytics dashboard showing abandoned checkout counts, recovery rates, recovered revenue, average time to recover, and breakdowns by product and email](https://mintcdn.com/dodopayments/B3-0kuKcZDP1TiJD/images/recovery/recovery-analytics.png?fit=max\&auto=format\&n=B3-0kuKcZDP1TiJD\&q=85\&s=d3bf0c7474818bc4584b75654423e14c) Recovery analytics dashboard showing ACR and dunning metrics The Abandoned Cart Recovery section shows these metrics: | Metric | Description | | - | - | | **Abandoned checkouts** | Total number of detected abandoned checkouts | | **Recovery rate** | Percentage of abandoned checkouts that were recovered | | **Recovered revenue** | Total revenue recovered through ACR | | **Avg. time to recover** | Average time from abandonment to recovery | | **Recovery rate by email** | Breakdown of which email in the sequence drove the recovery | | **Recovery rate by product** | Which products have the highest recovery rates | ## Webhook Events ACR sends two webhook events: | Event | Description | | - | - | | `abandoned_checkout.detected` | An abandoned checkout has been detected and recovery has begun | | `abandoned_checkout.recovered` | A customer completed payment through the recovery flow | > [card] [Recovery Webhook Payloads](/developer-resources/webhooks/intents/recovery) > > View the full webhook payload schemas for ACR events. ## Edge Cases ACR handles these cases automatically: | Scenario | Behavior | | - | - | | Customer completes purchase before next email | A payment through the recovery link marks the checkout `recovered` when it succeeds. If the customer pays the original checkout instead, the next send check marks the checkout `exhausted`. | | Customer starts a new checkout | The old abandoned checkout is marked `exhausted` at the next send check | | Customer clicks **Resume Checkout** after the checkout is recovered | The link returns a message that the checkout has already been recovered, and no new checkout opens | | Customer unsubscribes | The abandoned checkout is marked `opted_out`, and no further emails are sent. An email already scheduled for that checkout is dropped. | ## Best Practices * **Start with defaults**: Every email comes with a default delay and subject. Customize them after you have baseline data. * **Personalize emails**: Use subject placeholders such as `{store_name}` and `{discount_code}` to make each email specific to the purchase. * **Monitor analytics**: Check **Recovery rate by email** to see which messages drive the most conversions, and turn off emails that recover little. * **Use discounts strategically**: Start small (5-10%) to protect margins while you test the effect on conversion. * **Keep emails concise**: Keep recovery emails short and focused on one action. The email layout already includes the **Resume Checkout** button. > [!NOTE] > > ACR runs automatically once you turn it on. Start with the default settings, watch your analytics, and adjust based on the results. ## Related > [card] [Recovery Webhooks](/developer-resources/webhooks/intents/recovery) > > React to `abandoned_checkout.detected` and `abandoned_checkout.recovered` events. > [card] [Subscription Dunning](/features/recovery/subscription-dunning) > > Recover lapsed subscriptions with automated dunning emails. > [card] [Customer Portal](/features/customer-portal) > > Where customers manage their subscriptions and payment methods. > [card] [Discounts](/features/discount-codes) > > How discount codes work, including the codes ACR generates. # Manual Payment Retry Source: https://docs.dodopayments.com/features/recovery/manual-retry Retry a failed subscription renewal payment on demand from the dashboard or the API instead of waiting for the next automatic retry. > [!NOTE] > > Manual Retry re-attempts a failed subscription **renewal** payment when you ask, from the payment's detail page or through the API. It charges the payment method saved on the subscription, and it runs independently of the automatic [Payment Retries](/features/recovery/payment-retries) schedule. ## What Is Manual Retry? When a renewal payment fails, the subscription moves to `on_hold`. If you turned on [Payment Retries](/features/recovery/payment-retries), they re-attempt the charge on your retry schedule. Sometimes you know the payment will go through now: the customer has confirmed they topped up their account, or your support team is on a call with them. Manual Retry sends one attempt immediately, instead of waiting hours or days for the next scheduled one. * **Renewal payments only**: Manual Retry applies to subscription renewal invoices while the subscription is `on_hold`. First payments, one-time payments, plan-change charges, and on-demand charges are not eligible. * **No customer action**: The charge goes to the payment method already saved on the subscription. * **Independent of automatic retries**: A manual retry doesn't use up an attempt from the automatic schedule, doesn't move the next scheduled retry, and works even when Payment Retries are off. * **Retries the invoice, not the payment**: The failed payment is only the entry point. Dodo Payments finds the open renewal invoice behind it and charges that debt, so it doesn't matter which failed payment on the invoice you retry from. ## Retrying from the Dashboard Only team members whose role has **Write** access to **Payments** can send a manual retry, for example the Owner or the Admin role. See [Team Members](/features/team). **1. Open the failed payment** Go to **Transactions → Payments** and click the failed renewal payment to open its **Transaction details** page. **2. Click Retry Payment Manually** Click **Retry Payment Manually** in the top-right corner. The button is available only while the payment is [eligible](#eligibility). **3. Check the result** Dodo Payments creates a new payment for the attempt, and it appears in the **Activity Log**. If the charge succeeds, the subscription returns to `active`, and the next billing date moves to one billing period after the successful retry. If the payment processor hasn't settled the charge yet, the payment shows as in progress until the `payment.succeeded` or `payment.failed` webhook reports the outcome. ![Transaction details page for a failed payment showing the error code and message, an Activity Log, and a Retry Payment Manually button](https://mintcdn.com/dodopayments/0duTS18kYi2NwQ3m/images/recovery/manual-retry-transaction-details.png?fit=max\&auto=format\&n=0duTS18kYi2NwQ3m\&q=85\&s=5537fa5eff17cbe91a53599f887a26e7) Retry Payment Manually on the transaction details page of a failed renewal ## Eligibility Dodo Payments sends a manual retry only when every check in this table passes. The **Reason code** column is what the API returns: in `reason` on `GET /payments/{payment_id}/retry`, and as the error `code` on `POST /payments/{payment_id}/retry`. | Check | Requirement | Reason code | | - | - | - | | Payment type | A subscription **renewal** payment whose invoice is still open. Payments with no invoice, first payments, one-time payments, plan-change charges, and on-demand charges cannot be retried. | `PAYMENT_NOT_RETRYABLE` | | Subscription status | `on_hold` | `SUBSCRIPTION_INACTIVE` | | Scheduled cancellation | The subscription is not scheduled to cancel at the next billing date. | `CHARGE_NOT_ALLOWED_FOR_SCHEDULED_CANCELLATION` | | Saved payment method | The subscription has a saved payment method to charge. | `SUBSCRIPTION_HAS_NO_PAYMENT_METHOD` | | Last failure | The most recent failure is a **soft decline**. A hard decline, or a failure with no classified error code, cannot be retried. | `MANUAL_RETRY_HARD_DECLINE` | | Nothing in flight | No payment on the invoice is `processing` or still has no recorded status. Such a payment is an attempt, manual or automatic, that was just sent and hasn't reported back. Wait for its outcome first. | `MANUAL_RETRY_IN_FLIGHT` | | Newest payment failed | The most recent payment on the invoice has `failed` status. Any other status, such as `requires_customer_action`, `requires_payment_method`, or `cancelled`, blocks the retry even when nothing is in flight. A cancelled update-payment-method payment does not count. Dodo Payments cancels an unpaid update-payment-method link on an `on_hold` or `past_due` subscription after 24 hours, so an abandoned link stops blocking the retry. | `PREVIOUS_PAYMENT_PENDING` | | Not already paid | No payment on the invoice has succeeded. | `MANUAL_RETRY_ALREADY_PAID` | | Retry limit | Fewer than 3 manual retries were sent on the invoice, and the cooldown has passed. See [Retry Limits](#retry-limits). | `MANUAL_RETRY_LIMIT_REACHED` | | Customer | The customer is not on your [blocklist](/features/customer-blocklist). | `PAYMENT_NOT_RETRYABLE` | | Payment connector | For [BYOP](/features/byop) subscriptions, the connector is enabled. | `BYOP_CONNECTOR_DISABLED` | | Live mode | In live mode, your business has live payments enabled. | `MERCHANT_NOT_LIVE` | > [!NOTE] > > Manual Retry is narrower than automatic retries in one place: it requires the subscription to be `on_hold`. A `past_due` subscription in a grace period fails this check. Automatic retries keep running for other non-active statuses. See [Subscription Status Transitions](/features/recovery/payment-retries#subscription-status-transitions). > [!WARNING] > > Retrying a hard decline against the same card can't succeed, and repeated declines hurt your authorization rate. When the reason is `MANUAL_RETRY_HARD_DECLINE`, ask the customer to update their payment method instead. [Subscription Dunning](/features/recovery/subscription-dunning) does this automatically. ## Retry Limits Each renewal invoice allows **3** manual retries, with a cooldown between them: | Manual retry | Available | | - | - | | 1 | As soon as the payment is eligible | | 2 | 1 hour after the first | | 3 | 3 hours after the second | The limits apply in both test mode and live mode. When the limit refuses a retry, the API returns `MANUAL_RETRY_LIMIT_REACHED` (HTTP `429`), and the error body carries only `code` and `message`. To learn when the next retry opens, [check the retry state](#check-whether-a-payment-can-be-retried) and read `retry_available_at`. It is `null` once all three retries are spent. Automatic retries don't count toward this limit, and manual retries don't count toward the attempts of the automatic schedule. ## Customer Retries from the Portal Your customers can retry a failed renewal themselves. In the [Customer Portal](/features/customer-portal#retrying-a-failed-payment), a subscription with a failed renewal shows a **Retry Payment** button. It charges the open renewal invoice again with the saved payment method, using the same engine as a manual retry from your dashboard. A customer retry differs from yours in these ways: | | Your manual retry | Customer retry from the portal | | - | - | - | | **Needs Payment Retries enabled** | No | Yes. When [Payment Retries](/features/recovery/payment-retries) are off, the portal doesn't offer the retry. | | **Subscription status** | `on_hold` | `on_hold` or `past_due` | | **Retry limit** | 3 per invoice, with a 1-hour and then a 3-hour cooldown | The same 3 retries, shared with your manual retries | | **Blocked customers** | Not allowed | Not allowed. A [blocked customer's](/features/customer-blocklist) portal is read-only. | Because the limit is shared, a retry the customer sends uses one of the three manual retries on the invoice. When the customer can't retry, for example after a hard decline, the portal asks them to update their payment method instead. ## Manual vs. Automatic Retries The two retry paths differ in these ways: | | Manual Retry | Payment Retries | | - | - | - | | **Trigger** | You, from the dashboard or the API, or your customer from the Customer Portal | Dodo Payments, on your retry schedule | | **Timing** | Immediately | After each wait of your [retry schedule](/features/recovery/payment-retries#retry-schedule), counted from the previous failure | | **Attempts** | 3 per invoice, with a 1-hour and then a 3-hour cooldown | Up to 8 per invoice, as your retry schedule allows | | **Needs Payment Retries enabled** | No | Yes | | **Effect on the other** | None. A manual failure doesn't schedule or move an automatic attempt. | None. The automatic chain continues regardless of manual sends. | | **Analytics** | Counted in the **Payment Retries** metrics under **Analytics → Recovery** | Counted in the same metrics | ## Retrying via the API Check eligibility first, then send the retry. Both endpoints take the ID of a failed payment. ### Check Whether a Payment Can Be Retried `GET /payments/{payment_id}/retry` doesn't return an error for an ineligible payment. It returns `can_retry: false` with the `reason` code instead, so your own dashboard or support tooling can show the same state as the Dodo Payments dashboard. It requires read access to Payments (`payments:read`). ```typescript Node.js theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); const state = await client.payments.retrieveRetryState('pay_0NmDtkE0iRvmeTcT6t0ol'); if (state.can_retry) { console.log(`Retry available. ${state.sends_used}/${state.sends_allowed} used.`); } else { console.log(`Cannot retry: ${state.reason}. Next window: ${state.retry_available_at}`); } ``` ```python Python theme={null} import os from dodopayments import DodoPayments client = DodoPayments(bearer_token=os.environ["DODO_PAYMENTS_API_KEY"]) state = client.payments.retrieve_retry_state("pay_0NmDtkE0iRvmeTcT6t0ol") if state.can_retry: print(f"Retry available. {state.sends_used}/{state.sends_allowed} used.") else: print(f"Cannot retry: {state.reason}. Next window: {state.retry_available_at}") ``` ```bash cURL theme={null} curl https://live.dodopayments.com/payments/pay_0NmDtkE0iRvmeTcT6t0ol/retry \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" ``` ```json Response theme={null} { "can_retry": false, "reason": "MANUAL_RETRY_LIMIT_REACHED", "sends_used": 1, "sends_allowed": 3, "retry_available_at": "2026-08-26T16:51:00Z", "next_automatic_retry_at": "2026-08-27T03:51:00Z", "automatic_retry_number": 2, "automatic_retry_total": 5 } ``` | Field | Description | | - | - | | `can_retry` | `true` when a retry would be sent right now. | | `reason` | The code the retry would fail with. `null` when `can_retry` is `true`. | | `sends_used` | Manual retries already sent on this invoice. | | `sends_allowed` | Always `3`. | | `retry_available_at` | When the next manual retry opens. `null` when no retry is left, or when the refusal has nothing to do with the cooldown. | | `next_automatic_retry_at` | When the next [automatic retry](/features/recovery/payment-retries) on this invoice is scheduled. | | `automatic_retry_number` | The number of the queued automatic retry, starting at `1`. | | `automatic_retry_total` | The number of automatic retries that your current [retry schedule](/features/recovery/payment-retries#retry-schedule) plans for this invoice. With the **Standard** schedule, it depends on your recovery window. It is never less than `automatic_retry_number`, even after you shorten the schedule. | The three automatic retry fields are `null` together when no automatic retry is queued for the invoice. They are also `null` when Payment Retries are off, when the invoice is no longer open or is not a subscription renewal, and when the most recent failure is a hard decline or has no error code. The dashboard shows the same values on the payment's **Transaction details** page, as **Next automatic retry**. ### Send a Manual Retry `POST /payments/{payment_id}/retry` creates a new payment and charges the saved payment method. It requires write access to Payments (`payments:write`). The SDK examples reuse the `client` from the previous example. ```typescript Node.js theme={null} // `client` is the DodoPayments instance from the previous example. const retry = await client.payments.retry('pay_0NmDtkE0iRvmeTcT6t0ol'); console.log(retry.payment_id, retry.status); ``` ```python Python theme={null} # `client` is the DodoPayments instance from the previous example. retry = client.payments.retry("pay_0NmDtkE0iRvmeTcT6t0ol") print(retry.payment_id, retry.status) ``` ```bash cURL theme={null} curl -X POST https://live.dodopayments.com/payments/pay_0NmDtkE0iRvmeTcT6t0ol/retry \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" ``` ```json Response theme={null} { "payment_id": "pay_2IjeQm4hqU6RA4Z4kwDee", "invoice_id": "inv_9Kp2mQ7vRt4LxYw3", "status": "processing", "retry_attempt": 1, "is_manual_retry": true, "sends_used": 1, "sends_allowed": 3, "retry_available_at": "2026-08-26T16:51:00Z" } ``` | Field | Description | | - | - | | `payment_id` | The new payment created for this attempt. | | `invoice_id` | The renewal invoice that was charged. | | `status` | Outcome of the charge. `processing` means the processor hasn't settled it yet. `null` means no outcome was recorded before the response was returned. In both cases the payment webhooks report the final result. | | `retry_attempt` | Position of this attempt among the manual retries on the invoice, starting at `1`. | | `is_manual_retry` | Always `true` on this endpoint. | | `sends_used`, `sends_allowed`, `retry_available_at` | Retry limit state after this send. `retry_available_at` is the cooldown clock only. It is set even when this charge succeeds, in which case the invoice is paid and no further retry opens. | ### Error Responses When a retry is not allowed, `POST` returns one of these HTTP statuses: | HTTP status | Codes | What to do | | - | - | - | | `404` | `NOT_FOUND` | The payment doesn't belong to your business. | | `409` | `MANUAL_RETRY_IN_FLIGHT`, `PREVIOUS_PAYMENT_PENDING`, `CHARGE_NOT_ALLOWED_FOR_SCHEDULED_CANCELLATION` | The block is temporary, or something else must change first. Wait for the in-flight or pending payment to reach a final state, or clear the scheduled cancellation. | | `422` | `PAYMENT_NOT_RETRYABLE`, `SUBSCRIPTION_INACTIVE`, `SUBSCRIPTION_HAS_NO_PAYMENT_METHOD`, `MANUAL_RETRY_HARD_DECLINE`, `MANUAL_RETRY_ALREADY_PAID`, `BYOP_CONNECTOR_DISABLED`, `MERCHANT_NOT_LIVE` | This payment can't be retried. Don't repeat the call. | | `429` | `MANUAL_RETRY_LIMIT_REACHED` | [Check the retry state](#check-whether-a-payment-can-be-retried) and wait until its `retry_available_at`, or stop once all three retries are spent. | The [Error Codes](/api-reference/error-codes) reference describes every code. ## Webhooks A manual retry creates an ordinary payment, so the same webhooks fire as for any renewal attempt: | Event | Fires when | | - | - | | `payment.succeeded` | The retry was charged. `subscription.active` follows when the subscription is reactivated. | | `payment.failed` | The retry was declined. The subscription stays `on_hold`, and a manual failure doesn't schedule an automatic retry. | | `payment.processing` | The processor has accepted the charge but hasn't settled it yet. | On the payment object in these events, `retry_attempt` is `1` or higher and `subscription_id` is set, the same as for an automatic retry. The payment object has no field that marks a manual attempt, so keep the `payment_id` from the retry response if you need to tell a manual attempt apart from a scheduled one. > [card] [Payment Webhook Payloads](/developer-resources/webhooks/intents/payment) > > Full payload schemas for payment events. ## Related > [card] [Subscription Payment Retries](/features/recovery/payment-retries) > > The automatic retry schedule that runs alongside manual retries. > [card] [Subscription Dunning](/features/recovery/subscription-dunning) > > Email the customer to update their payment method after a hard decline. > [card] [Handle Payment Failures](/developer-resources/handle-payment-failures) > > Read decline codes and decide when a retry is worthwhile. > [card] [Error Codes](/api-reference/error-codes) > > Every `MANUAL_RETRY_*` code, its trigger, and its message. # Revenue Recovery Source: https://docs.dodopayments.com/features/recovery/overview Recover revenue lost to failed payments and abandoned checkouts with Dodo Payments' automatic retries, dunning emails, and abandoned cart recovery. > [!NOTE] > > Dodo Payments recovers revenue from failed subscription renewals and abandoned checkouts with three automatic tools, plus a manual retry that you send when you choose. The automatic tools need no integration work. Each one is off by default, and you turn it on in **Settings → Recovery**. ## Recovery Tools > [card] [Subscription Payment Retries](/features/recovery/payment-retries) > > Re-charge failed subscription renewals on the standard schedule or on waits you choose, with no customer action. > [card] [Manual Payment Retry](/features/recovery/manual-retry) > > Re-attempt a failed renewal immediately from the dashboard or the API. > [card] [Subscription Dunning](/features/recovery/subscription-dunning) > > Email customers to update their payment method when a renewal fails, or to re-purchase when they cancel. > [card] [Abandoned Cart Recovery](/features/recovery/abandoned-cart-recovery) > > Email customers who abandon a checkout, or whose checkout payment fails, to bring them back. ## Which Tool Recovers What Each tool covers a different failure. Find the scenario in the first column: | Scenario | Recovery tool | How it recovers | | - | - | - | | Subscription **renewal** fails on a **soft decline** (insufficient funds, network error) | [Payment Retries](/features/recovery/payment-retries) | Re-charges the saved payment method on your retry schedule | | Subscription **renewal** fails and you want to re-attempt **right now** (for example, the customer confirms they added funds) | [Manual Retry](/features/recovery/manual-retry) | Charges the saved payment method once, when you ask, independent of the automatic schedule | | Subscription **renewal** fails on a **hard decline** (expired or invalid card) | [Subscription Dunning](/features/recovery/subscription-dunning) | Emails the customer to update their payment method | | Customer **cancels** a subscription from the Customer Portal | [Subscription Dunning](/features/recovery/subscription-dunning) | Emails the customer to re-purchase | | Checkout for a **one-time purchase** or a **new subscription** fails or is abandoned | [Abandoned Cart Recovery](/features/recovery/abandoned-cart-recovery) | Emails the customer to complete the purchase | ## How They Work Together For subscriptions, **Payment Retries** and **Dunning** run side by side. When a renewal fails, retries re-charge the saved payment method in the background while dunning emails ask the customer to update it. Retries recover soft declines with no customer action. Dunning recovers the payments that need a new payment method, such as hard declines. When either one settles the renewal, the subscription returns to `active` and the other stops. Turn on both to cover both kinds of failure. To read failure codes and decide when a retry is worthwhile, see [Handle Payment Failures](/developer-resources/handle-payment-failures). ## Analytics Track recovery performance under **Analytics → Recovery** in your dashboard. The tab shows recovered revenue and the recovery rate, with separate metrics for payment retries, dunning, and abandoned cart recovery. See [Analytics & Reporting](/features/analytics-and-reporting) for every metric. ## Related > [card] [Handle Payment Failures](/developer-resources/handle-payment-failures) > > Read failure codes and decide when to retry. > [card] [Subscriptions](/features/subscription) > > The subscription states that recovery flows move between. > [card] [Recovery Webhooks](/developer-resources/webhooks/intents/recovery) > > React to dunning and abandoned checkout events. > [card] [Customer Portal](/features/customer-portal) > > Where customers update their payment method to recover a subscription. # Subscription Payment Retries Source: https://docs.dodopayments.com/features/recovery/payment-retries Retry failed subscription renewal payments automatically on the standard schedule or on waits you choose, and recover revenue with no integration work. > [!NOTE] > > Payment Retries re-charge failed subscription **renewal** payments automatically, on the standard schedule or on waits you choose. When a retry succeeds, the subscription returns to `active`, with no customer action and no integration work. ## What Are Payment Retries? When a subscription renewal payment fails, the subscription moves to `on_hold`, or to `past_due` if you set a [grace period](/features/subscription#grace-period). With Payment Retries on, Dodo Payments re-charges the customer's saved payment method on a schedule until a charge succeeds or the schedule runs out. Retries recover revenue lost to temporary failures, such as a temporary hold on the card, insufficient funds that the customer tops up later, or a transient network error. The customer gets no email and doesn't need to change anything. > [!NOTE] > > Payment Retries apply only to subscription **renewal** payments. The first payment of a subscription (mandate setup), one-time payments, plan-change charges, and on-demand charges are not retried. ## How Payment Retries Work **1. Renewal fails** A subscription renewal payment fails, and the subscription moves to `on_hold`, or to `past_due` during a grace period. **2. Retryability check** Dodo Payments checks the failure's error code. **Soft declines**, such as insufficient funds, a generic decline, or a processing or network error, are retryable. **Hard declines** end the retry chain, because another attempt won't change the outcome. A failure without an error code counts as a hard decline. **3. Scheduled retry** If the decline is retryable and your [retry schedule](#retry-schedule) has another attempt left, Dodo Payments schedules it. Each retry is an off-session charge to the customer's saved payment method, and each wait counts from the previous failure. **4. Recovery** On the first successful retry, the subscription returns to `active`, and the next billing date moves to one billing period after the successful retry. If the schedule runs out before any retry succeeds, retries stop and the subscription keeps its status, such as `on_hold`. ## Configuring Payment Retries Turn on and configure Payment Retries in **Settings → Recovery** in your dashboard. ![Payment retries section of the Recovery settings with the toggle on, Standard selected under Retry schedule, a Recovery window of 13 days, and the expanded schedule table marking the 6th to 8th retries as Skipped](https://mintcdn.com/dodopayments/UMiQC1uqTiTBQuTJ/images/recovery/payment-retries-settings.png?fit=max\&auto=format\&n=UMiQC1uqTiTBQuTJ\&q=85\&s=106906478520e0521651ebc4ffefbf24) Payment Retries settings under Settings → Recovery The page has these settings: | Setting | Description | Default | | - | - | - | | **Payment retries** | Automatically retry failed subscription renewal payments to recover revenue. | Off | | **Retry schedule** | **Standard** uses the schedule Dodo Payments recommends, limited to your recovery window. **Custom** lets you choose the wait before each retry. See [Retry Schedule](#retry-schedule). | Standard | | **Recovery window** | Shown for the **Standard** schedule only. Standard retries that fall after this window are skipped. From **1** to **30** days. | 13 days | The **Payment retries** toggle saves as soon as you switch it. The **Retry schedule** settings appear only while the toggle is on, and changes to them take effect when you click **Save**. The recovery window starts when the invoice for the failed renewal is created. With the **Standard** schedule, Dodo Payments schedules an attempt only if the sum of all waits up to that attempt fits inside the window, and only while the window is still open. ### Changing the Schedule During a Retry Chain Dodo Payments reads your settings each time it schedules the next retry, so a change also applies to payments that are already being retried: * A retry that is already queued keeps its time. Your new settings decide the wait before the retry after it. * When you switch between **Standard** and **Custom**, the chain continues at the same retry number. For example, if the 3rd retry fails after the switch, the next one is the 4th retry of the new schedule. * If the new schedule has no retry with that number, the chain ends. This happens when you switch to a **Custom** schedule with fewer retries, or when you remove custom retries. * When you switch to **Standard**, the recovery window applies again. If the next retry doesn't fit in the window, or the window has already closed, the chain ends. ## Retry Schedule Choose the schedule under **Retry schedule** on the same settings page. In both modes, Dodo Payments does not retry a hard decline. To see when the next automatic retry runs for a failed payment, open the payment's **Transaction details** page. It shows **Next automatic retry** with the date and the retry number, for example Retry 2 of 5. The total counts the retries that your current schedule plans for the invoice, so it changes when you change the schedule. ### Standard Schedule Retries back off progressively. Dodo Payments makes up to **8 attempts**, as long as each one fits in your recovery window. The settings page shows how many retries fit in your window. Click **View schedule** to see each retry, with the ones outside the window marked **Skipped**: | Attempt | Wait after previous attempt | Approx. time since failure | | - | - | - | | 1 | 12 hours | 12 hours | | 2 | 24 hours | 36 hours | | 3 | 48 hours | \~3.5 days | | 4 | 72 hours | \~6.5 days | | 5 | 96 hours | \~10.5 days | | 6 | 120 hours | \~15.5 days | | 7 | 7 days | \~22.5 days | | 8 | 7 days | \~29.5 days | > [!TIP] > > The default window of **13 days** covers attempts 1 through 5, because attempt 5 fires about 10.5 days after the failure. To run the later, more widely spaced attempts, increase the window: attempt 6 needs at least 16 days, attempt 7 at least 23 days, and attempt 8 the 30-day maximum. ### Custom Schedule Select **Custom** to set your own waits. Each row is one retry, and its wait counts from the previous attempt. The first time you select **Custom**, the rows are 12 hours, 1 day, and 2 days. The rules are: * Add **1** to **8** retries. Click **Add retry** to add a row with the longest wait that still fits. The button is hidden at 8 retries, or when less than 12 hours of the 30 days are left. * To remove a retry, click **×** next to its row. The other rows renumber. The last row can't be removed. * Each wait is **12 hours**, or **1**, **2**, **3**, **4**, **5**, or **7 days**. * The waits must add up to **30 days** or less. Options that would push the total past 30 days are disabled. Below the rows, the settings page shows how many retries the schedule makes and when the last one runs, counted from the failed payment. ![Payment retries section of the Recovery settings with Custom selected under Retry schedule, three retry rows with wait menus, an Add retry button, and the note on when the last retry runs](https://mintcdn.com/dodopayments/UMiQC1uqTiTBQuTJ/images/recovery/payment-retries-custom-schedule.png?fit=max\&auto=format\&n=UMiQC1uqTiTBQuTJ\&q=85\&s=69a6a5efe560568ecea46c96366e64b6) A custom retry schedule under Settings → Recovery The recovery window doesn't apply to a custom schedule. Because the waits add up to 30 days or less, all retries of a custom schedule run within 30 days of the failed payment. In addition, once 30 days have passed since the invoice for the failed renewal was created, Dodo Payments queues no new retry. Dodo Payments checks the 30-day limit when it queues a retry, not when the retry runs. A retry can therefore run after day 30 in two cases: you change the schedule while a payment is being retried, or the result of a retry arrives late. For example, the 5th retry of the **Standard** schedule fails at about day 10.5. You then switch to a **Custom** schedule whose 6th, 7th, and 8th waits are 7 days each. These retries run at about day 17.5, 24.5, and 31.5. The 8th retry is queued at day 24.5, before the limit, so it still runs. ## Subscription Status Transitions Retries move the subscription between these statuses: | Event | Subscription status | | - | - | | Renewal payment fails | `active` → `on_hold`, or `active` → `past_due` during a grace period | | Retry attempt fails | Unchanged. The next retry is scheduled if the schedule has one left. | | Retry attempt succeeds | `on_hold` or `past_due` → `active`, and the next billing date moves | | Retry schedule exhausted | Unchanged, for example `on_hold` | | Subscription cancelled | Scheduled retries stop, and no further attempts are made | > [!NOTE] > > When a subscription is cancelled, its retry chain ends and no further attempts are made. Every other status (`on_hold`, `past_due`, `expired`, `pending`, `failed`) keeps retrying, because the open renewal invoice is a debt for a period the customer already used. Retries also stop when the invoice is paid another way, for example after the customer updates their payment method, or when you add the customer to your [blocklist](/features/customer-blocklist). These transitions emit the standard subscription webhook events, so your entitlement logic needs no retry-specific handling: | Event | Fires when | | - | - | | `subscription.on_hold` | A renewal fails and the subscription is placed on hold | | `subscription.past_due` | A renewal fails while a grace period applies | | `subscription.active` | A retry succeeds and the subscription is reactivated | > [card] [Subscription Webhook Payloads](/developer-resources/webhooks/intents/subscription) > > View the full webhook payload schemas for subscription lifecycle events. ## Retryable vs. Non-Retryable Failures The error code of the most recent failure decides whether the chain continues: | Failure type | Examples | Retried? | | - | - | - | | **Soft decline** | Insufficient funds, generic decline, do not honor, transaction not allowed, card velocity exceeded, processing error, network error or timeout, try again later | Yes | | **Hard decline** | Stolen or lost card, invalid card, account closed, a recurring payment the cardholder didn't approve, and other terminal declines | No. The chain ends immediately. | > [!NOTE] > > Retrying a hard decline won't change the outcome, so the chain ends as soon as a hard decline occurs. Pair Payment Retries with [Subscription Dunning](/features/recovery/subscription-dunning) to ask the customer for a new payment method in those cases. For the type of every code, see [Transaction Failures](/api-reference/transaction-failures). ## Retrying on Demand You don't have to wait for the next scheduled attempt. While a subscription is `on_hold`, you can send a retry from the failed payment's detail page in the dashboard, or with `POST /payments/{payment_id}/retry`. Manual retries run independently of the schedule: they don't use up or move an automatic attempt, and they work even when Payment Retries are off. See [Manual Payment Retry](/features/recovery/manual-retry). When Payment Retries are on, your customers can also retry a failed renewal themselves with **Retry Payment** in the [Customer Portal](/features/customer-portal#retrying-a-failed-payment), while the subscription is `on_hold` or `past_due`. See [Customer Retries from the Portal](/features/recovery/manual-retry#customer-retries-from-the-portal). ## Payment Retries vs. Dunning Payment Retries and [Subscription Dunning](/features/recovery/subscription-dunning) recover different kinds of failure: | | Payment Retries | Subscription Dunning | | - | - | - | | **Mechanism** | Re-charges the saved payment method, with no email | Emails the customer to update their payment method | | **Customer action** | None required | Customer updates the payment method in the Customer Portal | | **Best for** | Temporary or soft declines that resolve on their own | Expired or invalid cards that need replacing | Turn on both for the widest coverage: automatic retries catch transient failures, and dunning brings back customers whose payment method needs replacing. ## Related > [card] [Manual Payment Retry](/features/recovery/manual-retry) > > Send a retry right away instead of waiting for the next scheduled attempt. > [card] [Subscription Dunning](/features/recovery/subscription-dunning) > > Email sequences that ask customers to update their payment method. > [card] [Abandoned Cart Recovery](/features/recovery/abandoned-cart-recovery) > > Recover abandoned or failed checkouts with recovery emails. > [card] [Subscriptions](/features/subscription) > > The subscription states that recovery flows move between. > [card] [Subscription Webhooks](/developer-resources/webhooks/intents/subscription) > > React to `subscription.on_hold` and `subscription.active` events. # Subscription Dunning Source: https://docs.dodopayments.com/features/recovery/subscription-dunning Send email sequences automatically to recover lapsed or cancelled subscriptions, and prompt customers to update their payment method or re-purchase. > [!NOTE] > > Subscription Dunning emails customers whose subscription lapsed after a failed payment, or who cancelled it, and asks them to update their payment method or re-purchase. It runs automatically once you turn it on. ## What Is Subscription Dunning? Dunning detects when a subscription enters a recoverable state and sends a sequence of emails that ask the customer to act. Three states start a sequence: * **On Hold subscriptions**: A renewal payment failed, for example because of insufficient funds or an expired card. * **Past Due subscriptions**: A renewal payment failed while a [grace period](/features/subscription#grace-period) is open. * **Cancelled subscriptions**: The customer cancelled from the Customer Portal. ## How Dunning Works **1. Trigger** A subscription enters one of the three states: * **On Hold**: A renewal payment failed. * **Past Due**: A renewal payment failed while a [grace period](/features/subscription#grace-period) is open. * **Cancelled**: The customer cancelled their subscription from the Customer Portal. Dodo Payments then creates a dunning attempt and sends the `dunning.started` webhook. No attempt starts when the matching sequence has no enabled emails, and a subscription has at most one active attempt at a time. **2. Grace Period** If you set a [grace period](/features/subscription#grace-period), a failed renewal moves the subscription to `past_due` instead of `on_hold`. The on-hold email sequence runs during that window, so the customer is asked to pay while they still have access. One failed payment starts one sequence. The end of the window doesn't start a second sequence. If the window ends with the subscription on hold, the remaining emails in the sequence still go out. If it ends with the subscription cancelled, the attempt is marked `exhausted`. The dunning attempt records a `past_due` trigger state. When you read dunning analytics, filter on `past_due` as well as on `on_hold`. **3. Email Sequence** Based on the trigger state, Dodo Payments sends up to 4 dunning emails at the delays you configure. Each email links to the Customer Portal, where the customer can update their payment method, or to a checkout where they can re-purchase a cancelled subscription. **4. Recovery** When the customer updates their payment method in the Customer Portal, Dodo Payments automatically charges the remaining dues. If the payment succeeds, the subscription is reactivated and the dunning attempt is marked `recovered`. ## Status Lifecycle Each dunning attempt has one of these statuses: | Status | Description | | - | - | | `recovering` | The dunning attempt is active, and emails are being sent | | `recovered` | The customer updated their payment method or re-purchased, and the payment succeeded | | `exhausted` | All emails were sent and seven days passed with no recovery, or the subscription state changed unexpectedly | > [!NOTE] > > When a dunning attempt is marked `exhausted`, Dodo Payments doesn't change the subscription. It stays in its current state (past due, on hold, or cancelled). ## Configuring Dunning Turn on and configure Dunning in **Settings → Recovery** in your dashboard. Dunning is off by default. ![Dunning settings page with enable toggle, four on-hold emails at 1, 3, 5, and 7 day intervals, and four cancelled emails at the same intervals](https://mintcdn.com/dodopayments/tvJ2MmXYymW0IZ3R/images/recovery/dunning-settings.png?fit=max\&auto=format\&n=tvJ2MmXYymW0IZ3R\&q=85\&s=7389a9413d6008800e7ca8a5c4cd1ee5) Dunning settings in the dashboard showing enable toggle, on-hold sequence, and cancelled sequence ### Email Sequences Dunning has two email sequences, **On Hold** and **Cancelled**, each with up to 4 emails. The dashboard lists them as **Emails sent to customer when subscription is on hold** and **Emails sent to customer when subscription is cancelled**. A `past_due` attempt uses the On Hold sequence. Each email has these settings: | Setting | Description | | - | - | | **Enable this email** | Turns the email on or off without deleting it | | **Send after** | How long after dunning starts to send this email, in days and hours | | **Subject Line** | The email subject. It supports the placeholders listed after this table. | | **Email Body Text** | Plain text shown inside the standard dunning email layout. Line breaks are kept. HTML and placeholders are not rendered. | | **Reply-to email** | The address that receives customer replies. If you leave it empty, your store contact email is used. | In **Subject Line**, Dodo Payments replaces these placeholders: `{store_name}`, `{store_owner_name}`, `{store_contact_email}`, `{subscription_id}`, `{failure_reason}`, and `{payment_form_link}`. The default delays are: | Sequence | Email # | Default Delay | | - | - | - | | On Hold | 1 | 1 day | | On Hold | 2 | 3 days | | On Hold | 3 | 5 days | | On Hold | 4 | 7 days | | Cancelled | 1 | 1 day | | Cancelled | 2 | 3 days | | Cancelled | 3 | 5 days | | Cancelled | 4 | 7 days | ### Example Dunning Emails Dunning sends a different email for each subscription state. These examples show what the customer sees. > [tab] On Hold > > ![Dunning email for an on-hold subscription showing store name, message about failed payment, subscription details with plan and amount, and an Update Payment Method button](https://mintcdn.com/dodopayments/tvJ2MmXYymW0IZ3R/images/recovery/dunning-on-hold-email.png?fit=max\&auto=format\&n=tvJ2MmXYymW0IZ3R\&q=85\&s=5e46040ed49a4da84569afdeeb87c813) > > Dunning email sent when a renewal payment fails and the subscription is on hold > [tab] Cancelled > > ![Dunning email for a cancelled subscription showing store name, message about cancellation, subscription details with plan and amount, and a Re-purchase Subscription button](https://mintcdn.com/dodopayments/tvJ2MmXYymW0IZ3R/images/recovery/dunning-cancelled-email.png?fit=max\&auto=format\&n=tvJ2MmXYymW0IZ3R\&q=85\&s=f404fbf9415df4e4bd01562a90bd2456) > > Dunning email sent when a customer cancels their subscription ## Customer Recovery Experience When a customer clicks the link in an on-hold dunning email, the Customer Portal opens on their subscription. There they can see the subscription status and update their payment method. ![Customer portal showing an on-hold subscription for Pro Plan at \$95.00/year with an Update payment method button and a warning banner about the failed payment](https://mintcdn.com/dodopayments/tvJ2MmXYymW0IZ3R/images/recovery/customer-recovery-page.png?fit=max\&auto=format\&n=tvJ2MmXYymW0IZ3R\&q=85\&s=f498d3654afd3d70447b7b8ce7bf3767) Customer portal showing an on-hold subscription with option to update payment method After the customer updates their payment method, Dodo Payments charges any outstanding dues. If the payment succeeds, the subscription returns to `active`. For a cancelled subscription, the link opens a checkout page with the subscription's product already in the cart. If the customer cannot pay the renewal price, you can move the `on_hold` subscription to a cheaper plan through the API. Dodo Payments voids the unpaid renewal invoice and charges the new plan to the saved payment method. Payment retries and dunning continue on the new invoice if that charge fails. See [Change Plan on an On-Hold Subscription](/developer-resources/subscription-upgrade-downgrade#change-plan-on-an-on-hold-subscription). ## Analytics Track Dunning performance under **Analytics → Recovery** in your dashboard. ![Recovery analytics dashboard showing dunning entry counts, success rates, recovered revenue, and per-email performance breakdown](https://mintcdn.com/dodopayments/B3-0kuKcZDP1TiJD/images/recovery/recovery-analytics.png?fit=max\&auto=format\&n=B3-0kuKcZDP1TiJD\&q=85\&s=d3bf0c7474818bc4584b75654423e14c) Recovery analytics dashboard showing ACR and dunning metrics The Dunning section shows these metrics: | Metric | Description | | - | - | | **Dunning entries** | Total number of dunning attempts created | | **Recovery rate** | Percentage of dunning attempts that led to recovery | | **Recovered revenue** | Total revenue recovered through dunning | | **Emails sent** | Total number of dunning emails sent | | **Avg. time to recover** | Average time from the start of dunning to recovery | | **Recovery rate by email** | Breakdown of which email in the sequence drove the recovery | ## Webhook Events Dunning sends two webhook events: | Event | Description | | - | - | | `dunning.started` | A dunning attempt has started for a subscription | | `dunning.recovered` | A subscription has been recovered through dunning | > [card] [Recovery Webhook Payloads](/developer-resources/webhooks/intents/recovery) > > View the full webhook payload schemas for dunning events. ## Edge Cases Dunning handles these cases automatically: | Scenario | Behavior | | - | - | | Customer pays before the first email | The subscription is reactivated, and the dunning attempt is marked `exhausted` instead of `recovered`. No `dunning.recovered` event is sent. | | Customer has, or buys, another active subscription with your business | The dunning attempt is marked `exhausted` before the next email | | All dunning emails sent | Seven days after the last email, the dunning attempt is marked `exhausted`. The subscription state doesn't change. | | Subscription changes to an unexpected state, for example cancellation at the end of a grace period | The dunning attempt is marked `exhausted` | | The subscription's [BYOP](/features/byop) connector is disabled | No dunning attempt starts. A running attempt sends no emails until the connector is enabled again. | ## Best Practices * **Start with defaults**: The default delays (1, 3, 5, and 7 days) spread the emails over a week, so customers aren't flooded but still see a steady reminder. * **Monitor recovery rates**: Check **Recovery rate by email** to see which email drives the most recoveries. If later emails recover almost nothing, turn them off. * **Coordinate with support**: Tell your support team that dunning emails are going out, so they can help customers who reply. * **Review subscription states**: Pair dunning with the `subscription.on_hold` and `subscription.cancelled` webhooks to track the full subscription lifecycle. > [!NOTE] > > Dunning works alongside the existing on-hold and reactivation flows in the Customer Portal. Once you turn it on, it runs automatically with no integration work. ## Related > [card] [Recovery Webhooks](/developer-resources/webhooks/intents/recovery) > > React to `dunning.started` and `dunning.recovered` events. > [card] [Abandoned Cart Recovery](/features/recovery/abandoned-cart-recovery) > > Recover abandoned or failed checkouts with recovery emails. > [card] [Customer Portal](/features/customer-portal) > > Customers update their payment methods in the Customer Portal. > [card] [Subscriptions](/features/subscription) > > The subscription states that trigger dunning. # Reports Source: https://docs.dodopayments.com/features/reports Reconcile your balance, review every fee, and export payments, adjustments, payouts, and the balance ledger as CSV or XLSX for any date range. ## Introduction **Reports** explains how money moves through your balance and builds exports for your accounting. To open it, go to **Settings → Reports**. The page has three parts: > [card] [Track Money Movement](#track-money-movement) > > Two live views that explain your balance and your fees on screen. > [card] [Download Reports](#download-reports) > > Four exports you build for a date range, as CSV or XLSX. > [card] [Generated Reports](#generated-reports) > > Every report you built before, ready to download again. ![The Reports tab in Settings, showing Track Money Movement, Download Reports, and Generated Reports](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/reports-hub.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=5ca9b31a0a29106dba531c8e1c5a7f9d) Settings → Reports: live views, custom exports, and your report history > [!NOTE] > > Reports are available in **Live Mode** only. They read the live balance ledger, which test mode activity doesn't reach, so in **Test Mode** the Reports page shows a message instead of the reports. Turn on the **Live Mode** switch in the sidebar before you build a report. ## Track Money Movement Two views answer a question on screen, with no download. Each takes a date range and has an **Export** button that saves the same view as a file. ### Balance and Payout Summary This view reconciles your balance for the period. It has three blocks. ![Balance and Payout Summary showing the Balance Summary block and the Balance Change from Activity block](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/balance-and-payout-summary.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=5b0cfd57bb38fde17a0978bdb6fb56e1) Balance and Payout Summary: starting balance, activity breakdown, and payout detail **Balance Summary** shows the period from start to end. | Row | Meaning | | - | - | | Starting balance | Your balance when the period began. | | Net balance change from activity | Everything that happened in the period, except payouts. | | Total payouts | The money that left in payouts. | | Ending balance | Starting balance + activity − payouts. | **Balance Change from Activity** breaks the middle row into its parts. | Row | What it includes | | - | - | | Payments received | Successful payments. | | Refunds issued | Refunds and refund fees, less any reversal of either. | | Disputes lost | Disputes, dispute fees, and Visa RDR fees, less any dispute or dispute fee reversal. | | Fees deducted | Payment fees, payout fees, dunning fees, payment retry fees, BYOP fees, abandoned cart recovery fees, Ethoca fees, deflection fees, moderation fees, and the gateway, interchange, and scheme fees of interchange-plus-plus (IC++) payments, less any reversal. | | Tax deducted | Tax, less any tax reversal. | | Other movements | Dodo Credits, manual adjustments, currency conversion, and reserve holds and releases. | | Net Balance Change | The sum of the rows above. | > [!NOTE] > > **Other movements** holds the entries that fit no named row above: **Dodo Credits** (credits Dodo Payments applies to your balance), **manual adjustments** (corrections posted by the Dodo Payments team), and **currency conversion** (the difference recorded when a balance is converted between currencies). **Payout Reconciliation** lists each payout in the period on its own row, with the gross amount, each deduction, and the net amount paid out. ![Payout Reconciliation section listing each payout with its gross amount, deductions, and net paid out](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/payout-reconciliation.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=a6c50e1b10b010deae1cb020c1afa179) Payout Reconciliation: one row per payout, gross to net > [!TIP] > > A payout claims every unclaimed ledger entry up to its cut-off date, not only the payments in the period. Dodo Credits and adjustments can therefore fund part of a payout, and they appear under **Other**. ### All Fees **All Fees** lists every fee taken from your balance in the period, with a total and a per-transaction breakdown. ![All Fees page showing the Fee Summary total and the Fee Breakdown by Transaction section](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/all-fees.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=bae2394ff27670737555d6237e792462) All Fees: a total, then every fee itemized by transaction ## Download Reports Four reports build a file for any date range. Each opens a panel where you choose the period, the format, and the filters for that report. Every report exports as **CSV** or **XLSX**. The four reports contain: | Report | What it contains | | - | - | | **Transactions Report** | Every payment processed, with the status of each transaction. | | **Adjustments Report** | Refunds and disputes together: every balance deduction in one file. | | **Payout Report** | A summary of payouts, with the full fee breakdown per payout period. | | **Ledger Reconciliation Report** | The balance ledger, one row per movement, to reconcile against your bank statement. | ### Transactions Report ![Create a Transactions Report panel with time period, format, payment method, and payment status filters](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/transactions-report-modal.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=11c1cae00fcd638dd6e38098f3c91def) Create a Transactions Report The Transactions Report has two filters: * **Payment Method**: Card, UPI, Wallet, Bank Transfer, Bank Redirect, Pay Later, Crypto, or Bank Debit. Select **All** for every method. * **Payment Status**: Succeeded, Failed, or Pending. ### Adjustments Report ![Create an Adjustment Report panel with adjustment type, payment method, refund status, and dispute status filters](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/adjustments-report-modal.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=ab43d59e062dd154f6d190cfb733f75b) Create an Adjustment Report The Adjustments Report has four filters: * **Adjustment Type**: All, Refunds, or Disputes. * **Payment Method**: the same eight methods as the Transactions Report. * **Refund Status**: Succeeded, Failed, or Pending. * **Dispute Status**: Opened, Challenged, Accepted, Lost, Won, Cancelled, or Expired. ### Payout Report Choose a period and a format. This report has no other filters. ![Create a Payout Report panel with time period and format options](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/payout-report-modal.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=ffbf9e7d57956c0172ecbad5460afab8) Create a Payout Report ### Ledger Reconciliation Report This report has two modes. To choose one, use **Reconciliation by**. ![Create a Ledger Reconciliation Report panel set to Period, showing the event type filter list](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/ledger-report-modal.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=1a7eee33cfbb2115ec66236bf670bd70) Create a Ledger Reconciliation Report, by period **Period** exports every ledger movement in a date range. **Payout ID** exports the movements of one payout. Enter the payout reference, for example `pyt_kxncrebha`, to get the exact rows that payout settled. ![The same panel set to Payout ID, showing the field that takes a payout reference](https://mintcdn.com/dodopayments/wcp2oXUYABdJitHh/images/reports/ledger-report-by-payout-id.png?fit=max\&auto=format\&n=wcp2oXUYABdJitHh\&q=85\&s=48f49419884ae9d949ed7ad5425bb30e) Look up one payout by its reference ID > [!NOTE] > > A payout ID that doesn't exist returns an error, not an empty file. **Event Types** filters the rows by the kind of balance movement. Select **All** to keep every type, or choose from these: | Group | Options | | - | - | | Money in | Payment, Dodo Credits, Adjustment, Currency Conversion | | Payouts | Payout, Payout Reversal, Payout Fees, Payout Fees Reversal | | Refunds | Refund, Refund Reversal, Refund Fees, Refund Fees Reversal | | Disputes | Dispute, Dispute Fees, Dispute Reversal, Dispute Fees Reversal, Visa RDR Fee | | Fees | Payment Fees, Payment Retry Fee, Dunning Fees, Abandoned Cart Recovery Fee, BYOP Fee, Deflection Fees, Deflection Fees Reversal, Moderation Fees, Gateway Fee, Interchange Fee, Scheme Fee | | Tax | Tax, Tax Reversal | Not every type has a reversal. Only Payout, Payout Fees, Refund, Refund Fees, Dispute, Dispute Fees, Deflection Fees, and Tax do. > [!TIP] > > To answer "what was in this payout?", use the **Payout ID** mode. To reconcile a bank statement line by line, use **Period** with **All** event types. ## Building and Downloading a Report To build a report and download it: **1. Open the report** Go to **Settings → Reports** and select the report you need. **2. Choose the period** Pick a date range. Only data inside this range goes into the file. **3. Choose the format and filters** Select **CSV** or **XLSX**, then set the filters for that report. **4. Download** Select **Download Report**. The file downloads, and the report is added to **Generated Reports**. The file name contains the report and the date range, so you can identify a download without opening it. For example: `dodo_ledger_1Jun2026-30Jun2026.csv`. > [!NOTE] > > A CSV export starts with a UTF-8 byte order mark, so Excel displays accented characters and non-Latin scripts correctly. ### Row Limits A single export has a row limit, so you may need to split a large period. | Report | CSV | XLSX | | - | - | - | | Ledger Reconciliation | 500,000 rows | 100,000 rows | | Every other report | 100,000 rows | 50,000 rows | If your date range exceeds the limit, the export is refused with a message. Narrow the range or add a filter, then build the report again. > [!TIP] > > For a large period, choose CSV. Its row limit is higher. ## Generated Reports Every report you build is recorded, so you can download it again without rebuilding it. The **Generated Reports** table has these columns: | Column | Meaning | | - | - | | Report | The report type. | | Date Range | The period the report covers. | | Format | CSV or XLSX. | | Rows | How many rows the file holds. | | Generated by | The team member who built it. | | Created At | When it was built. | | Status | **Completed** or **Failed**. | A download link is valid for a short time. If the stored file has expired, Dodo Payments rebuilds it from the same parameters and marks the row as regenerated. > [!WARNING] > > A rebuilt report can differ from the original, because the data behind a date range keeps changing. For example, a refund or a dispute recorded after the first build appears in the rebuild. If you need the figures exactly as they were, keep the file you downloaded. ## Which Report Do I Need? Match your question to a report: | Question | Report | | - | - | | Why is my balance this number? | Balance and Payout Summary | | What was in this payout? | Ledger Reconciliation, by **Payout ID** | | What fees did I pay? | All Fees | | I need every payment for my accountant. | Transactions Report | | How much did refunds and disputes cost me? | Adjustments Report | | I need to match my bank statement. | Ledger Reconciliation, by **Period** | ## Best Practices > [!TIP] > > * Reconcile with **Balance and Payout Summary** first. Download a detailed report only when a figure needs explaining. > * Export **CSV** for a long period, and **XLSX** only when you plan to work in the file by hand. > * Keep the file you downloaded. A rebuild may not match it. > * Add filters before you widen the date range. A filter keeps an export under the row limit. > [!WARNING] > > If a figure looks wrong, check the date range and the filters first. If it is still wrong, contact support with the report type and the period. > [card] [Contact Support](mailto:support@dodopayments.com) > > Email [support@dodopayments.com](mailto:support@dodopayments.com) with the report type and the period. ## Next Steps > [card] [Dashboard Analytics](/features/analytics-and-reporting) > > Track revenue, customers, retention, and transaction health. > [card] [Account Summary & Payout Wallet](/features/account-summary-payout-wallet) > > Understand your earnings, deductions, and payout cycles. > [card] [Payout Structure](/features/payouts/payout-structure) > > See how and when payouts reach your bank account. > [card] [Refunds](/features/transactions/refunds) > > Initiate and monitor refunds. # Seat-Based Billing Source: https://docs.dodopayments.com/features/seat-based-billing Implement per-user pricing for team software, SaaS products, and enterprise licenses with flexible seat management and proration. > [!NOTE] > > Seat-based billing charges customers based on the number of users on their account. Dodo Payments implements it using the **add-on** system: a base subscription product plus a per-seat add-on whose quantity represents the seat count. > [card] [Implementation Tutorial](/developer-resources/seat-based-pricing) > > Step-by-step guide with code examples. > [card] [Add-ons Documentation](/features/addons) > > Learn about the add-on system that powers seat-based billing. > [card] [Subscription Management](/features/subscription) > > Manage seat-based subscriptions and plan changes. > [card] [Webhooks](/developer-resources/webhooks/intents/subscription) > > Track seat changes with subscription webhooks. *** ## What is Seat-Based Billing? Seat-based billing charges customers based on the number of users who access your product. Instead of a flat fee, the price scales with team size. ### Common Use Cases | Industry | Example | Pricing Model | | - | - | - | | Team Collaboration | Slack, Notion, Asana | Per active user/month | | Developer Tools | GitHub, GitLab, Jira | Per seat/month | | CRM Software | Salesforce, HubSpot | Per user license | | Design Tools | Figma, Canva | Per editor seat | | Security Software | 1Password, Okta | Per user/month | | Video Conferencing | Zoom, Teams | Per host license | ### Benefits of Seat-Based Pricing **For Your Business:** * Revenue scales as customers grow * Customers can budget predictably * Clear upgrade path from individual to team to enterprise * Higher lifetime value as teams expand **For Your Customers:** * Pay only for the users they have * Easy to understand and forecast costs * Add or remove users as needed * Fair pricing that matches team size *** ## How It Works Dodo Payments implements seat-based billing using the **Add-ons** system. A seat-based subscription has two parts: | Component | What it is | Example | | - | - | - | | **Base product** | The subscription plan | "Team Plan" — \$50/month | | **Seat add-on** | A per-unit charge for each seat | "Extra Seat" — \$10/month per seat | The customer's monthly total is: ``` Total = Base price + (Seat add-on price × seat quantity) ``` **Example: 8 extra seats on a Team Plan** ``` Base plan: $50/month Seats: 8 × $10 = $80/month ──────────────────────────────── Total: $130/month ``` *** ## Pricing Strategies Choose the seat-based pricing strategy that fits your business: ### Strategy 1: Base + Per-Seat Add-on Include a set number of seats in the base plan, charge for additional seats. ``` Team Plan: $49/month (includes 5 seats) Extra seats: $10/month each 8 total seats = $49 + (3 × $10) = $79/month ``` **Best for:** Products where small teams can function with the base offering. ### Strategy 2: Pure Per-Seat Pricing Charge a flat rate per seat with no base fee. ``` Per Seat: $12/month 5 users = 5 × $12 = $60/month 50 users = 50 × $12 = $600/month ``` **Implementation:** Set the base plan price to \$0 and use only the seat add-on. **Best for:** Simple, transparent pricing. ### Strategy 3: Tiered Seat Pricing Different base plans with different per-seat rates. ``` Starter: $0/month + $15/seat Pro: $99/month + $10/seat Enterprise: $499/month + $7/seat ``` **Implementation:** Create separate products for each tier with different add-on prices. **Best for:** Encouraging upgrades to higher tiers; enterprise sales. ### Strategy 4: Seat Bundles Sell seats in packs rather than individually. ``` 5-Seat Pack: $50/month ($10/seat) 10-Seat Pack: $80/month ($8/seat) 25-Seat Pack: $175/month ($7/seat) ``` **Implementation:** Create multiple add-ons for different pack sizes. **Best for:** Simplifying purchasing decisions; encouraging larger commitments. *** ## Setting Up Seat-Based Billing ### Step 1: Plan Your Pricing Before implementation, define your pricing structure: **1. Define Base Plan** Decide what's included in the base subscription: * Base price (can be \$0 for pure per-seat) * Number of included seats * Features available at this tier **2. Set Seat Pricing** Determine the per-seat add-on cost: * Price per additional seat * Any volume discounts (via multiple add-ons) * Maximum seats allowed (if applicable) **3. Consider Billing Frequency** Align seat pricing with your billing cycle: * Monthly subscriptions → monthly seat charges * Annual subscriptions → annual seat charges (often discounted) ### Step 2: Create the Seat Add-on In your Dodo Payments dashboard: 1. Navigate to **Products** → **Add-Ons** 2. Click **Create Add-On** 3. Configure the add-on: | Field | Value | Notes | | - | - | - | | Name | "Additional Seat" or "Team Member" | Clear, user-friendly name | | Description | "Add another team member to your workspace" | Explain what customers get | | Price | Your per-seat price | e.g., \$10.00 | | Currency | Match your base product | Must be the same currency | | Tax Category | Same as base product | Ensures consistent tax handling | > [!TIP] > > Use descriptive add-on names that make sense on invoices. "Additional Team Seat" is clearer than "Seat Add-on" for customers reviewing their bills. ### Step 3: Create the Base Subscription Create your subscription product: 1. Navigate to **Products** → **Create Product** 2. Select **Subscription** 3. Configure pricing and details 4. In the **Add-Ons** section, attach your seat add-on ### Step 4: Attach Add-on to Product Link the seat add-on to your subscription: 1. Edit your subscription product 2. Scroll to **Add-Ons** section 3. Click **Add Add-Ons** 4. Select your seat add-on 5. Save changes > [!TIP] > > Your subscription product now supports seat-based pricing. Customers can purchase any quantity of additional seats during checkout. *** ## Managing Seats ### Adding Seats to New Subscriptions When creating a checkout session, specify the seat quantity: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_team_plan', quantity: 1, addons: [{ addon_id: 'adn_YOUR_SEAT_ADDON', quantity: 8 // 8 additional seats }] }], customer: { email: 'admin@company.com' }, return_url: 'https://yourapp.com/success' }); ``` ### Changing Seat Count on Existing Subscriptions Use the Change Plan API to adjust seats. The `addons` array sets the **new total** seat count (not the delta). ```typescript theme={null} // Currently 3 seats → change to 8 seats await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_team_plan', quantity: 1, proration_billing_mode: 'prorated_immediately', addons: [{ addon_id: 'adn_YOUR_SEAT_ADDON', quantity: 8 // new total, not +5 }] }); ``` ### Removing Seats To reduce seat count, specify the lower quantity: ```typescript theme={null} // Currently 8 seats → reduce to 3 seats await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_team_plan', quantity: 1, proration_billing_mode: 'prorated_immediately', addons: [{ addon_id: 'adn_YOUR_SEAT_ADDON', quantity: 3 // new total }] }); ``` ### Removing All Additional Seats Pass an empty `addons` array to remove all add-ons: ```typescript theme={null} // Remove all additional seats, keep only base plan seats await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_team_plan', quantity: 1, proration_billing_mode: 'prorated_immediately', addons: [] // removes all add-ons }); ``` *** ## Proration for Seat Changes When a seat change is applied mid-cycle, Dodo Payments calculates the immediate charge in three steps: ``` 1. Credit → a portion of the OLD plan's price (base + all add-ons) 2. Charge → a FULL cycle of the NEW plan's price 3. Net = Charge − Credit ``` The credit amount depends on the **proration mode** you choose. The charge is always a full cycle. > [!WARNING] > > The charge is **always for a full cycle**. Only the credit varies by mode. This is why the amount charged is rarely "new seats × price × days remaining". > > With `prorated_immediately`, the credit shrinks as the cycle progresses, so the same seat change costs more the later it is made. With `difference_immediately` and `full_immediately`, the credit does not depend on timing, so those two cost the same on any day of the cycle. ### How Each Mode Credits | Mode | Credit (old plan) | Charge (new plan) | Billing cycle | | - | - | - | - | | `prorated_immediately` | Remaining time only (time left ÷ cycle length) | Full cycle | Resets to today | | `prorated_immediately_keep_cycle` | Remaining time only | Remaining time only | **Unchanged** | | `difference_immediately` | The whole old plan | Full cycle | Resets to today | | `full_immediately` | None (0%) | Full cycle | Resets to today | | `do_not_bill` | Nothing credited, nothing charged | Not charged now — seats active immediately | **Unchanged** | With `difference_immediately`, the customer pays only the gap between the old plan price and the new plan price. That is where the name comes from, and it is why the amount is the same whenever in the cycle the change is made. If the credit is larger than the new cycle charge, the difference is held as subscription-scoped credit and applied automatically to future renewals. > [!WARNING] > > `prorated_immediately`, `difference_immediately`, and `full_immediately` all **reset the billing cycle to the change date**. The next renewal is re-anchored to the day the seat change is applied. **`do_not_bill`** keeps the original renewal date (the new seat count is billed in full at the next renewal, with no charge at the time of change). **`prorated_immediately_keep_cycle`** also keeps the original renewal date. It charges the price difference for the time left now. > [!NOTE] > > `prorated_immediately_keep_cycle` is the exception to the full-cycle charge. It charges only the time left on both sides, so the net is (new plan − old plan) × time left. Adding 5 seats at \$10 with 50% of the cycle left costs \$25.00. Removing seats gives a credit by the same rule. The credit goes to the [Customer Wallet](/features/customer-wallet). > [!WARNING] > > **`do_not_bill` applies the seat change immediately, not at renewal.** The new seat count takes effect as soon as the call succeeds, but nothing is charged until the next renewal. > > When **adding** seats, the customer has them free for the rest of the current cycle. Adding 5 seats at \$10 on day 1 of a 30-day cycle gives them 5 free seats for 29 days, and the higher amount is first charged on the original renewal date. > > When **removing** seats, the reverse applies: the seats are withdrawn immediately and no credit is given for the part of the cycle already paid for. > > Use `do_not_bill` when that is what you intend, such as a courtesy upgrade or a sales-agreed trial of extra seats. ### Worked Example: Adding 5 Seats One scenario run through all five modes, so the numbers are directly comparable. ``` Plan: $50/month base + $10/seat add-on Current: $50 + 3 × $10 = $80/month New: $50 + 8 × $10 = $130/month Timing: Day 15 of a 30-day cycle (50% remaining) ``` | Mode | Credit | Charge | **Net today** | Next renewal | | - | - | - | - | - | | `prorated_immediately` | −\$40.00 (50% × \$80) | +\$130.00 | **\$90.00** | \$130/month from today | | `prorated_immediately_keep_cycle` | −\$40.00 (50% × \$80) | +\$65.00 (50% × \$130) | **\$25.00** | \$130/month on original renewal date | | `difference_immediately` | −\$80.00 (the whole old plan) | +\$130.00 | **\$50.00** | \$130/month from today | | `full_immediately` | \$0.00 | +\$130.00 | **\$130.00** | \$130/month from today | | `do_not_bill` | — | — | **\$0.00** | \$130/month on original renewal date | In `prorated_immediately`, `difference_immediately`, and `full_immediately`, the customer receives a **full new month at \$130** in exchange for what they pay today. ### Why Timing Matters for `prorated_immediately` The same change costs more the later in the cycle it is made, because less of the current cycle is left to credit back. ``` Current: $80/month → New: $130/month ``` | When | Remaining | Credit | Charge | **Net today** | | - | - | - | - | - | | Day 3 of 30 | 90% | −\$72.00 | +\$130.00 | **\$58.00** | | Day 15 of 30 | 50% | −\$40.00 | +\$130.00 | **\$90.00** | | Day 27 of 30 | 10% | −\$8.00 | +\$130.00 | **\$122.00** | The customer receives a full new month in every row. Only the split between "already paid for" and "paying now" changes. To make a seat change cost the same regardless of when it happens, use `difference_immediately`. ### Worked Example: The "Surprising Charge" This is the case that most often surprises merchants. Adding a small seat add-on late in the cycle can produce a charge much larger than the add-on's price. ``` Plan: $50/month base, no add-ons Change: add 1 seat at $10/month Timing: Day 27 of a 30-day cycle (10% remaining) ``` | Mode | Credit | Charge | **Net today** | | - | - | - | - | | `prorated_immediately` | −\$5.00 (10% × \$50) | +\$60.00 | **\$55.00** | | `prorated_immediately_keep_cycle` | −\$5.00 (10% × \$50) | +\$6.00 (10% × \$60) | **\$1.00** | | `difference_immediately` | −\$50.00 (the whole old plan) | +\$60.00 | **\$10.00** | | `full_immediately` | \$0.00 | +\$60.00 | **\$60.00** | | `do_not_bill` | — | — | **\$0.00** | Adding a \$10/month seat costs **\$55.00** with `prorated_immediately`. The customer is charged for a full new month at \$60 and credited the \$5 that was left on the old month, and their renewal date resets. To make small mid-cycle additions cost the seat price and nothing more, use `difference_immediately`. To charge only for the time left and keep the renewal date, use `prorated_immediately_keep_cycle`. ### Worked Example: Removing Seats (Downgrade) With `prorated_immediately` or `difference_immediately`, when the new plan costs less than the credit, the excess is held as **subscription credit** and applied automatically to future renewals of this subscription. It is not added to the [Customer Wallet](/features/customer-wallet) and is not a [credit entitlement](/features/credit-based-billing). ``` Current: $50 base + 8 × $10 seats = $130/month New: $50 base + 2 × $10 seats = $70/month Timing: Day 6 of a 30-day cycle (80% remaining) Mode: prorated_immediately ``` ``` Credit for unused time on the current cycle (base plus all add-ons): = $130 × 80% = $104.00 credit Charge for a full cycle at the new seat count: = $50 + (2 × $10) = $70.00 Net = $70.00 − $104.00 = −$34.00 → $0 charged today → $34.00 held as subscription credit (applied to future renewals) → Billing cycle resets; next renewal is $70/month ``` > [!NOTE] > > The credit covers the **entire** subscription, base plan and all add-ons, not only the seats being removed. ### Reading the Preview Response `previewChangePlan` returns the exact line items that will be billed. Each line item has a `proration_factor`: | `proration_factor` | Meaning | | - | - | | Negative (e.g. `−0.50`) | **Credit** — fraction of the old plan being refunded | | `1` | **Charge** — a full new billing cycle | | `0` | **No charge / no credit** for this line | ```json expandable theme={null} { "immediate_charge": { "summary": { "settlement_amount": 9000, "settlement_currency": "USD" }, "line_items": [ { "type": "subscription", "unit_price": 5000, "quantity": 1, "proration_factor": -0.50 }, { "type": "addon", "unit_price": 1000, "quantity": 3, "proration_factor": -0.50 }, { "type": "subscription", "unit_price": 5000, "quantity": 1, "proration_factor": 1 }, { "type": "addon", "unit_price": 1000, "quantity": 8, "proration_factor": 1 } ] } } ``` Reading that: \$50 base and 3 × \$10 addon credited at 50%, a full \$50 base charged, and 8 × \$10 addon charged. Credit = \$40, charge = \$130, net = \$90. > [!NOTE] > > Proration is calculated to the second based on the exact time of the change, not rounded to the nearest day. The worked examples above use round day-boundary numbers for clarity. > [!TIP] > > **Choosing a proration mode for seat changes** > > * **`difference_immediately`** — the customer pays the price difference, whenever the change is made. Most predictable for teams that adjust seats often, and easiest to explain in your UI. > > * **`prorated_immediately`** — the customer is credited only for the time left on the current cycle. Costs more the later in the cycle the change is made. > > * **`prorated_immediately_keep_cycle`** — the customer pays the price difference for the time left on the current cycle. Removed seats give a credit by the same rule, and the credit goes to the customer wallet. The renewal date is preserved. > > * **`full_immediately`** — the customer pays for a full new cycle with no credit for unused time. > > * **`do_not_bill`** — the seat change takes effect immediately but nothing is charged now. Added seats are free until the next renewal; removed seats are withdrawn with no credit. The renewal date is preserved and the new seat count is billed in full from that renewal onwards. `do_not_bill` and `prorated_immediately_keep_cycle` are the only modes that do not reset the billing cycle. > > > [!NOTE] > > > > Seats granted through `do_not_bill` are not credited on a later plan change, because they were never billed. If you add 5 seats with `do_not_bill` and then change to 3 seats, the customer is billed for 3 seats in full with no credit for the 5 they were holding. > > Always call `previewChangePlan` and show the returned amount before confirming. See the [Proration Guide](/developer-resources/subscription-upgrade-downgrade#proration-modes) for detailed comparisons. ### Preview Before Changing Always preview proration before making changes: ```typescript expandable theme={null} const preview = await client.subscriptions.previewChangePlan('sub_123', { product_id: 'pdt_team_plan', quantity: 1, proration_billing_mode: 'prorated_immediately', addons: [{ addon_id: 'adn_YOUR_SEAT_ADDON', quantity: 8 }] }); console.log('Charge today:', preview.immediate_charge.summary.settlement_amount); console.log('Currency:', preview.immediate_charge.summary.settlement_currency); // Show customer: "Adding 5 seats will cost $90.00 today" ``` *** ## Tracking Seats with Webhooks Monitor seat changes by listening to subscription webhooks: ### Relevant Events | Event | When Triggered | Use Case | | - | - | - | | `subscription.active` | New subscription activated | Provision initial seats | | `subscription.plan_changed` | Seats added/removed | Update seat count in your app | | `subscription.renewed` | Subscription renewed | Confirm seat count unchanged | | `subscription.cancelled` | Subscription cancelled | Deprovision all seats | ### Webhook Handler Example ```typescript expandable theme={null} app.post('/webhooks/dodo', async (req, res) => { const event = req.body; switch (event.type) { case 'subscription.active': { // New subscription - provision seats const addonSeats = event.data.addons?.reduce( (total, addon) => total + addon.quantity, 0 ) || 0; await provisionSeats(event.data.customer.customer_id, addonSeats); break; } case 'subscription.plan_changed': { // Seats changed - update access const newSeats = event.data.addons?.reduce( (total, addon) => total + addon.quantity, 0 ) || 0; await updateSeatCount(event.data.subscription_id, newSeats); break; } case 'subscription.cancelled': // Subscription cancelled - deprovision await revokeAllSeats(event.data.subscription_id); break; } res.json({ received: true }); }); ``` > [!TIP] > > The `addons` array in the webhook payload contains the current addon quantities. Sum them to get the total seat count. If your base plan includes seats (e.g. 5 included), add that to the addon total in your application logic. *** ## Enforcing Seat Limits Your application must enforce seat limits. Dodo Payments tracks billing, but you control access. > [tab] Hard Limit > > Strictly prevent adding users beyond the seat count. > > ```typescript expandable theme={null} > async function inviteUser(teamId: string, email: string) { > const team = await getTeam(teamId); > const subscription = await getSubscription(team.subscriptionId); > const totalSeats = calculateTotalSeats(subscription); > const usedSeats = await countTeamMembers(teamId); > > if (usedSeats >= totalSeats) { > throw new Error('No seats available. Please upgrade your plan.'); > } > > await sendInvitation(teamId, email); > } > ``` > [tab] Soft Limit with Warning > > Allow exceeding with a warning and grace period. > > ```typescript expandable theme={null} > async function inviteUser(teamId: string, email: string) { > const team = await getTeam(teamId); > const { totalSeats, usedSeats } = await getSeatInfo(team); > > if (usedSeats >= totalSeats) { > // Allow but flag for billing > await flagOverage(teamId, usedSeats - totalSeats + 1); > await notifyAdmin(team.adminEmail, 'You have exceeded your seat limit'); > } > > await sendInvitation(teamId, email); > } > ``` > [tab] Auto-Upgrade > > Automatically add seats when limit is reached. > > ```typescript expandable theme={null} > async function inviteUser(teamId: string, email: string) { > const team = await getTeam(teamId); > // seatAddonQuantity is the current quantity of the seat add-on on the subscription > const { totalSeats, usedSeats, subscriptionId, seatAddonQuantity } = await getSeatInfo(team); > > if (usedSeats >= totalSeats) { > // Automatically add a seat > await client.subscriptions.changePlan(subscriptionId, { > product_id: team.productId, > quantity: 1, > proration_billing_mode: 'prorated_immediately', > addons: [{ addon_id: 'adn_YOUR_SEAT_ADDON', quantity: seatAddonQuantity + 1 }] > }); > > await notifyAdmin(team.adminEmail, 'A new seat was added to your plan'); > } > > await sendInvitation(teamId, email); > } > ``` *** ## Advanced Patterns ### Different Seat Types Offer different seat types with different pricing: ``` Full Seats: $20/month - Full access to all features View-Only Seats: $5/month - Read-only access Guest Seats: $0/month - Limited external collaborator access ``` **Implementation:** Create separate add-ons for each seat type. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_team_plan', quantity: 1, addons: [ { addon_id: 'addon_full_seat', quantity: 10 }, { addon_id: 'addon_viewer_seat', quantity: 25 }, { addon_id: 'addon_guest_seat', quantity: 50 } ] }] }); ``` ### Annual Seat Discounts Offer discounted annual seat pricing: ``` Monthly: $15/seat/month Annual: $12/seat/month (20% savings) ``` **Implementation:** Create separate products for monthly and annual plans with different add-on prices. ### Minimum Seat Requirements Require a minimum number of seats for certain plans: ```typescript theme={null} async function validateSeatCount(planId: string, seatCount: number) { const minimums = { 'pdt_starter': 1, 'pdt_team': 5, 'pdt_enterprise': 25 }; if (seatCount < minimums[planId]) { throw new Error(`${planId} requires at least ${minimums[planId]} seats`); } } ``` *** ## Best Practices ### Pricing Best Practices * **Clear Communication**: Show per-seat pricing prominently on your pricing page * **Included Seats**: Consider including a few seats in the base price to reduce friction * **Volume Discounts**: Offer lower per-seat rates for larger teams to win enterprise deals * **Annual Incentives**: Discount annual plans to improve cash flow and retention ### Technical Best Practices * **Cache Seat Counts**: Cache subscription seat counts locally to avoid API calls on every request * **Sync Regularly**: Periodically sync your local seat count with Dodo Payments via API * **Handle Failures**: If a seat change fails, show clear error messages and retry options * **Audit Trail**: Log all seat changes for billing disputes and compliance ### User Experience Best Practices * **Real-Time Feedback**: Show the cost impact immediately when adjusting seats * **Confirmation Steps**: Require confirmation before billing changes * **Proration Transparency**: Explain prorated charges clearly before applying * **Easy Downgrades**: Don't make it difficult to reduce seats (it builds trust) *** ## Troubleshooting > [accordion] Seat count mismatch between app and billing > > **Symptom**: Your app shows a different seat count than the subscription. > > **Causes**: > > * Webhook not received or processed > * Race condition during seat change > * Cached data not updated > > **Solutions**: > > 1. Implement webhook handlers for `subscription.plan_changed` > 2. Add a "Sync with billing" button that fetches current subscription > 3. Set cache TTL to ensure regular refresh > [accordion] Unexpected mid-cycle charge amount > > **Symptom**: Customer confused by mid-cycle charge amount. > > **Cause**: Using `prorated_immediately` late in the billing cycle (see [The Surprising Charge](#worked-example-the-surprising-charge) example above). > > **Solutions**: > > 1. Always use `previewChangePlan` before making changes > 2. Show clear breakdown: "Adding X seats will cost \$Y today" > 3. Switch to `difference_immediately` if you want the charge to always match the price difference > [accordion] Add-on not appearing in checkout > > **Symptom**: Seat add-on not available during checkout. > > **Causes**: > > * Add-on not attached to product > * Add-on archived or deleted > * Currency mismatch between product and add-on > > **Solutions**: > > 1. Verify add-on is attached in product settings > 2. Check add-on status in Add-Ons dashboard > 3. Ensure currencies match exactly > [accordion] Cannot reduce seats below current usage > > **Symptom**: Customer wants to reduce seats but has users assigned. > > **Solutions**: > > 1. Show which users must be removed before reducing seats > 2. Implement a workflow: Remove users → Reduce seats > 3. Consider a grace period before enforcing seat reduction *** ## Related Documentation > [card] [Seat-Based Pricing Tutorial](/developer-resources/seat-based-pricing) > > Complete implementation guide with code. > [card] [Add-ons](/features/addons) > > Understand the add-on system in depth. > [card] [Plan Changes & Proration](/developer-resources/subscription-upgrade-downgrade) > > Handle subscription modifications. > [card] [Subscription Webhooks](/developer-resources/webhooks/intents/subscription) > > Track subscription events. # Single Page Checkout Source: https://docs.dodopayments.com/features/single-page-checkout Reduce checkout drop-off by collecting contact, billing, and payment details on one page. Turn it on per checkout session or payment link, with no SDK change. ![Single page checkout with the order summary on the left, and Apple Pay and Google Pay, the email field, the payment method list, and the Pay Now button on the right](https://mintcdn.com/dodopayments/BgNHdF-IjEx41CmK/images/single-page-checkout/cover.png?fit=max\&auto=format\&n=BgNHdF-IjEx41CmK\&q=85\&s=2e93dfd6129d45e02f61e18636671a98) Single page checkout puts the wallet buttons, contact information, billing information, and the payment form on one page. Your customer enters their details, picks a payment method, and pays without moving to a separate payment step. With fewer steps and fewer fields before the **Pay Now** button, single page checkout is built to reduce drop-off and complete more payments than the two-page checkout. Single page checkout is off by default. You turn it on for each checkout session through the API, or for a payment link through its URL. > [card] [Checkout Sessions API](/api-reference/checkout-sessions/create) > > Create checkout sessions with `feature_flags.single_page`. > [card] [Checkout Features](/features/checkout) > > Currency, tax, discount codes, and address options for every checkout. > [card] [Overlay Checkout](/developer-resources/overlay-checkout) > > Open checkout in a modal on your site. > [card] [Inline Checkout](/developer-resources/inline-checkout) > > Embed checkout directly in your page. ## Why Use Single Page Checkout Each extra step and field between opening checkout and paying is a point where a customer can leave. Single page checkout removes the steps and fields that the two-page checkout adds before payment: * **No second page.** The two-page checkout collects details on page one, then loads a separate payment page after **Continue to Payment**. Single page checkout shows the payment form when the page opens, so the customer pays with no extra click and no second page load. * **Fewer fields before payment.** The contact block asks only for the email, and for the phone number only when you require it. Because `minimal_address` is on by default, billing information asks for the full name, the country, and the ZIP code only where tax needs it. * **Apple Pay and Google Pay first.** The wallet buttons sit at the top of the page. A customer with a card saved in their wallet pays without typing card details, and the checkout takes the email from the wallet when the field is empty. * **The final price before paying.** Tax, discounts, and currency changes update the total on the same page, so the customer sees the amount they pay before they press **Pay Now**, not on a later page. * **No charge for a total the customer did not see.** The customer pays the total that the page or the wallet sheet showed. If the total changes before the charge, the payment stops and the page shows the new total. The table compares the two checkout flows: | | Two-page checkout | Single page checkout | | - | - | - | | Steps | Details on page one, payment on page two | One page | | Contact fields | Full name, email, and phone on page one | Email, and phone only when required. The full name is in **Billing Information** | | Billing fields | On page one, before **Continue to Payment** | Inside the selected payment method | | Apple Pay and Google Pay | On the payment page | At the top of the page, or in the payment method list | | Pricing updates | As the customer edits page one | As the customer edits billing, tax ID, discount, currency, or cart fields | | Pay button | On the payment page | Inside the selected payment method | ## How It Works The hosted page keeps the same two-column layout as the standard checkout. The left column shows the order summary: your brand, the product, the discount code field, the subtotal, tax, and total, and the currency selector. The right column holds everything the customer fills in, followed by the page footer, from top to bottom: 1. **Apple Pay and Google Pay**: the wallet buttons the customer's device supports, with an **OR** line under them. See [Apple Pay and Google Pay](#apple-pay-and-google-pay) for when they move into the payment method list. 2. **Email**: the customer's email address. When you set `require_phone_number`, this block is titled **Contact Information** and also asks for the phone number. [Custom fields](/developer-resources/checkout-session#collecting-custom-fields) appear below this block. 3. **Payment Method**: the payment methods, as an accordion list by default. The selected method shows its own fields, then **Billing Information** (the customer's full name, country, and ZIP code), the **Purchasing as a business** checkbox, and the **Pay Now** button. 4. **Footer**: the security notice, the Merchant of Record notice, and the Privacy and Terms links. ![Right column of single page checkout showing the Apple Pay and Google Pay buttons, the email field, and the Payment Method list with Card expanded, the card fields, billing information with the full name, the Purchasing as a business checkbox, and the Pay Now button](https://mintcdn.com/dodopayments/BgNHdF-IjEx41CmK/images/single-page-checkout/payment-method.png?fit=max\&auto=format\&n=BgNHdF-IjEx41CmK\&q=85\&s=e8764db43e5bd3cc9ff17b3c8dcaf2c3) The page prices the order when it loads. It uses the billing country estimated from the customer's location, or the `billing_address.country` you set on the session. When the customer changes their country, state, ZIP code, tax ID, discount codes, currency, quantity, add-ons, or selected product, the totals in the left column update on the same page. If you set `pay_button_text` in `customization.theme_config`, that text replaces **Pay Now**. ## Enabling Single Page Checkout To use single page checkout for a session, set `feature_flags.single_page` to `true` when you create the checkout session. The examples use a `client` set up as in the [Checkout Sessions guide](/developer-resources/checkout-session#creating-your-first-checkout-session): ```typescript Node.js theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], feature_flags: { single_page: true }, return_url: 'https://yoursite.com/checkout/success' }); ``` ```python Python theme={null} session = client.checkout_sessions.create( product_cart=[{"product_id": "pdt_123", "quantity": 1}], feature_flags={"single_page": True}, return_url="https://yoursite.com/checkout/success", ) ``` ```bash cURL theme={null} curl -X POST https://test.dodopayments.com/checkouts \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "product_cart": [{ "product_id": "pdt_123", "quantity": 1 }], "feature_flags": { "single_page": true }, "return_url": "https://yoursite.com/checkout/success" }' ``` Send the customer to the `checkout_url` in the response, as you do for any checkout session. ### Payment Links To open a payment link as single page checkout, add `singlePage=true` to the link: ```text theme={null} https://checkout.dodopayments.com/buy/pdt_123?singlePage=true ``` This works for product links (`/buy/pdt_...`) and product collection links (`/buy/pdc_...`). Only the exact value `true` turns it on. Any other value keeps the two-page checkout. See [Payment Links](/developer-resources/integration-guide#payment-links) for the other query parameters. ### Overlay and Inline Checkout Overlay checkout and inline checkout use the flag on the checkout session. Create the session with `feature_flags.single_page: true` and pass its `checkout_url` to the Checkout SDK as usual. The SDK needs no extra option. ## Payment Method Layout Single page checkout shows the payment methods in one of two layouts: * **Accordion** (default): one row for each payment method. The accordion opens with no payment method selected, so the customer picks one. A customer with a saved payment method sees that row open. The selected row opens to show its fields and the **Pay Now** button. * **Tabs**: one tab for each payment method. The fields of the selected tab show below the tabs. ![Single page checkout with the payment methods shown as tabs, with Card selected](https://mintcdn.com/dodopayments/BgNHdF-IjEx41CmK/images/single-page-checkout/tabs.png?fit=max\&auto=format\&n=BgNHdF-IjEx41CmK\&q=85\&s=e473d88623711d23cb01a12b4b8f7e0a) To pick the layout, set `customization.payment_method_layout` to `accordion` or `tabs` when you create the session: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], feature_flags: { single_page: true }, customization: { payment_method_layout: 'tabs' }, return_url: 'https://yoursite.com/checkout/success' }); ``` `payment_method_layout` is only for single page checkout. If you set it while `feature_flags.single_page` is `false`, the request fails with a `422` error. You can also add `layout=tabs` or `layout=accordion` to the `checkout_url`. The value in the URL takes priority over the value on the session. ## Apple Pay and Google Pay The wallet buttons show at the top of the page, above the email field. Each button shows only when the customer's device and browser support that wallet. When the customer pays with a wallet and left the email field empty, the checkout uses the email from the wallet. The wallets move from the top of the page into the payment method list when the customer must fill in more than the email first: * You set `require_phone_number`. * You set `require_tax_id`. * The session has a required [custom field](/developer-resources/checkout-session#collecting-custom-fields). In the list, Apple Pay and Google Pay are rows (or tabs) like the other payment methods. The customer fills in the required fields, selects the wallet, and presses its Apple Pay or Google Pay button, which opens the wallet sheet. ![Single page checkout that requires a phone number, with Apple Pay selected in the payment method list and Google Pay as the next row](https://mintcdn.com/dodopayments/BgNHdF-IjEx41CmK/images/single-page-checkout/wallets-in-list.png?fit=max\&auto=format\&n=BgNHdF-IjEx41CmK\&q=85\&s=0f273f06ea5dea9957afbb705c4ff9d6) ### Wallet Totals The customer always pays the total that the wallet sheet shows: * **Apple Pay at the top of the page** prices the sheet for the country of the card's billing address before the customer approves. The sheet keeps the currency it opened with. For example, a $100 product on a US page, paid with a card billed in India, shows $118 USD with India's GST. * When Apple shares no billing address, or the postal code is too short to set the tax rate, the Apple Pay sheet shows the tax as pending. The customer then pays the exact tax for their full billing address. * If the card's country needs another currency, for example for a country-specific price, the Apple Pay sheet shows "Please use a card billed in" followed by the page's country. The customer picks another card. * **Apple Pay and Google Pay in the payment method list** charge the total on the page, for the address the customer entered. The card's billing address does not change the total. * **Google Pay at the top of the page** shares the card's billing address only after the customer approves. If that address changes the total, the payment stops before any charge, and the page shows the new total. The customer pays again with the new total. ## Address Collection Single page checkout turns on `minimal_address` by default. Billing information then asks only for the country, and for the ZIP or postal code in regions where tax needs it. To collect the full billing address, set `minimal_address` to `false`: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], feature_flags: { single_page: true }, minimal_address: false, return_url: 'https://yoursite.com/checkout/success' }); ``` See [Smart Address Collection](/features/checkout#smart-address-collection) for how each address mode works. ## Business Purchases and Tax ID Customers who buy for a company check **Purchasing as a business** inside the selected payment method. The business name and tax ID fields then appear in the same place. The `allow_tax_id` and `require_tax_id` feature flags behave the same as in the two-page checkout. ![Purchasing as a business checked in single page checkout, showing the business name and tax ID fields](https://mintcdn.com/dodopayments/BgNHdF-IjEx41CmK/images/single-page-checkout/business-tax-id.png?fit=max\&auto=format\&n=BgNHdF-IjEx41CmK\&q=85\&s=65fdb0c60575ba818c57825b971d9f9d) ## Subscriptions Single page checkout supports subscription products. The order summary shows the subscription, and the customer pays for it on the same page. See [Subscriptions](/features/subscription) for billing cycles, trials, and plan changes. ![Single page checkout for a subscription product](https://mintcdn.com/dodopayments/BgNHdF-IjEx41CmK/images/single-page-checkout/subscription.png?fit=max\&auto=format\&n=BgNHdF-IjEx41CmK\&q=85\&s=598fda163f4255db388a55ca46f19acd) ## Mobile and Dark Mode On a phone, single page checkout fits the same fields to the narrow screen. ![Single page checkout on a mobile phone](https://mintcdn.com/dodopayments/BgNHdF-IjEx41CmK/images/single-page-checkout/mobile.png?fit=max\&auto=format\&n=BgNHdF-IjEx41CmK\&q=85\&s=3161c53ca4b9bb1517866e785eafd65b) The customer can switch between light and dark mode with the theme switch in the page footer. Colors for each mode come from your **Design** settings in the dashboard, or from `customization.theme_config` on the session. See [Design & Theme Customization](/features/design). ![Single page checkout in dark mode](https://mintcdn.com/dodopayments/BgNHdF-IjEx41CmK/images/single-page-checkout/dark-mode.png?fit=max\&auto=format\&n=BgNHdF-IjEx41CmK\&q=85\&s=af9c52a24c5e05d5a11d0d577692c4d2) ## Embedded Checkout Events The Checkout SDK sends the same events for a single page session as for a two-page session. See [Overlay Checkout](/developer-resources/overlay-checkout) and [Inline Checkout](/developer-resources/inline-checkout) for each integration's event list. These events fire at a different point, or only in single page checkout: | Event | Single page checkout | | - | - | | `checkout.payment_page_opened` | Fires once, when the page opens, because the payment form is on the first page. In the two-page flow, it fires when the payment page opens. | | `checkout.form_ready` | Fires when the payment form on the page is ready for input. | | `checkout.payment_method_selected` | Fires each time the customer picks or changes a payment method row or tab. `data.message.payment_method_type` holds the method, for example `card` or `upi_collect`. A method that the checkout opens by itself, such as a saved payment method on load, does not fire it. Requires Checkout SDK `2.1.1` or later. | The payment methods offered inside overlay and inline embeds are the same as in the two-page flow. See [Digital Wallets](/features/payment-methods/digital-wallets) for Apple Pay and Google Pay availability by integration. ## After Payment After payment, single page checkout behaves the same as the two-page flow. The customer sees the payment status page, then goes to your `return_url` with the same query parameters. If you set `redirect_immediately`, the customer goes to your `return_url` without the status page. Webhooks are the same. See the [Checkout Sessions guide](/developer-resources/checkout-session#request-body) for the query parameters. ## FAQ > [accordion] Why are Apple Pay and Google Pay in the payment method list instead of at the top? > > The session asks for more than the email before payment: a required phone number, a required tax ID, or a required custom field. The wallets then move into the list, so the customer fills in those fields first. See [Apple Pay and Google Pay](#apple-pay-and-google-pay). > [accordion] Why does a wallet button not show? > > Each wallet shows only when the customer's device and browser support it, for example Apple Pay on a device with a card in Apple Wallet. Wallet availability also depends on the integration. See [Digital Wallets](/features/payment-methods/digital-wallets). > [accordion] What happens if the customer opens the checkout in two tabs? > > The most recently opened tab holds the payment. The other tab shows "This checkout is open in another tab." with a **Continue in this tab** link. The customer clicks the link to pay from that tab instead. > [accordion] What does the customer see if the price changes when they press Pay? > > When the customer presses **Pay Now**, the page locks their details and shows "Your payment details are locked while this payment is processed." If the total changed since the page last priced the order, the page shows "The price changed. Check the total and try again." The customer checks the new total and presses **Pay Now** again. > [accordion] Can customers edit details I set on the session? > > Customer details, billing address, tax ID, and business name that you set on the session are locked, the same as in the two-page checkout. To let the customer change one, set the matching `allow_customer_editing_*` feature flag to `true`, for example `allow_customer_editing_country`. > [accordion] Does single page checkout change what the API returns? > > No. The create response, the payment and subscription objects, and the webhooks are the same as for a two-page checkout session. > [card] [Checkout Sessions Guide](/developer-resources/checkout-session) > > All checkout session fields and feature flags. > [card] [Payment Links](/developer-resources/integration-guide#payment-links) > > Query parameters for static payment links. > [card] [Design & Theme Customization](/features/design) > > Set checkout colors, fonts, and button text. > [card] [Digital Wallets](/features/payment-methods/digital-wallets) > > Apple Pay and Google Pay setup. # Storefront Source: https://docs.dodopayments.com/features/storefront Create a branded, mobile-friendly Dodo Payments store that lists your one-time payment and subscription products, with no website to build. ![Dodo Payments Storefront cover image](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/cover-images/Storefront.png?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=01a8c507034e9c40fd4bd7c2afd51226) A Storefront is a branded online store, hosted by Dodo Payments, where customers browse your one-time payment and subscription products and buy them through Dodo Payments checkout. You sell online without building or maintaining a website. ## Key Highlights of the Feature 1. **Branded Storefront** * Customize your store with a store name, logo, and banner. * Share your store URL, for example `store.dodopayments.com/your-store`. 2. **Product Segregation** * The store groups your products into a **Products** section for one-time payment products and a **Subscriptions** section. 3. **Simple Checkout Flow** * Customers select a product and quantity, then click **Buy now** to go to Dodo Payments checkout. 4. **Publish/Unpublish** * Choose which products appear on your store from the dashboard, where you can add or remove them at any time. 5. **No Extra Setup** * You don't need a separate CMS. You manage pricing, descriptions, and subscription details in the dashboard, and the store uses them. 6. **Mobile-Friendly** * The storefront layout is responsive, so it works on phones, tablets, and desktops. ## Store Front Setup To set up and manage your storefront, follow these steps. ![Storefront settings in the Dodo Payments dashboard with store name, URL, logo, banner, and product fields](https://mintcdn.com/dodopayments/5D2vY2CKcFOZLLyz/images/store-front/sf-1.png?fit=max\&auto=format\&n=5D2vY2CKcFOZLLyz\&q=85\&s=085dab26f05d5f0ea48cb31fd6e8e0f9) ### Accessing Your Storefront Settings 1. In the Dodo Payments dashboard, go to **Settings → Storefront**. ### Store Branding 1. **Store Name**: Enter the public name of your store. It appears at the top of your storefront. 2. **Store Logo**: Upload a square image of your brand logo. 3. **Store Banner**: Upload a 16:9 banner for the top of the storefront. The recommended size is 1920×1080. Keep your logo and key text centered, because wider screens crop the top and bottom. 4. **Store URL**: * Enter the slug for your store address, for example `store.dodopayments.com/my-store`. * The slug can contain only lowercase letters, numbers, and hyphens. You can change it later. 5. **Listed Products**: Select the products you want to show on your storefront. Logo and banner images can be PNG, JPG, JPEG, GIF, SVG, or WebP files of up to 5 MB. ### Saving & Viewing Your Store ![Storefront settings with the Publish button and the store preview](https://mintcdn.com/dodopayments/5D2vY2CKcFOZLLyz/images/store-front/sf-2.png?fit=max\&auto=format\&n=5D2vY2CKcFOZLLyz\&q=85\&s=b0b3e18d91f835b0812ee708ee7a8d8b) 1. **Click Publish**: Click **Publish** to save your storefront setup and the products you listed. 2. **Preview Store**: Preview your storefront at its URL, or click **Visit Store** to open it. 3. **Share URL**: Share the link with your customers by email, on social media, or on your website. ### Test Mode ![Storefront in test mode showing the test mode banner at the top of the page](https://mintcdn.com/dodopayments/5D2vY2CKcFOZLLyz/images/store-front/sf-3.png?fit=max\&auto=format\&n=5D2vY2CKcFOZLLyz\&q=85\&s=01545a337bee2e0d3914af1712d0710c) Test mode and live mode have separate storefronts. A storefront you create in test mode shows a test mode banner at the top of the page. Use test mode to try the browsing and purchase flow yourself. To take real payments, share the live mode store link with your customers. When you're happy with how your store looks in test mode, you can copy the design and storefront branding to live mode instead of rebuilding them. See [Copy Design From Test to Live Mode](/features/design#copy-design-from-test-to-live-mode). ## Customer Experience ![Customer view of a storefront with the store banner, logo, and product cards](https://mintcdn.com/dodopayments/5D2vY2CKcFOZLLyz/images/store-front/sf-4.png?fit=max\&auto=format\&n=5D2vY2CKcFOZLLyz\&q=85\&s=4acd4e306ff344645e8cb218fd6876e8) ### Landing on the Storefront * **Visual Branding**: Customers see your store name, logo, and banner first. * **Organized Products**: Products appear in two sections: **Products** for one-time payments and **Subscriptions**. ### Browsing Products * **Product Cards**: Each card shows the product name, description, and price. To read the description, customers click the **i** icon on the bottom right of the card. * **Quantity Selection**: Customers choose how many items to buy. * **Subscription Frequency & Trial**: Subscription cards show the billing frequency, for example monthly, and any free trial, for example a 7-day trial. ![Product card on a storefront with the quantity selector and the Buy now button](https://mintcdn.com/dodopayments/5D2vY2CKcFOZLLyz/images/store-front/sf-5.png?fit=max\&auto=format\&n=5D2vY2CKcFOZLLyz\&q=85\&s=38357ae5c9893b01d684a01eb1c106d4) ### Buying Process 1. **Select Buy Now**: The customer clicks **Purchase** on a product, selects the quantity, and clicks **Buy now**. 2. **Redirect to Dodo Payments Checkout**: The customer goes to Dodo Payments checkout and completes the secure checkout flow there. 3. **Confirmation**: After a successful payment, Dodo Payments shows a confirmation. Storefront checkout links don't include a redirect URL, so you can't send storefront customers to your own "Thank You" page. > [card] [Design & Theme Customization](/features/design) > > Customize your storefront's appearance with pre-built themes, typography, colors, and a live preview on the Design page. # Subscriptions Source: https://docs.dodopayments.com/features/subscription Recurring billing for SaaS, memberships, and services. Flexible cycles, trials, proration, add-ons, and on-demand charges. > [!NOTE] > > Subscriptions automate recurring revenue. Create flexible billing cycles, free or paid trials, plan changes with proration, and add-ons. Customers renew automatically until they cancel or the term ends. > [card] [Upgrade & Downgrade](/developer-resources/subscription-upgrade-downgrade) > > Control plan changes with proration and quantity updates. > [card] [On‑Demand Subscriptions](/developer-resources/ondemand-subscriptions) > > Authorize a mandate now and charge later with custom amounts. > [card] [Customer Portal](/features/customer-portal) > > Let customers manage plans, billing, and cancellations. > [card] [Subscription Webhooks](/developer-resources/webhooks/intents/subscription) > > React to lifecycle events like created, renewed, and canceled. ## What Are Subscriptions? A subscription is a recurring product that charges customers on a schedule. Ideal for SaaS, memberships, digital content, and support plans. * **SaaS licenses**: Apps, APIs, or platform access * **Memberships**: Communities, programs, or clubs * **Digital content**: Courses, media, or premium content * **Support plans**: SLAs, success packages, or maintenance ## Key Benefits * **Predictable revenue**: Recurring billing with automated renewals * **Flexible cycles**: Monthly, annual, custom intervals, and trials * **Plan agility**: Proration for upgrades and downgrades * **Add-ons and seats**: Attach optional, quantifiable upgrades * **Hosted checkout**: Checkout pages and Customer Portal * **Developer-first**: Clear APIs for creation, changes, and usage tracking ## Creating Subscriptions Create subscription products in your Dodo Payments dashboard, then sell them through checkout or your API. Separating products from active subscriptions lets you version pricing, attach add-ons, and track performance independently. ### Subscription Product Creation Configure the fields in the dashboard to define how your subscription sells, renews, and bills. The sections below map directly to what you see in the creation form. #### Product Details * **Product Name** (required): The display name shown in checkout, customer portal, and invoices. * **Product Description** (optional): A clear value statement that appears in checkout and invoices. * **Product Image** (optional): PNG/JPG/WebP up to 3 MB. Used on checkout and invoices. * **Brand**: Associate the product with a specific brand for theming and emails. * **Tax Category** (required): Choose the category (for example, SaaS) to determine tax rules. > [!TIP] > > Pick the most accurate tax category to ensure correct tax collection per region. #### Pricing * **Pricing Type**: Choose **Subscription** (this guide). Alternatives are Single Payment and Usage Based Billing. * **Price** (required): Base recurring price with currency. A non-zero price must meet the subscription minimum for the currency the customer pays in: **\$1.00** for USD. In currencies other than USD, EUR, and GBP, the price must also be worth at least \$1.00. For example, an AED subscription needs about 3.70 AED, not the listed 2.00 AED minimum. EUR and GBP use their own listed minimums. See [Minimum Amounts](/features/adaptive-currency#minimum-amounts). Amounts below the minimum are not supported. A price of exactly **\$0** is a separate, supported case; see [Card-Optional at Zero Price](#card-optional-at-zero-price). * **Discount Applicable (%)**: Optional percentage discount applied to the base price; reflected in checkout and invoices. You can enter up to two decimal places, such as `10.5`. In the API, use `discount_bps` (basis points, so `1050` is 10.5%). * **Repeat payment every** (required): Interval for renewals, e.g., every 1 Month. Select the cadence (months or years) and quantity. * **Subscription Period** (required): Total term for which the subscription remains active (e.g., 20 Years). After this period ends, renewals stop unless extended. > [!WARNING] > > `subscription_period` sets when the subscription expires, not how often it charges. If the subscription period equals the payment frequency (for example, both 1 month), the subscription expires after a single charge instead of renewing. For a subscription that renews until the customer cancels it, set the period to 20 years. This is the recommended value and also the maximum. * **Trial Period Days** (required): Set trial length in days. Use 0 to disable trials. The first charge occurs automatically when the trial ends. * **Trial Amount**: Optional upfront charge for a paid trial. Leave it unset for a free trial. See [Paid Trials](#paid-trials). * **Card-optional at \$0 Price**: Let customers start the subscription without adding a card when a \$0 price or a discount leaves nothing due today. A free trial has its own **Start the trial without a card** checkbox. See [Card-Optional at Zero Price](#card-optional-at-zero-price). * **Select add-on**: Attach up to 10 add-ons that customers can purchase alongside the base plan. ```typescript ❌ Wrong — expires after 1 charge theme={null} // subscription_period equals payment_frequency → expires after 1 month const product = await client.products.create({ name: "Pro Plan", tax_category: "saas", price: { type: "recurring_price", currency: "USD", price: 2900, payment_frequency_count: 1, payment_frequency_interval: "Month", subscription_period_count: 1, // ❌ Same as payment frequency → expires after 1 charge subscription_period_interval: "Month", }, }); ``` ```typescript ✅ Correct — renews monthly for up to 20 years theme={null} // subscription_period much longer than payment_frequency → renews each month const product = await client.products.create({ name: "Pro Plan", tax_category: "saas", price: { type: "recurring_price", currency: "USD", price: 2900, payment_frequency_count: 1, payment_frequency_interval: "Month", subscription_period_count: 20, // ✅ 20-year term (recommended maximum), charged monthly subscription_period_interval: "Year", }, }); ``` > [!WARNING] > > Editing the price of an active product changes what **new** customers pay. Existing subscriptions are never repriced — each one keeps the price it was created with and renews at that price for as long as it stays active. > > To move an existing subscriber onto a different price, change their plan explicitly with [Change Plan](/api-reference/subscriptions/change-plan), or let them switch through the [Customer Portal](/features/customer-portal) if you have enabled self-service plan changes. Your proration settings apply to that plan change, not to product price edits. > [!NOTE] > > Add-ons are ideal for quantifiable extras such as seats or storage. You can control allowed quantities and proration behavior when customers change them. #### Advanced Settings * **Tax Inclusive Pricing**: Display prices inclusive of applicable taxes. Final tax calculation still varies by customer location. * **License key** (in **Entitlements**): Issue a unique key to each customer after purchase. See the [License Keys](/features/license-keys) guide. * **Digital Files** (in **Entitlements**): Deliver files or content automatically after purchase. Learn more in [Digital Product Delivery](/features/digital-product-delivery). * **Metadata**: Attach custom key–value pairs for internal tagging or client integrations. See [Metadata](/api-reference/metadata). > [!TIP] > > Use metadata to store identifiers from your system (e.g., accountId) so you can reconcile events and invoices later. ## Subscription Trials Trials let customers evaluate a subscription before paying the full recurring price. A trial can be free (no charge until it ends) or paid (a reduced amount charged upfront). After the trial, the full price charges at the first renewal. ### Configuring Trials Set **Trial Period Days** in the product's pricing section (use `0` to disable). To override it for one customer, set `subscription_data.trial_period_days` on the checkout session: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_monthly', quantity: 1 }], customer: { customer_id: 'cus_123' }, subscription_data: { trial_period_days: 14 } }); ``` > [!WARNING] > > `trial_period_days` must be between 0 and 10,000 days. ### Paid Trials Charge a reduced amount upfront for the trial window. Set **Trial Amount** on the product's price. The full recurring price charges at the first renewal. ![Subscription pricing form with a trial duration and an optional trial amount for a paid trial](https://mintcdn.com/dodopayments/xWy-mQaJKoU2V22s/images/subscriptions/paid-trials.png?fit=max\&auto=format\&n=xWy-mQaJKoU2V22s\&q=85\&s=e7d6749e11cc3f8bfa45906d970fd606) Paid trials are configured on the product's price, not per subscription or per checkout session: | Field | Type | Description | | - | - | - | | `trial_amount` | integer | Amount charged today for the trial, in the price currency's minor units (for example, `500` for \$5.00). Requires `trial_period_days > 0`. Omit or set to `null` for a free trial. | | `trial_apply_discounts` | boolean | Whether checkout discount codes reduce the trial charge. Defaults to `false`, so the trial amount is charged in full even when a discount applies to the recurring price. | ```typescript theme={null} const product = await client.products.create({ name: 'Pro Plan', tax_category: 'saas', price: { type: 'recurring_price', price: 2900, // $29.00 per month after the trial currency: 'USD', discount_bps: 0, purchasing_power_parity: false, payment_frequency_count: 1, payment_frequency_interval: 'Month', subscription_period_count: 20, subscription_period_interval: 'Year', // 20-year term — the recommended value for ongoing plans trial_period_days: 14, trial_amount: 500, // $5.00 charged today trial_apply_discounts: false } }); ``` The trial amount is taxed and included in checkout calculations and payment link pricing. Adaptive Currency markup applies per currency. The [preview endpoint](/developer-resources/checkout-session) returns `trial_amount` and `trial_period_days` so you can show the amount due today before creating the subscription. ### Card-Optional at Zero Price Let customers start a subscription without adding a payment method when nothing is due today. Enable it per price in the product's pricing section, with one checkbox for each case below. ![Subscription pricing form with the Card-Optional at \$0 Price checkbox next to Trial Period and Default Discount](https://mintcdn.com/dodopayments/qD0RSXoLZULfSVwD/images/subscriptions/card-optional-at-zero-price-pricing.png?fit=max\&auto=format\&n=qD0RSXoLZULfSVwD\&q=85\&s=d76357fda744c461e140675834f25e7b) Nothing due today happens in two cases: * **A free trial**: `trial_period_days` is set with no `trial_amount`, so the first charge is \$0 while the trial runs. Check **Start the trial without a card** under **Trial Period (Days)**. * **A \$0 recurring price**: Either the price itself is \$0, or a discount brings it to \$0 (the product's **Default Discount (%)** or a [discount code](/features/discount-codes) stacked at checkout). Check **Card-optional at \$0 Price**. > [!WARNING] > > A [paid trial](#paid-trials) always requires a card. Setting a **Trial Amount** means something is due, so the card requirement stays on. > [!NOTE] > > Each checkbox maps to its own API field: `trial_payment_method_optional` (free trial case) and `zero_amount_payment_method_optional` (\$0 price case). You can enable either one on its own. #### What Happens Without a Card A card-optional subscription is created and activated immediately with no payment method on file. The [checkout session preview](/api-reference/checkout-sessions/preview) returns `payment_method_required: false` for such a cart, and the subscription object shows `has_payment_method: false`. Then: 1. **A reminder email goes out before billing starts.** The number of days is set in **Settings → Subscriptions → Payment Method Reminder** (see [Subscription Settings](/features/product-collections#subscription-settings)). The **Add Payment Method Reminder** email (see [Customer Emails](/features/communication-preferences#customer-emails)) links the customer to the Customer Portal to add a card. 2. **If no card is added in time, the subscription goes `on_hold`** when the trial ends or the discounted period runs out and a real charge is due. The customer receives the **Subscription On Hold, No Payment Method** email. 3. **Adding a payment method reactivates the subscription** (see [Reactivating from On Hold](#reactivating-from-on-hold)). A charge is created for the amount now due, and the subscription returns to `active` on success. ![Subscriptions settings tab showing the Payment Method Reminder days field](https://mintcdn.com/dodopayments/qD0RSXoLZULfSVwD/images/subscriptions/payment-method-reminder-settings.png?fit=max\&auto=format\&n=qD0RSXoLZULfSVwD\&q=85\&s=ee3b0b8db635b28ab8cb8f0dd1f1da7d) > [!NOTE] > > A card added before the trial or discounted period ends prevents the hold. The next renewal charges that card. ### Preventing Trial Misuse Stop customers from repeatedly claiming trials of the same product. When enabled, a customer who has already redeemed a trial of a product gets a paid subscription instead of a fresh trial of that product. ![Prevent Trial Misuse toggle in the Subscriptions settings tab](https://mintcdn.com/dodopayments/xWy-mQaJKoU2V22s/images/subscriptions/prevent-trial-misuse.png?fit=max\&auto=format\&n=xWy-mQaJKoU2V22s\&q=85\&s=954fb3e74985d71017cbfc18fbf09e04) Enable it from **Settings → Subscriptions**. Once enabled: * Customers are matched by normalized email (plus-aliases stripped), so `user+trial@example.com` and `user@example.com` count as the same person. * Redemptions are recorded at trial activation, so a customer who cancels the same day has still consumed their trial. * Existing customers are backfilled from historical trials by email, so past trial users are recognized immediately. * Passing `trial_period_days` explicitly on a checkout session or subscription skips the check and grants that trial. > [!NOTE] > > Off by default. See [Subscription Settings](/features/product-collections#subscription-settings) for all business-level subscription controls. ### Detecting Trial Status The subscription object has no trial status field. For a free trial, retrieve the subscription's payments: if there is exactly one payment with a `total_amount` of 0, the subscription is in trial. This check doesn't work for paid trials, where the first payment is the `trial_amount`. ```typescript theme={null} const subscription = await client.subscriptions.retrieve('sub_123'); const payments = await client.payments.list({ subscription_id: subscription.subscription_id }); const isInTrial = payments.items.length === 1 && payments.items[0].total_amount === 0; ``` > [!WARNING] > > This check only works for free trials. For a [paid trial](#paid-trials), the first payment equals the trial amount. Compare the first payment against the subscription's `trial_amount`, or check whether `next_billing_date` is still within the trial window. ### Updating Trial Period Extend the trial by updating `next_billing_date`: ```typescript theme={null} await client.subscriptions.update('sub_123', { next_billing_date: '2025-02-15T00:00:00Z' // New trial end date }); ``` > [!WARNING] > > You cannot set `next_billing_date` to a past time. The date must be in the future. ## Subscription Plan Changes Upgrade or downgrade subscriptions, adjust quantities, or migrate to different products. Proration mode controls whether the change triggers an immediate charge, creates credit, or applies no billing adjustment. You can change plans and update the next billing date from the dashboard, or change plans with the API. To let customers change plans themselves, add subscription products to a Product Collection and enable **Allow Subscription Updates** in **Settings → Subscriptions**. ```mermaid theme={null} sequenceDiagram participant C as Customer participant A as Your App participant D as Dodo Payments C->>A: Request plan change A->>D: Preview change (optional) D-->>A: Charge breakdown A->>C: Show cost C->>A: Confirm A->>D: changePlan API D->>D: Prorate & charge D-->>A: Result D->>A: Webhook: plan_changed A->>C: Access updated ``` > [card] [Product Collections](/features/product-collections) > > Group related products to enable upgrade/downgrade paths in the Customer Portal. ### Proration Modes Choose how customers are billed when changing plans: | Mode | Upgrade | Downgrade | Billing Cycle | Best For | | - | - | - | - | - | | `prorated_immediately` | Credit unused time, charge full new cycle | Credit unused time, charge full new cycle | Resets to today | Fair time-based billing | | `prorated_immediately_keep_cycle` | Charge price difference for the time left | Credit price difference for the time left | Stays the same | Mid-cycle changes on a fixed billing date | | `difference_immediately` | Charge price difference | Credit price difference | Resets to today | Simple tier changes | | `full_immediately` | Charge full new plan price | Charge full new plan price | Resets to today | Billing cycle resets | | `do_not_bill` | Switch immediately, no charge | Switch immediately, no charge | Stays the same | Free migrations | #### `prorated_immediately` Credits the unused portion of the current billing cycle, then charges a full cycle at the new plan. The new plan is never charged at a fraction of its price. Net immediate charge = (full new cycle) minus (remaining fraction × full old cycle). If the credit exceeds the new cycle charge, the difference is held as subscription-scoped credit for future renewals. The billing cycle re-anchors to the change date. ```typescript theme={null} await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_pro', quantity: 1, proration_billing_mode: 'prorated_immediately' }); ``` #### `prorated_immediately_keep_cycle` Charges the price difference for the time left in the current billing cycle. The next billing date does not change, and the new plan price applies from that date. Net immediate charge = (new plan price − old plan price) × remaining fraction of the cycle. A downgrade gives a credit for the same amount. The credit goes to the [customer wallet](/features/customer-wallet) and offsets later charges. ```typescript theme={null} await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_pro', quantity: 1, proration_billing_mode: 'prorated_immediately_keep_cycle' }); ``` > [!WARNING] > > This mode needs `effective_at: 'immediately'`. A change to a plan with a shorter billing interval returns `422`. A change to a plan with a longer billing interval runs as `prorated_immediately` and resets the billing date. See the [Upgrade & Downgrade Guide](/developer-resources/subscription-upgrade-downgrade#prorated_immediately_keep_cycle) for all rules. #### `difference_immediately` Charges the price difference immediately (upgrade) or adds credit for future renewals (downgrade). ```typescript theme={null} // Upgrade: charges $50 (difference between $30 and $80) // Downgrade: credits the price difference, auto-applied to renewals await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_pro', quantity: 1, proration_billing_mode: 'difference_immediately' }); ``` > [!NOTE] > > Credits from downgrades are subscription-scoped and auto-applied to future renewals. They're distinct from [Credit-Based Billing](/features/credit-based-billing) entitlements. When a customer downgrades with `difference_immediately`, the unused value becomes a subscription-scoped credit that automatically offsets future renewals: ```mermaid theme={null} flowchart LR A[Downgrade] --> B[Calculate Credit] B --> C[Credit Added] C --> D[Next Renewal] D --> E{Credit Left?} E -->|Yes| F[Apply to invoice] F --> D E -->|No| G[Full price charged] ``` #### `full_immediately` Charges the full new plan amount immediately, ignoring remaining time. Best for resetting billing cycles. ```typescript theme={null} await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_monthly', quantity: 1, proration_billing_mode: 'full_immediately' }); ``` #### `do_not_bill` Switches to the new plan immediately without any billing adjustment. No charges, no credits. The new plan is active as soon as the call succeeds but is not charged until the next renewal. The customer keeps the upgraded plan free for the rest of the current cycle. The original renewal date is preserved, and the new plan price applies at that renewal. ```typescript theme={null} await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_new_plan', quantity: 1, proration_billing_mode: 'do_not_bill' }); ``` > [accordion] Example: Prorated upgrade calculation > > **Scenario**: Customer on Basic (\$30/month) upgrades to Pro (\$80/month) on day 16 of a 30-day cycle using `prorated_immediately`. > > ``` > Credit for unused time on Basic = $30 × (15 remaining / 30 total) = $15.00 > Full cycle of Pro = $80.00 (never prorated) > ──────────────────────────────────────────────────────────────────── > Immediate charge = $80.00 − $15.00 = $65.00 > ``` > > The customer starts a full new month of Pro today, so Pro is charged in full and only the unused time on Basic is credited. > > Next renewal on **February 15** (January 16 + 30 days): **\$80.00/month**. > > > [!TIP] > > > > For more detailed calculation examples and edge cases, see our full [Upgrade & Downgrade Guide](/developer-resources/subscription-upgrade-downgrade). > [accordion] Example: Prorated upgrade that keeps the billing date > > **Scenario**: Customer on Basic (\$30/month) upgrades to Pro (\$80/month) on day 16 of a 30-day cycle (January 1 to January 31) using `prorated_immediately_keep_cycle`. > > ``` > Price difference = $80.00 − $30.00 = $50.00 > Time left = 15 remaining / 30 total > ──────────────────────────────────────────── > Immediate charge = $50.00 × (15 / 30) = $25.00 > ``` > > The billing date does not change. Next renewal on **January 31**: **\$80.00/month**. > [accordion] Example: Downgrade credit calculation > > **Scenario**: Customer on Pro (\$80/month) downgrades to Starter (\$20/month) using `difference_immediately`. > > ``` > Credit = Old plan − New plan = $80 − $20 = $60.00 > ``` > > The \$60 credit auto-applies to future renewals: > > * Renewal 1: \$20 − \$20 (credit) = **\$0.00** (\$40 credit remaining) > > * Renewal 2: \$20 − \$20 (credit) = **\$0.00** (\$20 credit remaining) > > * Renewal 3: \$20 − \$20 (credit) = **\$0.00** (credit exhausted) > > * Renewal 4: **\$20.00** (full price) > > > [!NOTE] > > > > Learn more about how credits are managed in the [Upgrade & Downgrade Guide](/developer-resources/subscription-upgrade-downgrade). ### Changing Plans with Add-ons Modify add-ons when changing plans. Add-ons are included in proration calculations: ```typescript theme={null} await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_pro', quantity: 1, proration_billing_mode: 'difference_immediately', addons: [{ addon_id: 'addon_extra_seats', quantity: 2 }] // addons: [] // Empty array removes all existing add-ons }); ``` > [!NOTE] > > By default (`effective_at: 'immediately'`) plan changes trigger immediate charges. Pass `effective_at: 'next_billing_date'` to schedule the change for the next billing date instead — the pending change is returned on the subscription as `scheduled_change`, and you can cancel it with [Cancel Scheduled Plan Change](/api-reference/subscriptions/cancel-change-plan). Failed charges may move the subscription to `on_hold` status, unless you pass `on_payment_failure: 'prevent_change'`, which keeps the subscription on its current plan until payment succeeds. Track changes via `subscription.plan_changed` webhook events. Plan changes are rejected while a subscription is `past_due` — see [Grace Period](#grace-period). ### Previewing Plan Changes Preview the exact charge before committing: ```typescript theme={null} const preview = await client.subscriptions.previewChangePlan('sub_123', { product_id: 'pdt_pro', quantity: 1, proration_billing_mode: 'prorated_immediately' }); console.log('You will be charged:', preview.immediate_charge.summary.total_amount, preview.immediate_charge.summary.currency); ``` > [card] [Preview Change Plan API](/api-reference/subscriptions/preview-change-plan) > > Preview plan changes before committing. ## Pausing and Resuming Subscriptions Pause a subscription to freeze it instead of ending it. Billing stops, access is revoked, and the subscription keeps its plan and history. Use it as a retention alternative to cancellation. Open any active subscription under **Sales → Subscriptions** and click **Pause subscription**. The status changes to `paused` and renewals stop until resumed. ![Subscription details page in the dashboard showing the Update, Pause subscription, and Cancel Subscription buttons](https://mintcdn.com/dodopayments/JB6sccx0km6wps_z/images/subscriptions/pause-subscription-dashboard.png?fit=max\&auto=format\&n=JB6sccx0km6wps_z\&q=85\&s=c0e9a0f99d941d703f97b8c694f1f8d7) ### What Happens When You Pause * **Renewals stop.** No invoice is generated and no renewal charge is attempted while paused. * **Access is revoked immediately.** Pausing revokes every delivered and pending [entitlement grant](/features/entitlements/introduction), which disables [license keys](/features/license-keys) and stops new [digital product](/features/digital-product-delivery) download URLs. Resuming re-grants them. * **The billing clock freezes.** `next_billing_date` and `expires_at` both move forward by the exact length of the pause, so the customer keeps the time they already paid for. * **No pause duration limit.** A paused subscription stays paused until resumed. You don't set a pause length upfront. > [!WARNING] > > Pausing revokes access immediately, not at the end of the billing period. Make that clear to the customer before they confirm. Resuming returns the subscription to `active` and restores entitlements. Because the clock was frozen, the next renewal lands the paused duration later than originally scheduled. ### Pausing Usage-Based Subscriptions A [usage-based](/features/usage-based-billing/introduction) subscription can have usage recorded but not yet billed when paused. **Bill Usage at Pause** under **Settings → Subscriptions** controls what happens: | Setting | Behavior | | - | - | | **On** (default) | Dodo Payments raises an invoice for accrued usage since the last billing date and collects it immediately. | | **Off** | Owed usage is carried forward and billed on the next regular invoice. | Only metered usage is settled this way. The recurring base fee is never charged at pause time. Standard and on-demand subscriptions have nothing to settle. > [!NOTE] > > **Bill Usage at Pause** is recorded per billing cycle. Changing it mid-cycle doesn't affect the cycle already in progress; the new value applies from the next cycle onward. > [!WARNING] > > The settlement invoice is collected like any other invoice, so it can fail. If it goes unpaid past the [dunning](/features/recovery/subscription-dunning) grace period, the subscription moves to `on_hold` while remaining flagged as paused. A subscription in that state has two exits: | Exit | Result | | - | - | | The settlement invoice is paid | The subscription returns to `paused`, not `active`. Resume it explicitly when the customer is ready. | | You resume it directly | The subscription goes straight to `active` and the unpaid settlement invoice is voided, along with its pending retries. The owed usage is written off. | > [!NOTE] > > Resuming is a valid exit from this hold. You don't have to collect the settlement invoice first. Resuming forgives the outstanding usage rather than deferring it. ### Letting Customers Pause Their Own Subscriptions **Allow Subscription Pause** under **Settings → Subscriptions** controls whether customers can pause and resume from the Customer Portal. Off by default, so self-service pause is opt-in. ![Subscriptions settings tab showing the Allow Subscription Pause and Bill Usage at Pause toggles](https://mintcdn.com/dodopayments/JB6sccx0km6wps_z/images/subscriptions/subscription-pause-settings.png?fit=max\&auto=format\&n=JB6sccx0km6wps_z\&q=85\&s=dd01b98a8ce2444bc387b1614ac73e42) This setting only governs the Customer Portal. You can always pause and resume from the dashboard or the API. Turning it off stops new customer pauses, but doesn't trap a customer who is already paused. They can still resume a pause they started. Pauses you started stay under your control. > [card] [Pausing from the Customer Portal](/features/customer-portal#pausing-a-subscription) > > See what the customer sees, including the confirmation dialog. ### Pausing via API Pause and resume run through the `status` field on the update subscription endpoint: ```typescript theme={null} // Pause await client.subscriptions.update('sub_123', { status: 'paused' }); // Resume await client.subscriptions.update('sub_123', { status: 'active' }); ``` > [!WARNING] > > Send `paused` or `active` on its own. Combining either with any other field is rejected with `422`. The older boolean `pause` field is removed and always fails with `422`, so a caller still on it gets a loud error instead of a silent no-op. Pausing emits `subscription.paused` and resuming emits `subscription.unpaused`. Both carry the full subscription object, with `paused_at` set while paused and `null` once resumed. ### Pause and Other Subscription Actions * **Cancellation still works.** You can cancel a paused subscription exactly as you would an active one. Any open settlement invoice from the pause is voided. * **Scheduled plan changes are delayed, not dropped.** A [plan change](#subscription-plan-changes) scheduled for the next billing date sits untouched while paused, then applies at the shifted billing date once resumed. Its `scheduled_change.effective_at` is a snapshot from when it was scheduled and is not adjusted for the pause. To drop the change, use [Cancel Scheduled Plan Change](/api-reference/subscriptions/cancel-change-plan). ## Subscription States A subscription moves through defined statuses over its lifetime: | Status | Meaning | Recoverable? | Recovery | | - | - | - | - | | `pending` | Being created or processed | — | Wait for `subscription.active` or `subscription.failed` | | `active` | Active and will renew automatically | — | No action needed | | `past_due` | Renewal payment failed and [grace period](#grace-period) is open; customer keeps full access | **Yes** | Settle renewal debt before deadline (see [Grace Period](#grace-period)) | | `on_hold` | Renewal or plan-change charge failed; renewals stopped, access revoked | **Yes** | Recover automatically via [Payment Retries](/features/recovery/payment-retries) and [Dunning](/features/recovery/subscription-dunning), or update the payment method (see [Reactivating from On Hold](#reactivating-from-on-hold)) | | `paused` | Deliberately paused by you or customer; billing frozen, access revoked | **Yes** | Resume with `status: active` or from Customer Portal (see [Pausing and Resuming Subscriptions](#pausing-and-resuming-subscriptions)) | | `cancelled` | Cancelled and will not renew | Re-purchase only | Customer must start a new subscription; [Dunning](/features/recovery/subscription-dunning) can prompt a re-purchase | | `failed` | Creation failed (initial mandate or payment did not succeed) | **No — terminal** | Customer must create a new subscription with a working payment method | | `expired` | Reached the end of its term | — | Customer must start a new subscription if desired | > [!WARNING] > > `on_hold` and `failed` are often confused. `on_hold` is recoverable for an already-active subscription whose renewal failed. `failed` is terminal and only occurs when initial subscription creation fails. > [!NOTE] > > `past_due` and `on_hold` are both involuntary but differ in one way: `past_due` keeps the customer's access, `on_hold` removes it. A subscription reaches `past_due` only when you enable a [grace period](#grace-period). Without one, a failed renewal goes straight to `on_hold`. > [!NOTE] > > `on_hold` and `paused` are distinct. `on_hold` is involuntary (payment failed). `paused` is deliberate (you or the customer chose to freeze it). A usage-based subscription can still owe a settlement invoice at the moment it is paused (see [Pausing Usage-Based Subscriptions](#pausing-usage-based-subscriptions)). ### State Machine ```mermaid theme={null} stateDiagram-v2 [*] --> pending pending --> active: Creation succeeds pending --> failed: Mandate creation fails active --> on_hold: Renewal fails (no grace period), or plan-change charge fails active --> past_due: Renewal fails and a grace period is set past_due --> active: Renewal debt settled past_due --> on_hold: Grace period ends (on_hold) past_due --> cancelled: Grace period ends (cancel_subscription) past_due --> cancelled: Cancelled on_hold --> active: Payment method updated / retry succeeds active --> paused: Paused paused --> active: Resumed paused --> on_hold: Pause settlement invoice unpaid (usage-based) on_hold --> paused: Pause settlement invoice paid active --> cancelled: Cancelled on_hold --> cancelled: Cancelled paused --> cancelled: Cancelled active --> expired: Term ends failed --> [*] cancelled --> [*] expired --> [*] ``` ### On Hold State A subscription enters `on_hold` when: * A renewal payment fails (insufficient funds, expired card, etc.) * A plan change charge fails * Payment method authorization fails * A [pause settlement invoice](#pausing-usage-based-subscriptions) for a usage-based subscription goes unpaid * A [grace period](#grace-period) ends with renewal debt unpaid and expiry action is `on_hold` * A [Card-Optional at Zero Price](#card-optional-at-zero-price) subscription's free trial or \$0 period ends with no payment method ever added > [!NOTE] > > If you set a grace period, a failed renewal moves the subscription to `past_due` first. It reaches `on_hold` only when the window ends. Some payment methods report the result of a renewal payment after some days. While a renewal payment by one of these methods is in `processing`, Dodo Payments waits for the result and keeps the subscription `active`. The table gives the maximum wait after Dodo Payments creates the payment: | Payment method | API method type | Maximum wait | | - | - | - | | UPI | `upi_collect`, `upi_intent` | 3 days | | Pix | `pix` | 8 days | The 3 days for UPI are more than the [48-hour processing delay](#48-hour-processing-delay) of UPI renewals. If the payment fails, the subscription moves to `on_hold`, or to `past_due` if you set a grace period. If the payment is still in `processing` after the maximum wait, the subscription moves to `on_hold`. If you set a grace period, the subscription stays `active` until the next billing date, and then moves to `past_due`. A renewal payment can still succeed after the subscription moved to `on_hold` or `past_due`. When it does and no renewal invoice is left unpaid, the subscription returns to `active` on its own. The `next_billing_date` does not change. > [!WARNING] > > When a subscription is in `on_hold`, it will not renew automatically. Unless a late renewal payment succeeds, you must update the payment method to reactivate it. ### Reactivating from On Hold Update the payment method to reactivate a subscription from `on_hold`. This automatically: 1. Creates a charge for remaining dues 2. Generates an invoice 3. Processes the payment using the new payment method 4. Reactivates the subscription to `active` on successful payment > [!NOTE] > > The one exception is a hold caused by an unpaid pause settlement invoice. Clearing that invoice returns the subscription to `paused`, not `active`, because pause is where it was before the payment failed. Resume it explicitly once the invoice is settled. ```typescript theme={null} const response = await client.subscriptions.updatePaymentMethod('sub_123', { payment_method: { type: 'new', return_url: 'https://example.com/return' } }); if (response.payment_id) { console.log('Charge created:', response.payment_id); // Redirect customer to response.payment_link to complete payment // Monitor webhooks for payment.succeeded and subscription.active } ``` > [!NOTE] > > After successfully updating the payment method for an `on_hold` subscription, you'll receive `payment.succeeded` followed by `subscription.active` webhook events. If the customer cannot pay the renewal price, you can change the plan of the `on_hold` subscription instead. Dodo Payments voids the unpaid renewal invoice and charges the new plan to the saved payment method. The subscription becomes `active` when that invoice is paid. See [Change Plan on an On-Hold Subscription](/developer-resources/subscription-upgrade-downgrade#change-plan-on-an-on-hold-subscription). ### Grace Period A grace period is a window between a failed renewal and loss of access. The subscription moves to `past_due` instead of `on_hold`, and the customer keeps everything they bought until the window ends. This gives them time to fix a card without losing your product. Off by default. Enable one from **Settings → Subscriptions → Subscription Grace Period**. ![Subscription settings tab showing the Subscription Grace Period toggle, the number of days field, and the status after the grace period](https://mintcdn.com/dodopayments/S2k6LKmgHYlRKci9/images/subscriptions/subscription-grace-period-settings.png?fit=max\&auto=format\&n=S2k6LKmgHYlRKci9\&q=85\&s=4c506116408f7c800bdd13d7561db86c) #### Settings | Setting | Values | Description | | - | - | - | | Subscription Grace Period | on / off | Enable grace period for the business. Off by default. | | Number of days of grace period | 1 to 30 days | Window length. Default is 3 days. | | Status of subscription after grace period | `on_hold` or `cancel_subscription` | What happens when the window ends unpaid. | #### What Happens During the Window While a subscription is `past_due`: * The customer keeps access. Entitlement grants, license keys, and digital product downloads all stay live. * Usage-based billing keeps recording usage. * The subscription does not renew. * The subscription cannot be paused. * [Dunning](/features/recovery/subscription-dunning) emails go out, and [payment retries](/features/recovery/payment-retries) continue. * `subscription.past_due` is emitted at entry. The `subscription.past_due` webhook carries the deadline as `past_due_ends_at`. Store it when the event arrives — the subscription API does not return this field. Every subscription webhook while the window is open carries the same value, next to a `status` of `past_due`. > [!NOTE] > > The window is fixed when the subscription enters it. If you change the length or expiry action later, a window already open keeps its original values. New values apply to the next subscription that enters a window. #### Recovery The window closes when the renewal debt is settled through a successful retry or when the customer updates the payment method. The subscription returns to `active`, and a `subscription.active` webhook is sent. Only the failed renewal opens a window. An unrelated merchant charge that goes unpaid does not move a subscription to `past_due`. #### When the Window Ends If the renewal debt is still unpaid at the deadline, the subscription moves to `on_hold` or to `cancelled`, as you configured. At the same time: * A scheduled plan change on the subscription is cancelled. * A pending plan change whose invoice is still unpaid is cancelled. If the expiry action is `cancel_subscription`, open invoices are also voided, and their payment retries stop. > [!NOTE] > > A pending plan change whose invoice was paid is applied while the window is still open, not at the deadline. A paid invoice settles the change whatever the subscription status. > [!WARNING] > > Plan changes are rejected while a subscription is `past_due`. Settle the renewal debt first. ### Webhook Events by Transition Each transition emits a webhook so you can drive entitlement logic without polling: | Transition | Event | | - | - | | Subscription activated | `subscription.active` | | Renewal succeeds | `subscription.renewed` | | Renewal fails, grace period opens | `subscription.past_due` | | Renewal fails → on hold | `subscription.on_hold` | | Subscription paused | `subscription.paused` | | Paused subscription resumed | `subscription.unpaused` | | Creation fails | `subscription.failed` | | Plan upgraded/downgraded | `subscription.plan_changed` | | Cancelled | `subscription.cancelled` | | Term ended | `subscription.expired` | | Any field changes | `subscription.updated` | > [card] [Subscription Webhook Payloads](/developer-resources/webhooks/intents/subscription) > > View the full payload schema for subscription lifecycle events. ## API Management > [accordion] Create subscriptions > > Use `POST /checkouts` to create subscriptions programmatically from products, with optional trials (`subscription_data.trial_period_days`) and add-ons (`product_cart[].addons`). > > > [!WARNING] > > > > `POST /subscriptions` is deprecated. Existing integrations keep working, but new integrations should use [Checkout Sessions](/api-reference/checkout-sessions/create). > > > [card] [API Reference](/api-reference/checkout-sessions/create) > > > > View the create checkout session API. > [accordion] Update subscriptions > > Use `PATCH /subscriptions/{subscription_id}` to cancel at the next billing date, extend the subscription period, update billing details, or modify metadata. To change quantity, use the [Change Plan API](/api-reference/subscriptions/change-plan) instead. > > > [card] [API Reference](/api-reference/subscriptions/patch-subscriptions) > > > > Learn how to update subscription details. > [accordion] Pause and resume subscriptions > > Pause and resume run through the `status` field on `PATCH /subscriptions/{subscription_id}`: `status: paused` pauses an active subscription and `status: active` resumes it. Neither value can be combined with any other field in the same request. See [Pausing and Resuming Subscriptions](#pausing-and-resuming-subscriptions) for full behavior and billing effects. > > > [card] [API Reference](/api-reference/subscriptions/patch-subscriptions) > > > > View the update subscription API, including the `status` field. > [accordion] Change plans (proration) > > Change the active product and quantities with proration controls. > > > [card] [API Reference](/api-reference/subscriptions/change-plan) > > > > Review plan change options. > [accordion] On-demand charges > > For on-demand subscriptions, charge specific amounts on demand. > > > [card] [API Reference](/api-reference/subscriptions/create-charge) > > > > Charge an on-demand subscription. > [accordion] List and retrieve > > Use `GET /subscriptions` to list all subscriptions and `GET /subscriptions/{subscription_id}` to retrieve one. > > > [card] [API Reference](/api-reference/subscriptions/get-subscriptions) > > > > Browse listing and retrieval APIs. > [accordion] Usage history > > Fetch recorded usage for metered or hybrid pricing models. > > > [card] [API Reference](/api-reference/subscriptions/get-usage-history) > > > > See usage history API. > [accordion] Update payment method > > Update the payment method for a subscription. For active subscriptions, this updates the payment method for future renewals. For subscriptions in `on_hold`, this reactivates the subscription by creating a charge for remaining dues. > > When generating a new payment-method link, you can pass `allowed_payment_method_types` to restrict which payment methods the customer sees. Customers will never see a method that isn't in the list, though including a method does not guarantee it appears (availability depends on factors like customer location and your business settings). > > > [card] [API Reference](/api-reference/subscriptions/update-payment-method) > > > > Learn how to update payment methods and reactivate subscriptions. ## Common Use Cases * **SaaS and APIs**: Tiered access with add-ons for seats or usage * **Content and media**: Monthly access with introductory trials * **B2B support plans**: Annual contracts with premium support add-ons * **Tools and plugins**: License keys and versioned releases ## Integration Examples ### Checkout Sessions (Subscriptions) Create a checkout session with a subscription product and optional add-ons: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_subscription', quantity: 1 } ] }); ``` ### Plan Changes with Proration Upgrade or downgrade a subscription and control proration behavior: ```typescript theme={null} await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_new', quantity: 1, proration_billing_mode: 'difference_immediately' }); ``` ### Cancel at Next Billing Date Schedule a cancellation that takes effect at the end of the current billing period: ```typescript theme={null} await client.subscriptions.update('sub_123', { cancel_at_next_billing_date: true }); ``` ### See Who Cancelled a Subscription When a subscription is cancelled, or a cancellation is scheduled, the subscription records who did it in a `cancelled_by` object. The object appears on [Get Subscription](/api-reference/subscriptions/get-subscriptions), [List Subscriptions](/api-reference/subscriptions/get-subscriptions-1), the [Update Subscription](/api-reference/subscriptions/patch-subscriptions) response, and every `subscription.*` webhook. ```json theme={null} "cancelled_by": { "actor_type": "merchant_user", "name": "Jane Smith", "email": "jane@acme.com" } ``` | `actor_type` | Who cancelled | `name` and `email` | | - | - | - | | `merchant_user` | A member of your team, from the dashboard | The member's name and email | | `customer` | The customer, from the Customer Portal | The customer's name and email | | `api_key` | Your backend, with an API key | `null` | | `dodo_team` | The Dodo Payments team | `null` | * `cancelled_by` is `null` when Dodo Payments cancels the subscription, for example after a dispute, an Ethoca alert, a tax failure, or the end of a grace period. * If the cancellation is scheduled with `cancel_at_next_billing_date`, `cancelled_by` names who scheduled it. * If a scheduled cancellation is revoked, or the customer accepts a retention offer, `cancelled_by` is cleared. * Customer Portal responses never include `cancelled_by`, so your team members' details are not shown to customers. ### Extend the Subscription Period Extend how long a subscription runs by passing a new `subscription_period_count` and `subscription_period_interval` to `PATCH /subscriptions/{subscription_id}`. The subscription's expiry is recomputed from the new count and interval: ```typescript theme={null} await client.subscriptions.update('sub_123', { subscription_period_count: 5, subscription_period_interval: 'Month' }); ``` > [!NOTE] > > A subscription's period can only be increased, never shortened. > [!NOTE] > > The values shown above set the subscription's new total period, not a product-creation value. When creating a product, set a long subscription period such as 20 years. ### On‑Demand Subscriptions Create an on‑demand subscription and charge later as needed: ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_on_demand', quantity: 1 }], customer: { customer_id: 'cus_123' }, subscription_data: { on_demand: { mandate_only: true } } }); // After the customer completes checkout, charge the created subscription await client.subscriptions.charge('sub_123', { product_price: 4900, product_currency: 'USD', product_description: 'Extra usage for September' }); ``` ### Update Payment Method for Active Subscription Update the payment method for an active subscription: ```typescript theme={null} const response = await client.subscriptions.updatePaymentMethod('sub_123', { payment_method: { type: 'new', return_url: 'https://example.com/return' } }); // Or use existing payment method await client.subscriptions.updatePaymentMethod('sub_123', { payment_method: { type: 'existing', payment_method_id: 'pm_abc123' } }); ``` For a subscription from a [multi-subscription cart](/developer-resources/checkout-session#multi-subscription-cart), the new payment method also moves to the other subscriptions from that cart that have the same settlement currency and billing currency. Every subscription from a cart starts with the same pair. If a later change, such as a plan change, moved one of them to another settlement currency or billing currency, update that subscription separately. ### Reactivate Subscription from on\_hold Reactivate a subscription that went on hold due to failed payment: ```typescript theme={null} const response = await client.subscriptions.updatePaymentMethod('sub_123', { payment_method: { type: 'new', return_url: 'https://example.com/return' } }); if (response.payment_id) { // Charge created for remaining dues // Redirect customer to response.payment_link // Monitor webhooks: payment.succeeded → subscription.active } ``` ## Subscriptions with RBI-Compliant Mandates UPI and Indian card subscriptions operate under RBI (Reserve Bank of India) regulations with specific mandate requirements. ### Mandate Limits The mandate type and amount depend on your subscription's recurring charge: * **Charges below the mandate floor (default ₹15,000)**: We create an on-demand mandate for the floor amount. The subscription amount is charged periodically according to your subscription frequency, up to the mandate limit. * **Charges at or above the mandate floor**: We create a subscription mandate (or on-demand mandate) for the exact subscription amount. The mandate floor is configurable per merchant or per request via `mandate_min_amount_inr_paise` (INR paise). The amount registered with the bank is `max(mandate_floor, billing_amount)` — so the floor effectively becomes the customer-facing authorization ceiling whenever billing is lower. See [India Payment Methods](/features/payment-methods/india#configurable-mandate-floor) for detailed information about RBI-compliant mandates and the configurable mandate floor. ### Upgrade and Downgrade Considerations When upgrading or downgrading subscriptions, consider the mandate limits: * If an upgrade/downgrade results in a charge amount that exceeds the mandate floor (default ₹15,000) and goes beyond the existing on-demand payment limit, the transaction charge may fail. * The customer may need to update their payment method or change the subscription again to establish a new mandate with the correct limit. ### Authorization for High-Value Charges For subscription charges of ₹15,000 or more: * The customer will be prompted by their bank to authorize the transaction. * If the customer fails to authorize, the transaction fails and the subscription goes on hold. ### 48-Hour Processing Delay Recurring charges on Indian cards and UPI subscriptions follow a unique processing pattern: * Charges are initiated on the scheduled date according to your subscription frequency. * The actual deduction from the customer's account occurs only after 48 hours from payment initiation. * This 48-hour window may extend up to 2-3 additional hours depending on bank API responses. ### Mandate Cancellation Window During the 48-hour processing window: * Customers can cancel the mandate via their banking apps. * If a customer cancels the mandate during this period, the subscription will remain active (edge case specific to Indian card and UPI AutoPay subscriptions). * However, the actual deduction may fail, and in that case, we will put the subscription on hold. If you provide benefits, credits, or subscription usage to customers immediately upon charge initiation, handle this 48-hour window appropriately: * Delay benefit activation until payment confirmation * Implement grace periods or temporary access * Monitor subscription status for mandate cancellations * Handle subscription hold states in your application logic > [!TIP] > > Monitor subscription webhooks to track payment status changes and handle edge cases where mandates are cancelled during the 48-hour window. ## Best Practices * **Start with clear tiers**: 2-3 plans with obvious differences * **Communicate pricing**: Show totals, proration, and next renewal date * **Use trials thoughtfully**: Convert with onboarding, not just time * **Leverage add-ons**: Keep base plans simple and upsell extras * **Test changes**: Validate plan changes and proration in test mode > [!NOTE] > > Subscriptions are a flexible foundation for recurring revenue. Start simple, test thoroughly, and iterate based on adoption, churn, and expansion metrics. # Tax Inclusive Pricing Source: https://docs.dodopayments.com/features/tax-inclusive-pricing Show final, tax-inclusive prices upfront. Dodo Payments calculates tax by location and breaks it out at checkout and on invoices. ## What Is Tax Inclusive Pricing? Tax Inclusive Pricing lets you embed applicable taxes directly in your displayed product price. Customers see one final amount upfront for a more transparent, conversion-friendly experience. At checkout, Dodo Payments calculates the tax-exclusive portion and tax amount from the displayed price based on customer location, and clearly breaks them out on the invoice. > [!NOTE] > > Final tax still varies by customer location and tax category. Checkout and invoices show the calculated tax portion derived from the displayed price. ## Key Benefits * **Clarity for customers**: One final price displayed upfront * **Compliance by region**: Tax is calculated per location and broken out * **Accurate invoicing**: Invoices show net amount and tax derived from price * **Conversion friendly**: Reduced surprises at checkout ## Product Setup Create or edit a product in your dashboard, then enable tax-inclusive pricing under pricing settings. #### Pricing * **Price** (required): Base price that is displayed to the customer. * **Tax Inclusive Pricing**: Toggle on to treat the displayed price as tax inclusive. Dodo Payments will compute the net (pre-tax) amount and tax portion at checkout based on customer location and tax category. > [!WARNING] > > Only future purchases reflect updated tax-inclusive settings. Existing purchases and active subscriptions are not retroactively changed. > [!TIP] > > Use consistent product copy such as "Tax inclusive" so customers understand totals at a glance. ## API Management > [accordion] Create products (tax inclusive) > > Use `POST /products` to create products with `price.tax_inclusive` set to `true`. The flag lives on the price object, not the product. > > > [card] [API Reference](/api-reference/products/post-products) > > > > Create product via API > [accordion] Update products > > Use `PATCH /products/{id}` to toggle `price.tax_inclusive` on existing products. > > > [card] [API Reference](/api-reference/products/patch-products) > > > > Update product via API > [accordion] Checkout Sessions > > Use `POST /checkouts` to sell products marked as tax inclusive. The displayed price remains the same; checkout derives net amount and tax. > > > [card] [API Reference](/api-reference/checkout-sessions/create) > > > > Create checkout session > [accordion] Refunds (tax handling) > > Use `POST /refunds` to issue refunds. For partial, per-item refunds you can specify whether tax is included using the `tax_inclusive` flag on each entry of the `items` array (defaults to `true`). Omit `items` to refund the payment in full. > > > [card] [API Reference](/api-reference/refunds/post-refunds) > > > > Create a refund ## Integration Examples ### Create a Product with Tax-Inclusive Pricing ```typescript theme={null} const product = await client.products.create({ name: 'Pro Plan', description: 'All features included', tax_category: 'saas', price: { type: 'one_time_price', currency: 'USD', price: 10000, discount_bps: 0, purchasing_power_parity: false, tax_inclusive: true } }); ``` ### Update an Existing Product to Toggle Tax Inclusive ```typescript theme={null} // `price` is a discriminated union, so send the complete price object, // not just the field you want to change. await client.products.update(product.product_id, { price: { type: 'one_time_price', currency: 'USD', price: 10000, discount_bps: 0, purchasing_power_parity: false, tax_inclusive: true } }); ``` ## Best Practices * **Choose the right tax category** to ensure correct calculation per region. * **Communicate totals** clearly with "Tax Inclusive" labels in product copy. * **Test in Test Mode** to validate. ## Related > [card] [Purchasing Power Parity](/features/purchasing-power-parity) > > Charge less in price-sensitive countries automatically. > [card] [Charm Pricing](/features/charm-pricing) > > Round converted prices to clean, appealing endings. > [card] [Products](/features/products) > > Manage pricing options across products. > [card] [Subscriptions](/features/subscription) > > Configure recurring products with advanced settings. > [card] [Discount Codes](/features/discount-codes) > > Offer promotions while keeping invoice clarity. # Team Members Source: https://docs.dodopayments.com/features/team Invite teammates to your Dodo Payments dashboard with predefined or custom roles, and control what each one can read and change. ![Team Members cover image](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/cover-images/Team.png?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=092966bd8d046d553e08cb1fa82f6b7f) Invite teammates to your business dashboard and give each one a role. A role sets what each teammate can see and change, resource by resource, from payments and refunds to products, webhooks, and payouts. ## How to Add a Teammate? ![My Team page listing team members with their roles and actions](https://mintcdn.com/dodopayments/rsanoiHs7RZfcFW7/images/team/team-1.png?fit=max\&auto=format\&n=rsanoiHs7RZfcFW7\&q=85\&s=2c2bd94706a053f6986ff0de060b9dde) 1. Go to **Settings → Team**. 2. Click **Invite Member** in the top-right corner. 3. Enter the email address of each teammate. Press space, comma, or Enter after each address to add another, or paste a list. 4. Select one role for everyone in this invite. To give teammates different roles, send separate invites. 5. Click **Send Invite**. Each teammate gets an email with a sign-in link right away. ## How Can a Teammate Access the Dashboard? ![Create your account form with first name, last name, phone number, and password fields](https://mintcdn.com/dodopayments/rsanoiHs7RZfcFW7/images/team/team-3.png?fit=max\&auto=format\&n=rsanoiHs7RZfcFW7\&q=85\&s=d7dd76129fb019db0afbf97bdfd8abfc) 1. The teammate opens the invitation email and clicks the link. 2. A teammate without a Dodo Payments account goes to the signup page and creates one. A teammate who already has an account opens the business from the business switcher at the top of the sidebar. 3. After signup, the teammate can use the dashboard with the assigned role. Pages and actions outside the role are hidden, or show that the teammate doesn't have access. ## Roles and Permissions ![Business switcher showing the business name with the Owner role badge](https://mintcdn.com/dodopayments/rsanoiHs7RZfcFW7/images/team/team-4.png?fit=max\&auto=format\&n=rsanoiHs7RZfcFW7\&q=85\&s=3786c6f59e32ba4fb9caab942bbca5ae) Your role appears as a badge next to the business name in the business switcher at the top of the sidebar. To see the exact access of every role, click **Manage Roles** on the **Team** page. A role grants **None**, **Read**, or **Write** access to each resource, such as Payments, Refunds, Products, Webhooks, or Business Settings. **Write** includes **Read**. Payouts and Balances are read-only for every role. API keys use the same access levels; see [Authentication](/api-reference/introduction#authentication). ### Owner The **Owner** has full control of the business. Each business has exactly one Owner. Only the Owner can change a member's role, and the Owner can't be removed from the team. To make another teammate the Owner, see [Transferring Business Ownership](/features/ownership-transfer). ### Predefined Roles | Role | Access | | - | - | | **Admin** | Full access, including team members and API keys. | | **Developer** | Builds integrations. Reads all data, and writes products, customers, checkout sessions, license keys, webhooks, events, meters, credits, entitlements, API keys, and moderation. No access to money movement such as refunds. | | **Analyst** | Read-only access to all data. | | **Support Specialist** | Handles refunds, disputes, and customers. Reads payments, subscriptions, checkout sessions, license keys, analytics, and invoices. | | **Finance** | Read-only access to payments, refunds, disputes, payouts, balances, analytics, invoices, and moderation. | Teammates who joined with the earlier **Editor** or **Viewer** roles keep them. **Editor** has access to everything, and **Viewer** has read-only access. ### Custom Roles To give a teammate a different mix of access, create a custom role: 1. On the **Team** page, click **Manage Roles**. 2. Click **Create Custom Role**. 3. Enter a **Role Name**, such as Billing Manager. 4. Set **None**, **Read**, or **Write** for each resource. Grant access to at least one resource. 5. Click **Create Role**. The new role then appears in the role picker when you invite a teammate or change a role. You can edit a custom role's permissions at any time. To delete a custom role that teammates hold, reassign them to another role first. ### Who Can Manage the Team Teammates whose role has **Write** access to **Team Members** can invite and remove teammates. They can only grant roles with less access than their own, and only access they have themselves. Only the Owner can change a member's role. Any teammate except the Owner can leave the business with **Leave Team** on the **Team** page. # Disputes Source: https://docs.dodopayments.com/features/transactions/disputes View and respond to disputes from the Transactions page, and stop chargebacks before they are filed with Visa RDR, Ethoca alerts, and deflections. ## Introduction A dispute, also called a chargeback, starts when a customer asks their card issuer to reverse a payment. As your [Merchant of Record](/features/mor-introduction), Dodo Payments handles the dispute process with the card networks. You decide whether to accept or counter each dispute, and you supply the evidence. When a dispute opens, the disputed amount and a dispute fee are deducted from your balance. The **Disputes** tab shows the status, reason, and dispute ID of every dispute on your account. Dodo Payments also provides three tools that stop disputes before they become chargebacks: * [Visa Rapid Dispute Resolution (RDR)](#visa-rapid-dispute-resolution-rdr) refunds Visa disputes at or below your threshold automatically. * [Ethoca Alerts](#ethoca-alerts) refund Mastercard and other non-Visa payments automatically when the issuer sends an alert. * [Deflections](#deflections) block fraud claims on Visa and Mastercard payments before they are filed, so you keep the funds. ## Viewing and Understanding Disputes **1. Open the Transactions Page** Go to **Transactions** in your dashboard and select the **Disputes** tab. The list shows each dispute's amount, status, dispute ID, associated payment, and creation date. **2. View Dispute Details** Click a dispute in the list to open its details: the dispute ID, payment ID, customer name and email, reason, and remarks. When the card network sends a reason code, the details also show the network and the code, for example **Visa** and **Reason code 10.4**. Below them are a title and a description of what the cardholder claims, and a **Recommended evidence** list for that reason code. Use the list to decide whether to counter the dispute and which files to upload. **3. Access Associated Payment Information** To see the full details of the disputed payment, click its ID in the **Associated Payment** column. To read disputes from your backend, use [List Disputes](/api-reference/disputes/get-disputes) and [Get Dispute Detail](/api-reference/disputes/get-disputes-1), or listen for [dispute webhooks](/developer-resources/webhooks/intents/dispute). ## Responding to a Dispute When a customer opens a dispute, Dodo Payments emails you, and the dispute appears in the **Disputes** tab with the status **Dispute opened**. When the reason code is known, the email and the notification name it, for example "Fraud: card-absent transaction (Visa 10.4)". > [!WARNING] > > You have **10 days** to respond to a dispute after it is created. The countdown shown on the dispute in your dashboard reflects the same window. **1. Check Your Dashboard** Go to **Transactions → Disputes** and find the new dispute. **2. Review the Email Notification** Check your registered email address for the dispute notification. **3. Choose Your Response** Open the dispute. You can accept it or counter it. ![Dispute details page showing the dispute amount, reason, customer, and payment ID, with the Accept Dispute and Counter Dispute buttons](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/disputes/1.png?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=27063993592af91e6ac1464956aaa3a7) **4. If Accepting** Click **Accept Dispute** and confirm. The disputed amount is refunded to the customer, the dispute fee applies, and you lose the dispute. No further action is required. **5. If Countering** Click **Counter Dispute** and complete the form. First, select why you should win the dispute and describe the product or service. Then upload your evidence and click **Submit**. Follow the [Dispute Response Best Practices](#dispute-response-best-practices) when you prepare the evidence. ![Counter dispute form asking why you should win the dispute, with a product or service description and the product type](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/disputes/2.png?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=7712b07bf6246c34bc59a7f27d0d03c3) ![Counter dispute evidence step with evidence types, file upload areas, an access activity logs upload, and the Submit button](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/disputes/3.png?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=a2415d76c609768b7550ab08b80614dc) After you submit evidence, the dispute status changes to **Dispute challenged** while the card network reviews it. ## Dispute Response Best Practices **1. Understand the Dispute Reason** Review the dispute reason carefully. If the dispute shows a network reason code, start with its description and **Recommended evidence** list. Common reasons include: > [card] Fraudulent Transaction > > The customer claims they did not authorize the transaction. > [card] Product/Service Not Received > > The customer claims they did not receive the product or service after payment. > [card] Not as Described > > The customer claims the product or service differs from what was advertised. > [!NOTE] > > Your response must address the specific reason. Don't submit generic or unrelated evidence. **2. Gather the Right Evidence** Focus on evidence of the customer's identity, access, and usage. > [tab] Fraudulent Transaction > > > [card] Required Evidence > > > > * **Invoice** of the purchase > > * **IP address, device, and location** details at the time of purchase > > * **Login timestamps** showing access to your platform or service > > * **Browser or device fingerprint**, or account activity logs > > * Previous successful transactions from the same customer or account > > * Terms of Service and Refund Policy accepted at the time of purchase > [tab] Product/Service Not Received > > > [card] Required Evidence > > > > * **Invoice** of the purchase > > * Screenshot or logs showing a **successful login** > > * Timestamped activity, such as downloads, content viewed, or sessions started > > * Emails or support messages confirming that access was granted > > * Welcome emails or onboarding steps the customer completed > > * Internal logs showing the product or service was delivered as promised > [tab] Not as Described > > > [card] Required Evidence > > > > * **Invoice** of the purchase > > * The product or service description on your website at the time of purchase > > * A comparison of what was promised and what was delivered > > * Documentation or screenshots of what the customer accessed > > * Any customer communication acknowledging receipt or usage > > * The refund policy and support options made available to the customer **3. Craft a Clear Description** > [card] Focus Points > > * What the customer purchased > * When and how they accessed it > * Why the dispute claim is inaccurate > [!NOTE] > > Keep your language factual and professional. Avoid emotional or accusatory statements. > [card] Example Response > > "We offer a digital image generation from text service using AI. The customer purchased a monthly subscription on March 5 and accessed the product multiple times from March 5–10 and generated 4 images in the duration. Please see attached access logs and the accepted terms showing our no-refund policy." **4. Format and Submit Evidence** > [card] Submission Guidelines > > * Use **PDF, JPG, PNG, or ZIP** files only > * **Label each file** clearly, for example `Login_Log_March_5.pdf` > * Submit only **relevant** and **organized** files > * Keep each file under 5 MB > * To upload several files for one evidence type, compress them into a single ZIP archive > * Do **not include links or URLs** > [accordion] Common Mistakes to Avoid > > > [card] Avoid These Errors > > > > * Ignoring the actual dispute reason > > * Using vague or emotional statements > > * Uploading unrelated or unstructured files > > * Providing links instead of files > [accordion] Bonus Tips > > > [card] Strengthen Your Case > > > > * Include **timestamps with a time zone** to prove access timelines > > * Highlight any **two-factor authentication** or verification steps > > * Share **refund refusal communication** if it aligns with your policy > > * Keep your policies visible, so you can prove the customer accepted them ## Visa Rapid Dispute Resolution (RDR) Visa Rapid Dispute Resolution (RDR) resolves eligible Visa disputes **before they become formal chargebacks**. When a cardholder disputes a Visa payment with their bank, RDR checks the amount against your configured threshold. If the amount qualifies, RDR refunds the cardholder on your behalf, so no chargeback is filed. ### Why RDR Matters Disputes cost digital businesses money and time. A high dispute rate also has consequences beyond each lost payment: > [card] Financial Impact > > For each dispute, the disputed amount **plus** a dispute fee are deducted from your balance. The dispute fee is not refunded, even if you win. > [card] Dispute Rate Penalties > > Card networks monitor your dispute and fraud levels. Exceeding Visa's or Mastercard's thresholds places you in a monitoring program with fines. > [card] Account Risk > > A consistently high dispute rate can lead to higher processing fees, reserve requirements, or account termination by payment processors. > [card] Operational Overhead > > Each dispute needs evidence, a written response, and follow-up, which takes time away from building your product. > [!WARNING] > > Visa's Acquirer Monitoring Program (VAMP) counts your disputes and fraud reports each month against your settled transactions. A merchant with a ratio of **1.5%** or more and at least **1,500** disputes and fraud reports in a month is flagged as excessive. In CEMEA, the limits are a ratio of 2.2% and at least 150 disputes and fraud reports worth USD 75,000 or more. Visa charges fees for every month the merchant stays above the threshold. ### How RDR Works **1. Cardholder Initiates a Dispute** The customer contacts their bank to dispute a Visa transaction on their statement. **2. RDR Intercepts the Dispute** Before the dispute becomes a formal chargeback, Visa's RDR system checks whether the transaction qualifies for automatic resolution under your configured rules. **3. Automatic Refund Issued** If the transaction amount is at or below your threshold, the cardholder is refunded through Visa's network, and the dispute is resolved. **4. No Chargeback Recorded** Because the dispute is resolved before it becomes a formal chargeback, it **does not count against your dispute rate** with Visa. > [!NOTE] > > A transaction refunded through RDR appears as a **lost dispute** in your Dodo Payments dashboard, marked **Resolved by RDR**. This is expected: the refund was issued automatically to prevent a formal chargeback, and the "lost" status reflects that the funds were returned to the cardholder. The dispute webhook reports it as `dispute.lost` with `is_resolved_by_rdr: true`. A Visa RDR fee replaces the dispute fee for these disputes. ### Key Benefits RDR changes the outcome of a low-value Visa dispute in four ways: | Benefit | Description | | - | - | | **Lower dispute rate** | RDR-resolved disputes are excluded from Visa's VAMP count, which helps you stay below its monitoring thresholds | | **Zero operational overhead** | You don't gather evidence, write responses, or track dispute deadlines. Resolution is automatic | | **Better customer experience** | Cardholders get their refund without waiting weeks for a dispute to be resolved | | **Protect your account standing** | Stay out of Visa's monitoring programs and avoid escalating fines and processing restrictions | ### Configuration RDR uses a **USD threshold**. A Visa dispute at or below your threshold is resolved automatically with a refund. A dispute above the threshold goes through the normal dispute process, so you can counter it with evidence. > [!NOTE] > > For example, with a \$100 threshold: a \$75 dispute is resolved automatically (refunded), while a \$150 dispute proceeds normally for you to review and respond to. ### Enable RDR for Your Account Visa RDR is **enabled by default** on all Dodo Payments accounts with a **\$100 USD threshold**. Any Visa dispute at or below \$100 is resolved automatically with a refund, with no action from you. For pricing, see the [Dodo Payments pricing page](https://dodopayments.com/pricing). ![Dispute Resolution settings showing the Visa RDR toggle with a \$100 threshold and the Ethoca Alerts card with an Enroll button](https://mintcdn.com/dodopayments/CkIwIO_d6TQRG6OY/images/disputes/dispute-resolution-settings.png?fit=max\&auto=format\&n=CkIwIO_d6TQRG6OY\&q=85\&s=d0268346732dae141fcbda1511a8f37b) Visa RDR on the Dispute Resolution settings page #### Customizing Your Threshold To change the RDR threshold: **1. Open the Dispute Resolution Settings** Go to **Settings → Dispute Resolution** in your Dodo Payments dashboard and find the **Visa RDR** card. **2. Edit the Threshold** Click **Edit** next to the current threshold and enter the new amount in USD. Visa disputes at or below this amount are resolved automatically. **3. Save Your Changes** Save the new threshold. It applies to every Visa dispute that arrives after you save it. > [!NOTE] > > To turn RDR off, switch off the **Visa RDR** toggle. Keeping it on protects your dispute rate. If Dodo Payments has locked the RDR settings for your business, you can't change them from the dashboard; contact support. > [!TIP] > > Start with a threshold near your average transaction value, then adjust it as you learn your dispute patterns. ### Frequently Asked Questions > [accordion] Can a cardholder dispute the same transaction again after RDR resolution? > > No. Once a transaction is resolved through RDR, it is closed at the Visa network level. The issuer does not process another chargeback for the same transaction. If the cardholder tries again, their bank sees the earlier resolution and rejects the dispute. Visa enforces this upstream, so there is nothing for you to manage. ## Ethoca Alerts Visa RDR covers only Visa cards. **Ethoca alerts** give you the same pre-chargeback protection on Mastercard and other non-Visa cards. Ethoca is Mastercard's alert network. When a cardholder reports fraud or disputes a charge, their card issuer sends an alert before it files a chargeback. Dodo Payments then refunds the payment automatically, so the chargeback is never filed. Alerts come only from card issuers that take part in Ethoca. Most alerts are on Mastercard payments. Alerts on American Express and other non-Visa cards are handled the same way when the issuer takes part. Visa disputes are always handled by [Visa RDR](#visa-rapid-dispute-resolution-rdr). ### How Ethoca Alerts Work After your business is enrolled, every alert on a non-Visa payment is resolved automatically: **1. Cardholder Reports the Charge** The customer tells their bank that a Mastercard or other non-Visa charge is fraudulent, or disputes it. **2. The Issuer Sends an Alert** Before filing a chargeback, the issuer sends an alert through Ethoca. Dodo Payments matches it to the original payment using the card details, amount, and transaction time. **3. The Payment Is Refunded in Full** Dodo Payments refunds the full payment amount to the cardholder. There is **no threshold**: every matched alert is refunded, whatever the amount. **4. Any Linked Subscription Is Cancelled** If the payment belongs to a subscription, the subscription is cancelled immediately. An active subscription would produce the same alert again at the next renewal. **5. The Alert Is Resolved** Dodo Payments confirms the refund through Ethoca, so the issuer does not file a chargeback. The dispute **does not count against your chargeback ratio**, which helps keep you out of Mastercard's chargeback monitoring programs. > [!NOTE] > > If the payment was already refunded or is already under dispute, the alert is closed without another refund. Any linked subscription is still cancelled. > [!WARNING] > > Enrolling means accepting automatic refunds. You can't review an alert or counter it with evidence. To respond to disputes on non-Visa cards yourself, don't enroll, or unenroll at any time. ### What You See in the Dashboard An Ethoca alert does not appear in the **Disputes** tab, because no dispute is created. Instead: | Where | What appears | | - | - | | **Transactions → Refunds** | A full refund with the reason **Ethoca fraud alert** | | **Subscriptions** | The linked subscription, if any, with the status **Cancelled** | | **Notifications** | An email titled "Refund issued automatically for \[customer] after a fraud alert", plus an in-app and push notification | | **Webhooks** | The standard refund and subscription webhooks fire. There is no Ethoca-specific event | ### Enable Ethoca Alerts Ethoca alerts are **opt-in**. Before you enroll, your business needs live payments enabled and a statement descriptor. A fee applies for each alert. For pricing, see the [Dodo Payments pricing page](https://dodopayments.com/pricing). **1. Open Dispute Resolution Settings** Go to **Settings → Dispute Resolution** in your Dodo Payments dashboard and find the **Ethoca Alerts** card. Only editors and owners can change this setting. ![Dispute Resolution settings showing the Ethoca Alerts card with an Enroll button](https://mintcdn.com/dodopayments/CkIwIO_d6TQRG6OY/images/disputes/dispute-resolution-settings.png?fit=max\&auto=format\&n=CkIwIO_d6TQRG6OY\&q=85\&s=d0268346732dae141fcbda1511a8f37b) Ethoca Alerts on the Dispute Resolution settings page **2. Enroll** Click **Enroll** and confirm. By confirming, you accept that every alerted payment is refunded automatically. **3. Wait for Confirmation** Your status shows **Pending** while Ethoca confirms your enrollment, which takes **2 to 4 business days**. Click **Refresh** to check. Alerts are not refunded automatically until your status shows **Enrolled**. #### Unenrolling Click **Unenroll** on the same card and confirm. Your status shows **Removal requested** until the removal completes, usually within a few minutes. Alerts can still arrive and be refunded until it does. You can enroll again at any time. If the dashboard reports that your enrollment can't be removed there, contact support. ### Ethoca Alerts FAQ > [accordion] Why was a subscription cancelled after an Ethoca alert? > > The cardholder told their bank that they dispute the charge. An active subscription would bill them again at the next renewal and produce another alert and another refund. Cancelling it immediately stops that cycle. This also applies when the alert is closed without a refund because the payment was already refunded or disputed. > [accordion] Can I contest an Ethoca alert with evidence? > > No. Enrolling in Ethoca alerts means every matched alert is refunded automatically. To respond to disputes on non-Visa cards yourself, unenroll on the **Settings → Dispute Resolution** page. You can still counter Visa disputes above your RDR threshold. > [accordion] Can a payment go through both Visa RDR and Ethoca alerts? > > No. Visa RDR handles Visa disputes, and Ethoca alerts handle non-Visa disputes. A single payment goes through only one of them. > [accordion] Why was an alert not refunded automatically? > > Alerts are refunded only while your enrollment status shows **Enrolled**. Alerts that arrive while your status is **Pending** are not refunded. Alerts on payments that can't be matched to a single transaction go through the normal dispute process instead. > [accordion] Why did I still receive a chargeback on a non-Visa payment after enrolling? > > Not every issuer takes part in Ethoca, so some disputes arrive as chargebacks without an alert first. Disputes that the cardholder raised before your enrollment was confirmed can also still arrive as chargebacks. Respond to these from the **Disputes** tab as usual. ## Deflections A **deflection** stops a dispute before it is filed, without a refund. When a cardholder tells their bank they did not make a purchase, the bank checks the payment against the order details and the customer's earlier purchases from you. If the evidence shows that the same customer made the purchase, the bank blocks the dispute. You keep the payment, and nothing counts against your dispute rate. A deflection fee applies. ### How Deflections Work **1. Cardholder Questions a Charge** The customer contacts their bank about a Visa or Mastercard charge, usually because they don't recognize it or believe it is fraud. **2. The Bank Looks Up the Order** The bank requests the order details. Dodo Payments answers automatically with what was purchased and when, the order total, the customer's account details, and, where available, the IP address used at checkout. Often the cardholder recognizes the purchase at this point, and the inquiry ends. **3. The Network Checks Earlier Purchases** If the cardholder still claims fraud, the network compares the payment with the same customer's earlier undisputed payments to you. When at least two earlier payments share key details, such as the IP address and email address, the bank blocks the dispute. Visa does this through Compelling Evidence 3.0, and Mastercard through First-Party Trust. **4. The Dispute Is Deflected** No dispute is filed, and no refund is issued. The deflection does not count against your dispute rate. > [!NOTE] > > Deflections work for returning customers. A first-time customer has no earlier payments to compare against, so a fraud claim on their first payment can't be blocked this way. ### What You See in the Dashboard A deflection creates no dispute and no refund. Instead: | Where | What appears | | - | - | | **Notifications** | An email titled "Dispute deflected for your \[amount] payment" | | **Balance** | The deflection fee, listed under **Deflection Fees** | | **Webhooks** | No event fires. There is no dispute or refund to report | ### Availability Every Dodo Payments business is enrolled in deflections automatically. There is nothing to enable or configure. For pricing, see the [Dodo Payments pricing page](https://dodopayments.com/pricing). ### Deflections FAQ > [accordion] Why did I receive a deflection email but see no dispute? > > That is expected. A deflection means the dispute was blocked before it was filed, so there is no dispute to show. The deflection email is your record of it. > [accordion] Should I refund a deflected payment? > > No. The dispute was blocked in your favor, so the payment stands. Refunding it gives up the sale for no benefit. # Payments Source: https://docs.dodopayments.com/features/transactions/payments Track every payment from the Transactions page. Filter by status, currency, and date, open payment details, download invoices, and start refunds. [Checkout Experience | Dodo Payments]() The **Payments** tab on the **Transactions** page lists every payment on your account. Open a payment to see its full breakdown, download its invoice, or start a [refund](/features/transactions/refunds). ## **Payments Listing Page** The Payments listing page records every payment attempt. For each payment, it shows the amount, status, payment ID, payment method, customer, and date. Each payment shows one of these statuses: | Status | Meaning | | - | - | | **Successful** | The payment was completed. | | **Processing** | The payment was sent to the payment processor and is waiting for confirmation. The **Status** filter calls this status **In Progress**. | | **Failed** | The payment attempt was declined. | | **Cancelled** | The payment was cancelled before it completed. | | **Requires customer action** | The customer needs to complete an additional verification step. | | **Requires payment method** | The payment was created but not charged, for example because the customer didn't finish checkout. | | **On hold** | The payment is waiting for review, confirmation, or capture before it can complete. | A payment that was refunded or disputed shows its refund or dispute status instead, such as **Refunded**, **Partially refunded**, or **Dispute opened**. > [!NOTE] > > The **Payment Method** column fills in after the customer submits a payment method. The **Date** column shows when the payment was created, not when it completed. *** ## **Payment Details Page** Click a payment in the listing to open its **Payment Details Page**, which breaks down the transaction. ### Successful Payment ![Payment details page showing a successful payment with green status and transaction breakdown](https://mintcdn.com/dodopayments/o0NHkVXqfi7_fJzV/images/transactions/payments/successful-payment.png?fit=max\&auto=format\&n=o0NHkVXqfi7_fJzV\&q=85\&s=1747ba9d3c524e896e9eb810af10437c) Example of a successfully captured card payment A successful payment shows: * **Status**: **Successful** at the top, with the final captured amount. * **Payment breakdown**: The amount, tax, and fees of the payment, and the estimated net amount. See [Interchange-Plus-Plus Fees](#interchange-plus-plus-fees). * **Transaction details**: Payment ID, payment date, payment method, payment type, settlement amount, settlement tax, tax in the payment currency, the subscription ID for a subscription payment, and the checkout session ID. * **Product Cart**: Products and the quantities purchased, with any add-ons and usage meters of each item. * **Discounts**: Each discount applied to the payment, with its code, the amount off, and the number of billing cycles. * **Customer details**: Name, email, phone number, and billing address. * **Card Information**: Card network, last four digits, card type, issuing country, and card holder name. * **Custom fields**: The customer's answers to your checkout's [custom fields](/developer-resources/checkout-session#collecting-custom-fields), when the checkout has them. * **Metadata**: Any metadata attached to the payment. You can copy each value. * **Other information**: Business, customer, and brand IDs, the payment link, and a link to each subscription that a renewal payment charged. * **Activity Log**: Each status change and its timestamp, at the end of the page. * **Actions**: Click **Invoice** to download the invoice, or **Initiate Refund** to start a refund. Both buttons are in the top-right corner. ### Interchange-Plus-Plus Fees On a payment with interchange-plus-plus (IC++) pricing, the **Fees** group of the payment breakdown shows each fee on its own row: | Row | What it is | | - | - | | **Gateway fee** | The fixed Dodo Payments fee on the payment | | **Payment method fee** | The percentage fee of the payment method | | **Interchange fee** | Fee charged by the customer's card issuing bank for processing the payment | | **Scheme fee** | Fee charged by the card scheme for processing the transaction | Hover over or tap the info icon on a row to see what the fee covers. The processor sends the interchange and scheme fees 3 to 5 days after a successful payment. Until then, these two rows show `-`, with a note about the delay. A payment with standard pricing shows one **Payment Fees** row. See [Balances](/features/account-summary-payout-wallet) for the ledger entries of each fee. ### Failed Payment ![Payment details page showing a failed payment with red error banner, decline error code and message](https://mintcdn.com/dodopayments/o0NHkVXqfi7_fJzV/images/transactions/payments/failed-payment.png?fit=max\&auto=format\&n=o0NHkVXqfi7_fJzV\&q=85\&s=ac5cea5fc28fe87b3318df6547f94bf6) Example of a failed card payment with decline information A failed payment shows: * **Status**: **Failed**, with a red banner. * **Error context**: The gateway **Error Code** and a readable **Error Message**, for example `INSUFFICIENT_FUNDS` with "Your card was declined." * **Other information**: The error fields are repeated in the details section for quick reference. * **Next steps**: * For a failed subscription **renewal**, click **Retry Payment Manually** to charge the saved payment method again right away. See [Manual Payment Retry](/features/recovery/manual-retry) for eligibility and limits. * Ask the customer to retry the payment with a different card or funding source. * Ask the customer to check their card details and available funds. * If the decline persists, ask the customer to contact their card issuer and then try again. > [!NOTE] > > Look up any **Error Code** in the [Transaction Failures](/api-reference/transaction-failures) reference to see what it means and the recommended action. To handle failed payments in your code, see [Handle Payment Failures](/developer-resources/handle-payment-failures). ## **Important Information** * **Automatic Activation**: Supported payment methods become available to your customers automatically once your account is verified and live mode is enabled. See [Payment Methods](/features/payment-methods) for the full list. * **No Additional Configuration Required**: You don't need to set up payment methods. Dodo Payments pre-configures and manages them, and you can disable specific methods from your dashboard. * **Additional Payment Methods**: Dodo Payments adds payment methods over time and updates the [Payment Methods](/features/payment-methods) page when it does. To request a method that isn't supported, email [support@dodopayments.com](mailto:support@dodopayments.com). ## How to Navigate and Use the Payments Page **1. Navigate to the Payments Section** Open the **Transactions** page and select the **Payments** tab to view all payments. **2. Filter Payments** Use the filters to narrow the list: * **Status**: In Progress, Successful, Failed, Requires Payment Method, or Requires Customer Action. * **Currency**: The currency the customer paid in. * **Date range**: Payments from a specific period. **3. View Payment Details** Click any payment in the list to open its details page. **4. Review Payment Information** On the payment details page, you can review: * **Transaction details**: Amount, currency, payment method, and timestamp * **Customer information**: Name, email, and billing details * **Payment status**: The current status, with each status change and its timestamp in the **Activity Log** **5. Download Invoice** To download the invoice, click **Invoice** in the top-right corner of the payment details page. To read payments from your backend, use [List Payments](/api-reference/payments/get-payments), [Get Payment Detail](/api-reference/payments/get-payments-1), and [Get Invoice](/api-reference/payments/get-invoice). To react to status changes, listen for [payment webhooks](/developer-resources/webhooks/intents/payment) such as `payment.succeeded` and `payment.failed`. # Refunds Source: https://docs.dodopayments.com/features/transactions/refunds Issue full or partial refunds from the payment details page, track each refund's status, and learn the rules that decide whether a refund can go through. Refund a customer in full or in part from the payment's details page. The refund goes to the original payment method, and Dodo Payments emails the customer a receipt when it succeeds. ## Initiate Refund You can initiate two types of refunds from the **Payment Details Page**: * **Full refund**: Refunds the entire payment amount to the customer. * **Partial refund**: Refunds part of the payment. You set the amount to refund for each item. To begin, click **Initiate Refund** and choose **Full refund** or **Partial refund**. The refund goes through only if it meets every [refund rule](#refund-rules). ![Initiate refund button on the payment details page](https://mintcdn.com/dodopayments/G4bT0KSWSqgyqhfn/images/transactions/refunds/initiate-refund.png?fit=max\&auto=format\&n=G4bT0KSWSqgyqhfn\&q=85\&s=1b2cc9f687451eaeef24e8d0310225c7) > [!TIP] > > Partial refunds are useful when only a portion of the order needs to be refunded. To refund from your backend, call [Create Refund](/api-reference/refunds/post-refunds) with the `payment_id`. For a partial refund, pass `items`, each with an `item_id` (the `product_id` or add-on ID) and the `amount` to refund. Omit `amount` to refund the whole item. > [!WARNING] > > By default, each `amount` is in the smallest unit of the payment's settlement currency, which is USD for most payments. To give amounts in the currency the customer paid in, set `currency` on the request. See [Refunds in the Payment Currency](#refunds-in-the-payment-currency). ### Refunds in the Payment Currency When the customer pays in a different currency from your settlement currency, for example AED with [Adaptive Currency](/features/adaptive-currency), you can enter the refund in the customer's currency. The amount you enter is the refund amount in the customer's currency. To refund in the payment currency from your backend: 1. Call [Retrieve Line Items](/api-reference/payments/retrieve-line-items) with `?currency=` set to the payment's `currency`. The response gives each item's `amount`, `tax`, and `refundable_amount` in that currency. 2. Call [Create Refund](/api-reference/refunds/post-refunds) with `currency` set to the same value, and each `items[].amount` in the smallest unit of that currency. ```json theme={null} { "payment_id": "pay_gr4RizvMOXFJ6xca3y2tU", "currency": "AED", "items": [{ "item_id": "pdt_0NVbdIG3JNg9Yc8ey5JHW", "amount": 5000 }], "reason": "Customer returned one seat" } ``` This request refunds 50.00 AED to the customer. * `currency` must equal the payment's `currency`. Any other value returns `REFUND_CURRENCY_NOT_SUPPORTED`. * Dodo Payments debits your balance in the settlement currency. It converts at the payment's own rate, `total_amount` divided by `settlement_amount`, not at the exchange rate on the refund day. The refund that returns the rest of the payment debits the rest of its settlement amount, so all refunds of a payment add up to its settlement amount with no rounding remainder. * Credits bought with the payment can't be refunded in the payment currency. To refund the `credits` line item, send the refund without `currency`. * If an earlier refund of the payment has no amount in the payment currency, a refund with `currency` returns `REFUND_CURRENCY_NOT_SUPPORTED`. Send that refund without `currency`. * For a payment in the settlement currency, `currency` is optional and has no effect on the amounts. In the dashboard, the refund dialog of a cross-currency payment shows each item's amounts in the payment currency. Below the total, it shows the **Estimated settlement debit** in your settlement currency. The final debit can differ slightly from the estimate. ### Details Required for Refund * **Refund Amount**: The amount to be refunded. For a partial refund, enter the amount for each item you want to return to the customer. The dashboard shows each item's refundable amount and prevents you from refunding more than the original payment. * **Refund Reason**: The reason for the refund, recorded with the refund. The dashboard requires at least 5 characters, and the API accepts up to 3,000. Before you confirm, the dashboard shows the price refund, the tax refund, and the total refund to the customer. ### Refund Rules 1. The payment must have succeeded. 2. Our standard policy is that a customer must request a refund within **7 days** of making the purchase, and requests after that are invalid. To leave room for edge cases, merchants have a longer window of **30 days** from the payment date (default) to process full or partial refunds from the dashboard. After 30 days, refunds are not allowed. 3. The refund, together with any earlier refunds on the payment, can't exceed the amount paid. 4. Only one refund per payment can be in progress. A refund with the status `pending` or `review` must finish before you start another. 5. Your balance must cover the refund amount. 6. In live mode, live payments must be enabled for your business. 7. Refunds are issued to the original payment method used by the customer. 8. Some cross-currency payments allow a partial refund only after the payment processor completes its verification of the payment. Until then, only a first full refund is allowed, and a partial refund fails with `PARTIAL_REFUND_NOT_ALLOWED`. A refund of the remaining amount after an earlier refund also counts as a partial refund. The `partial_refund_allowed` field of [Retrieve Line Items](/api-reference/payments/retrieve-line-items) shows whether a partial refund is allowed. It can stay `false` for a few hours after verification completes, because [Create Refund](/api-reference/refunds/post-refunds) checks the latest verification status and the line items do not. If any rule is not met, the refund request is denied. For help, contact [support@dodopayments.com](mailto:support@dodopayments.com). ## When Your Balance Can't Cover a Refund Dodo Payments pays a refund from your wallet balance, not from the original payment. If your balance is lower than the refund amount, the refund is denied, even though the payment succeeded. Your balance can be lower than a payment's full amount for three reasons: * **A payment adds less than the customer paid.** Your wallet is credited with the payment, and then the tax on it and the Dodo Payments transaction fees are debited. A full refund returns more than the payment added to your balance. * **A payout moves your balance to your bank.** On each payout date, your eligible balance is transferred to your bank account. Right after a payout, your balance may not cover a refund for a payment made before it. * **Other entries use the same balance.** Earlier refunds, disputes, and their fees are deducted from your balance when they occur. When a refund goes through, the [Balances](/features/account-summary-payout-wallet) ledger records these entries: | Ledger entry | Effect on your balance | | - | - | | **Refund** | Debit of the amount returned to the customer | | **Tax Reversal** | Credit of the tax on the refunded amount | | **Refund Fees** | Debit of the fee for processing the refund | The **Payment Fees** entry has no reversal, so Dodo Payments does not return the transaction fees on the original payment when you refund it. To issue a refund that your balance can't cover: 1. Check your balance under **Payouts → Balances**. 2. Wait until new payments raise your balance, and then initiate the refund. Refunds must be initiated within the refund window, so don't wait past it. 3. If the refund can't wait, email [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email address with the payment ID. > [!TIP] > > The balance rule also applies in test mode. To test a refund end to end, including the `refund.succeeded` webhook, complete enough test payments that your test-mode balance covers the refund amount. ## Refund Status Track the progress of your refund with these statuses: | Status | Description | Possible Reason | | - | - | - | | succeeded | The refund was processed. | — | | pending | The refund was submitted to the payment processor and is awaiting completion. | — | | review | The payment processor is reviewing the refund before it completes. | A risk or compliance check on the refund | | failed | The refund could not be processed. | The payment was disputed, or a bank issue | Dodo Payments sends the `refund.succeeded` or `refund.failed` webhook when a refund reaches a final status. See [Refund Webhooks](/developer-resources/webhooks/intents/refund). ## Refund Network Reference A succeeded refund gets a reference number from the card network or the bank. Give this number to your customer when they can't find the refund, so they can trace it with their bank. The reference appears on the refund details sheet and the refund page, with a copy button. Its heading shows the kind of reference: | Reference | API value | | - | - | | Acquirer reference number (ARN) | `acquirer_reference_number` | | System trace audit number (STAN) | `system_trace_audit_number` | | Retrieval reference number (RRN) | `retrieval_reference_number` | | Refund reference number | `other` | * The reference is usually available 1 to 3 business days after the refund succeeds. Until then, the refund shows **Not available yet**. After it arrives, the dashboard shows the date it was made available. * Funds can take 5 to 10 business days to settle in the customer's account. * Failed refunds don't show a reference. * The refunds table has a **Network reference** column. It is visible on the payment page, and you can turn it on from **Edit columns** on the **Refunds** page and the customer page. In the API, the refund object carries `network_reference` and `network_reference_type`. Both are `null` until the reference is available. They appear on [Get Refund Detail](/api-reference/refunds/get-refunds-1), [List Refunds](/api-reference/refunds/get-refunds), and the refunds of a payment. The `refund.succeeded` webhook carries the same fields, but the reference usually arrives after the webhook is sent and no second webhook follows. To get the reference, read the refund from the API. ## Refunds Page The **Refunds** tab on the **Transactions** page lists every refund, with its amount, status, refund ID, associated payment, refund type, date, and reason: * To open the **Payment Details Page** for a refund's payment, click its ID in the **Associated Payment** column. * Refunds are exported from **Settings → Reports**. The [Adjustments Report](/features/reports#adjustments-report) covers refunds and disputes together, as CSV or XLSX. The **Refunds** page looks like this: ![Refunds page showing a list of refund transactions](https://mintcdn.com/dodopayments/G4bT0KSWSqgyqhfn/images/transactions/refunds/refunds-page.png?fit=max\&auto=format\&n=G4bT0KSWSqgyqhfn\&q=85\&s=22c72ca071883cc91fea7e8b4d7854de) To read refunds from your backend, use [List Refunds](/api-reference/refunds/get-refunds) and [Get Refund Detail](/api-reference/refunds/get-refunds-1). ## Refund Receipt When a refund succeeds, Dodo Payments emails the customer. The email shows the refund amount, status, Refund ID, original payment amount, and refund date, and links to the **Refund Receipt**. The **Refund Successful** email is on by default; you can turn it off under [Customer Emails](/features/communication-preferences#customer-emails). To fetch the receipt from your backend, use [Get Refund Receipt](/api-reference/refunds/get-refund-receipt). **Refund Receipt Template:** ![Refund receipt template showing the refund details](https://mintcdn.com/dodopayments/G4bT0KSWSqgyqhfn/images/transactions/refunds/refund-receipt-template.png?fit=max\&auto=format\&n=G4bT0KSWSqgyqhfn\&q=85\&s=7070148120060d73114fafb1d21b5396) The refund receipt includes: * **Refund ID**: The unique identifier for the refund, with the ID of the refunded payment. * **Refund type**: Whether the refund is full or partial. * **Refund amount**: The amount refunded to the customer, with its taxable amount and tax amount. * **Refund date**: The date the refund was processed. * **Refund method**: The payment method the refund was sent to. * **Refund reason**: The reason for the refund. # Upsells & Downsells Source: https://docs.dodopayments.com/features/upsells-and-downsells Increase revenue with one-click purchases using saved payment methods for post-purchase offers, subscription upgrades, and cross-sells. > [!NOTE] > > Upsells and downsells let you offer additional products or plan changes to customers using their saved payment methods. This enables one-click purchases that skip payment collection, dramatically improving conversion rates. > [card] Post-Purchase Upsells > > Offer complementary products immediately after checkout with one-click purchasing. > [card] Subscription Upgrades > > Move customers to higher tiers with automatic proration and instant billing. > [card] Cross-Sells > > Add related products to existing customers without re-entering payment details. ## Overview Upsells and downsells are powerful revenue optimization strategies: * **Upsells**: Offer a higher-value product or upgrade (e.g., Pro plan instead of Basic) * **Downsells**: Offer a lower-priced alternative when a customer declines or downgrades * **Cross-sells**: Suggest complementary products (e.g., add-ons, related items) Dodo Payments enables these flows through the `payment_method_id` parameter, which lets you charge a customer's saved payment method without requiring them to re-enter card details. ### Key Benefits | Benefit | Impact | | - | - | | **One-click purchases** | Skip payment form for returning customers | | **Higher conversion** | Reduce friction at the moment of decision | | **Instant processing** | Charges process immediately with `confirm: true` | | **In-App Experience** | Customers stay in your app throughout the flow | ## How It Works ```mermaid theme={null} sequenceDiagram participant C as Customer participant A as Your App participant D as Dodo API C->>A: Completes purchase A->>D: Get payment methods D-->>A: payment_method_id A->>C: Show upsell offer C->>A: Accept (one click) A->>D: Charge with payment_method_id D-->>A: Payment success D->>A: Webhook: payment.succeeded ``` ## Prerequisites Before implementing upsells and downsells, ensure you have: * Customers with saved payment methods (automatically saved after their first purchase) * Upsell products configured in the dashboard (one-time payments, subscriptions, or add-ons) * A webhook endpoint configured to handle `payment.succeeded`, `payment.failed`, and `subscription.plan_changed` events ## Getting Customer Payment Methods Before offering an upsell, retrieve the customer's saved payment methods: > [tab] TypeScript > > ```typescript theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'live_mode', > }); > > async function getPaymentMethods(customerId: string) { > const paymentMethods = await client.customers.retrievePaymentMethods(customerId); > > // Returns { items: [...] } — the list of saved payment methods. > // Each item has: payment_method_id, payment_method, payment_method_type, last_used_at, > // recurring_enabled, and card (last4_digits, card_network, card_type, expiry_month, expiry_year) > return paymentMethods; > } > > // Example usage > const methods = await getPaymentMethods('cus_123'); > console.log('Available payment methods:', methods); > > // Use the first available method for upsell > const primaryMethod = methods.items[0]?.payment_method_id; > ``` > [tab] Python > > ```python theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), > environment="live_mode", > ) > > def get_payment_methods(customer_id: str): > payment_methods = client.customers.retrieve_payment_methods(customer_id) > > # Returns an object with an `items` list of saved payment methods. > # Each item has: payment_method_id, payment_method, payment_method_type, last_used_at, > # recurring_enabled, and card (last4_digits, card_network, card_type, expiry_month, expiry_year) > return payment_methods > > # Example usage > methods = get_payment_methods("cus_123") > print("Available payment methods:", methods) > > # Use the first available method for upsell > primary_method = methods.items[0].payment_method_id if methods.items else None > ``` > [tab] Go > > ```go theme={null} > package main > > import ( > "context" > "fmt" > "os" > > "github.com/dodopayments/dodopayments-go" > "github.com/dodopayments/dodopayments-go/option" > ) > > func getPaymentMethods(customerID string) ([]dodopayments.CustomerGetPaymentMethodsResponseItem, error) { > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > ) > > resp, err := client.Customers.GetPaymentMethods( > context.TODO(), > customerID, > ) > if err != nil { > return nil, err > } > > return resp.Items, nil > } > > func main() { > methods, err := getPaymentMethods("cus_123") > if err != nil { > panic(err) > } > > fmt.Println("Available payment methods:", methods) > > // Use the first available method for upsell > if len(methods) > 0 { > primaryMethod := methods[0].PaymentMethodID > fmt.Println("Primary method:", primaryMethod) > } > } > ``` > [!NOTE] > > Payment methods are automatically saved when customers complete checkout. You don't need to explicitly save them. ## Post-Purchase One-Click Upsells Offer additional products immediately after a successful purchase. The customer can accept with a single click since their payment method is already saved. ```mermaid theme={null} flowchart LR A[Purchase] --> B{Upsell?} B -->|Yes| C[Show Offer] B -->|No| F[Done] C --> D{Accept?} D -->|Yes| E[One-Click Charge] --> F D -->|No| F ``` ### Implementation > [tab] TypeScript > > ```typescript theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'live_mode', > }); > > async function createOneClickUpsell( > customerId: string, > paymentMethodId: string, > upsellProductId: string > ) { > // Create checkout session with saved payment method > // confirm: true processes the payment immediately > const session = await client.checkoutSessions.create({ > product_cart: [ > { > product_id: upsellProductId, > quantity: 1 > } > ], > customer: { > customer_id: customerId > }, > payment_method_id: paymentMethodId, > confirm: true, // Required when using payment_method_id > return_url: 'https://yourapp.com/upsell-success', > feature_flags: { > redirect_immediately: true // Skip success page > }, > metadata: { > upsell_source: 'post_purchase', > original_order_id: 'order_123' > } > }); > > return session; > } > > // Example: Offer premium add-on after initial purchase > async function handlePostPurchaseUpsell(customerId: string) { > // Get customer's payment methods > const methods = await client.customers.retrievePaymentMethods(customerId); > > if (methods.items.length === 0) { > console.log('No saved payment methods available'); > return null; > } > > // Create the upsell with one-click checkout > const upsell = await createOneClickUpsell( > customerId, > methods.items[0].payment_method_id, > 'pdt_premium_addon' > ); > > console.log('Upsell processed:', upsell.session_id); > return upsell; > } > ``` > [tab] Python > > ```python theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), > environment="live_mode", > ) > > def create_one_click_upsell( > customer_id: str, > payment_method_id: str, > upsell_product_id: str > ): > """Create a one-click upsell using saved payment method.""" > > # Create checkout session with saved payment method > # confirm=True processes the payment immediately > session = client.checkout_sessions.create( > product_cart=[ > { > "product_id": upsell_product_id, > "quantity": 1 > } > ], > customer={ > "customer_id": customer_id > }, > payment_method_id=payment_method_id, > confirm=True, # Required when using payment_method_id > return_url="https://yourapp.com/upsell-success", > feature_flags={ > "redirect_immediately": True # Skip success page > }, > metadata={ > "upsell_source": "post_purchase", > "original_order_id": "order_123" > } > ) > > return session > > > def handle_post_purchase_upsell(customer_id: str): > """Offer premium add-on after initial purchase.""" > > # Get customer's payment methods > methods = client.customers.retrieve_payment_methods(customer_id) > > if not methods.items: > print("No saved payment methods available") > return None > > # Create the upsell with one-click checkout > upsell = create_one_click_upsell( > customer_id=customer_id, > payment_method_id=methods.items[0].payment_method_id, > upsell_product_id="pdt_premium_addon" > ) > > print(f"Upsell processed: {upsell.session_id}") > return upsell > ``` > [tab] Go > > ```go theme={null} > package main > > import ( > "context" > "fmt" > "os" > > "github.com/dodopayments/dodopayments-go" > "github.com/dodopayments/dodopayments-go/option" > "github.com/dodopayments/dodopayments-go/shared" > ) > > func createOneClickUpsell( > customerID string, > paymentMethodID string, > upsellProductID string, > ) (*dodopayments.CheckoutSessionResponse, error) { > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > ) > > // Create checkout session with saved payment method > // Confirm: true processes the payment immediately > session, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{ > CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ > ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{ > { > ProductID: dodopayments.F(upsellProductID), > Quantity: dodopayments.F(int64(1)), > }, > }), > Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam]( > dodopayments.AttachExistingCustomerParam{ > CustomerID: dodopayments.F(customerID), > }, > ), > PaymentMethodID: dodopayments.F(paymentMethodID), > Confirm: dodopayments.F(true), // Required when using payment_method_id > ReturnURL: dodopayments.F("https://yourapp.com/upsell-success"), > FeatureFlags: dodopayments.F(dodopayments.CheckoutSessionFlagsParam{ > RedirectImmediately: dodopayments.F(true), // Skip success page > }), > Metadata: dodopayments.F(dodopayments.MetadataParam{ > "upsell_source": shared.UnionString("post_purchase"), > "original_order_id": shared.UnionString("order_123"), > }), > }, > }) > > return session, err > } > > func handlePostPurchaseUpsell(customerID string) (*dodopayments.CheckoutSessionResponse, error) { > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > ) > > // Get customer's payment methods > resp, err := client.Customers.GetPaymentMethods(context.TODO(), customerID) > if err != nil { > return nil, err > } > > if len(resp.Items) == 0 { > fmt.Println("No saved payment methods available") > return nil, nil > } > > // Create the upsell with one-click checkout > upsell, err := createOneClickUpsell( > customerID, > resp.Items[0].PaymentMethodID, > "pdt_premium_addon", > ) > if err != nil { > return nil, err > } > > fmt.Printf("Upsell processed: %s\n", upsell.SessionID) > return upsell, nil > } > ``` > [!WARNING] > > When you pass `payment_method_id` to a checkout session, you must also set `confirm: true` and provide an existing `customer_id`. The payment method must belong to that customer. ## Subscription Upgrades Move customers to higher-tier subscription plans with automatic proration handling. ```mermaid theme={null} sequenceDiagram participant C as Customer participant A as Your App participant D as Dodo API C->>A: Request upgrade A->>D: Preview change plan D-->>A: Charge amount A->>C: Confirm $50 charge? C->>A: Confirm A->>D: Change plan D->>A: Webhook: plan_changed ``` ### Preview Before Committing Always preview plan changes to show customers exactly what they'll be charged: > [tab] TypeScript > > ```typescript theme={null} > async function previewUpgrade( > subscriptionId: string, > newProductId: string > ) { > const preview = await client.subscriptions.previewChangePlan(subscriptionId, { > product_id: newProductId, > quantity: 1, > proration_billing_mode: 'difference_immediately' > }); > > return { > immediateCharge: preview.immediate_charge?.summary, > newPlan: preview.new_plan, > effectiveAt: preview.immediate_charge?.effective_at > }; > } > > // Show customer the charge before confirming > const preview = await previewUpgrade('sub_123', 'pdt_pro_plan'); > console.log(`Upgrade will charge: ${preview.immediateCharge}`); > ``` > [tab] Python > > ```python theme={null} > def preview_upgrade(subscription_id: str, new_product_id: str): > preview = client.subscriptions.preview_change_plan( > subscription_id=subscription_id, > product_id=new_product_id, > quantity=1, > proration_billing_mode="difference_immediately" > ) > > return { > "immediate_charge": preview.immediate_charge.summary if preview.immediate_charge else None, > "new_plan": preview.new_plan, > "effective_at": preview.immediate_charge.effective_at if preview.immediate_charge else None, > } > > # Show customer the charge before confirming > preview = preview_upgrade("sub_123", "pdt_pro_plan") > print(f"Upgrade will charge: {preview['immediate_charge']}") > ``` > [tab] Go > > ```go theme={null} > func previewUpgrade(subscriptionID string, newProductID string) (map[string]interface{}, error) { > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > ) > > preview, err := client.Subscriptions.PreviewChangePlan( > context.TODO(), > subscriptionID, > dodopayments.SubscriptionPreviewChangePlanParams{ > UpdateSubscriptionPlanReq: dodopayments.UpdateSubscriptionPlanReqParam{ > ProductID: dodopayments.F(newProductID), > Quantity: dodopayments.F(int64(1)), > ProrationBillingMode: dodopayments.F(dodopayments.UpdateSubscriptionPlanReqProrationBillingModeDifferenceImmediately), > }, > }, > ) > if err != nil { > return nil, err > } > > return map[string]interface{}{ > "immediate_charge": preview.ImmediateCharge.Summary, > "new_plan": preview.NewPlan, > "effective_at": preview.ImmediateCharge.EffectiveAt, > }, nil > } > ``` ### Execute the Upgrade > [tab] TypeScript > > ```typescript theme={null} > async function upgradeSubscription( > subscriptionId: string, > newProductId: string, > prorationMode: 'prorated_immediately' | 'prorated_immediately_keep_cycle' | 'difference_immediately' | 'full_immediately' | 'do_not_bill' = 'difference_immediately' > ) { > // change-plan returns 200 with a ChangePlanResponse body (payment_id, payment_link, > // client_secret, expires_on). All four are null when the change settles off-session. > await client.subscriptions.changePlan(subscriptionId, { > product_id: newProductId, > quantity: 1, > proration_billing_mode: prorationMode > }); > > // Re-read the subscription to observe the applied state. > return await client.subscriptions.retrieve(subscriptionId); > } > > // Upgrade from Basic ($30) to Pro ($80) > // With difference_immediately: charges $50 instantly > const upgrade = await upgradeSubscription('sub_123', 'pdt_pro_plan'); > console.log('Upgrade status:', upgrade.status); > ``` > [tab] Python > > ```python theme={null} > def upgrade_subscription( > subscription_id: str, > new_product_id: str, > proration_mode: str = "difference_immediately" > ): > # change_plan returns 200 with a ChangePlanResponse body (payment_id, payment_link, > # client_secret, expires_on). All four are None when the change settles off-session. > client.subscriptions.change_plan( > subscription_id=subscription_id, > product_id=new_product_id, > quantity=1, > proration_billing_mode=proration_mode > ) > > # Re-read the subscription to observe the applied state. > return client.subscriptions.retrieve(subscription_id) > > # Upgrade from Basic ($30) to Pro ($80) > # With difference_immediately: charges $50 instantly > upgrade = upgrade_subscription("sub_123", "pdt_pro_plan") > print(f"Upgrade status: {upgrade.status}") > ``` > [tab] Go > > ```go theme={null} > func upgradeSubscription( > subscriptionID string, > newProductID string, > prorationMode dodopayments.UpdateSubscriptionPlanReqProrationBillingMode, > ) error { > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > ) > > // ChangePlan returns a SubscriptionChangePlanResponse alongside the error. > _, err := client.Subscriptions.ChangePlan( > context.TODO(), > subscriptionID, > dodopayments.SubscriptionChangePlanParams{ > UpdateSubscriptionPlanReq: dodopayments.UpdateSubscriptionPlanReqParam{ > ProductID: dodopayments.F(newProductID), > Quantity: dodopayments.F(int64(1)), > ProrationBillingMode: dodopayments.F(prorationMode), > }, > }, > ) > > return err > } > > func main() { > // Upgrade from Basic ($30) to Pro ($80) > // With DifferenceImmediately: charges $50 instantly > err := upgradeSubscription( > "sub_123", > "pdt_pro_plan", > dodopayments.UpdateSubscriptionPlanReqProrationBillingModeDifferenceImmediately, > ) > if err != nil { > panic(err) > } > fmt.Println("Upgrade succeeded") > } > ``` ### Proration Modes Choose how customers are billed when upgrading: #### `difference_immediately` Charges price difference instantly (\$30→\$80 = \$50). Best for simple upgrades. #### `prorated_immediately` Credits unused time on the old plan, then charges a full cycle of the new one. Best for crediting unused time. #### `prorated_immediately_keep_cycle` Charges the price difference for the time left in the current cycle (\$30→\$80 with half the cycle left = \$25). Keeps the billing date. Best when customers renew on a fixed date. #### `full_immediately` Charges full new plan price, ignores remaining time. Best for billing cycle resets. #### `do_not_bill` Applies the plan change with no immediate charge; the new plan is billed at the next renewal and the original billing date is preserved. Best for courtesy upgrades and free migrations. > [!TIP] > > Use `difference_immediately` for straightforward upgrade flows — the charge is the plain price difference. Use `prorated_immediately` when you want the customer credited for unused time on the current plan and charged a full cycle of the new one. ## Cross-Sells Add complementary products for existing customers without requiring them to re-enter payment details. ```mermaid theme={null} flowchart LR A[View Product] --> B{Existing Customer?} B -->|Yes| C[One-Click Buy] --> E[Deliver] B -->|No| D[Standard Checkout] --> E ``` The examples below create a confirmed checkout session with the customer's saved `payment_method_id`, the same way as [Post-Purchase One-Click Upsells](#post-purchase-one-click-upsells). With `confirm: true`, every billing address field is required. ### Implementation > [tab] TypeScript > > ```typescript theme={null} > async function createCrossSell( > customerId: string, > paymentMethodId: string, > productId: string, > quantity: number = 1 > ) { > // Charge the saved payment method with a confirmed checkout session > const session = await client.checkoutSessions.create({ > product_cart: [ > { > product_id: productId, > quantity: quantity > } > ], > customer: { customer_id: customerId }, > billing_address: { country: 'US', city: 'San Francisco', state: 'CA', street: '1 Market St', zipcode: '94105' }, > payment_method_id: paymentMethodId, > confirm: true, // Required when using payment_method_id > return_url: 'https://yourapp.com/purchase-complete', > metadata: { > purchase_type: 'cross_sell', > source: 'product_recommendation' > } > }); > > return session; > } > > // Example: Customer bought a course, offer related ebook > async function offerRelatedProduct(customerId: string, relatedProductId: string) { > const methods = await client.customers.retrievePaymentMethods(customerId); > > if (methods.items.length === 0) { > // Fall back to standard checkout > return client.checkoutSessions.create({ > product_cart: [{ product_id: relatedProductId, quantity: 1 }], > customer: { customer_id: customerId }, > return_url: 'https://yourapp.com/purchase-complete' > }); > } > > // One-click purchase > return createCrossSell(customerId, methods.items[0].payment_method_id, relatedProductId); > } > ``` > [tab] Python > > ```python theme={null} > def create_cross_sell( > customer_id: str, > payment_method_id: str, > product_id: str, > quantity: int = 1 > ): > """Charge the saved payment method with a confirmed checkout session.""" > > session = client.checkout_sessions.create( > product_cart=[ > { > "product_id": product_id, > "quantity": quantity > } > ], > customer={"customer_id": customer_id}, > billing_address={"country": "US", "city": "San Francisco", "state": "CA", "street": "1 Market St", "zipcode": "94105"}, > payment_method_id=payment_method_id, > confirm=True, # Required when using payment_method_id > return_url="https://yourapp.com/purchase-complete", > metadata={ > "purchase_type": "cross_sell", > "source": "product_recommendation" > } > ) > > return session > > > def offer_related_product(customer_id: str, related_product_id: str): > """Offer related product with one-click purchase if possible.""" > > methods = client.customers.retrieve_payment_methods(customer_id) > > if not methods.items: > # Fall back to standard checkout > return client.checkout_sessions.create( > product_cart=[{"product_id": related_product_id, "quantity": 1}], > customer={"customer_id": customer_id}, > return_url="https://yourapp.com/purchase-complete" > ) > > # One-click purchase > return create_cross_sell(customer_id, methods.items[0].payment_method_id, related_product_id) > ``` > [tab] Go > > ```go theme={null} > func createCrossSell( > customerID string, > paymentMethodID string, > productID string, > quantity int64, > ) (*dodopayments.CheckoutSessionResponse, error) { > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > ) > > // Charge the saved payment method with a confirmed checkout session > session, err := client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{ > CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ > ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{ > { > ProductID: dodopayments.F(productID), > Quantity: dodopayments.F(quantity), > }, > }), > Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam]( > dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F(customerID)}, > ), > BillingAddress: dodopayments.F(dodopayments.CheckoutSessionBillingAddressParam{ > Country: dodopayments.F(dodopayments.CountryCodeUs), > City: dodopayments.F("San Francisco"), > State: dodopayments.F("CA"), > Street: dodopayments.F("1 Market St"), > Zipcode: dodopayments.F("94105"), > }), > PaymentMethodID: dodopayments.F(paymentMethodID), > Confirm: dodopayments.F(true), // Required when using payment_method_id > ReturnURL: dodopayments.F("https://yourapp.com/purchase-complete"), > Metadata: dodopayments.F(dodopayments.MetadataParam{ > "purchase_type": shared.UnionString("cross_sell"), > "source": shared.UnionString("product_recommendation"), > }), > }, > }) > > return session, err > } > > func offerRelatedProduct(customerID string, relatedProductID string) (interface{}, error) { > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > ) > > resp, err := client.Customers.GetPaymentMethods(context.TODO(), customerID) > if err != nil { > return nil, err > } > > if len(resp.Items) == 0 { > // Fall back to standard checkout > return client.CheckoutSessions.New(context.TODO(), dodopayments.CheckoutSessionNewParams{ > CheckoutSessionRequest: dodopayments.CheckoutSessionRequestParam{ > ProductCart: dodopayments.F([]dodopayments.ProductItemReqParam{ > {ProductID: dodopayments.F(relatedProductID), Quantity: dodopayments.F(int64(1))}, > }), > Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam]( > dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F(customerID)}, > ), > ReturnURL: dodopayments.F("https://yourapp.com/purchase-complete"), > }, > }) > } > > // One-click purchase > return createCrossSell(customerID, resp.Items[0].PaymentMethodID, relatedProductID, 1) > } > ``` ## Subscription Downgrades When customers want to move to a lower-tier plan, handle the transition gracefully with automatic credits. ### How Downgrades Work 1. Customer requests downgrade (Pro → Basic) 2. System calculates remaining value on current plan 3. Credit is added to subscription for future renewals 4. Customer moves to new plan immediately > [!NOTE] > > The preview's `immediate_charge.summary.customer_credits` is in the currency of the customer's credit wallet, given by `customer_credits_currency`. It can differ from the summary's `currency`, for example when the customer pays in INR on a USD subscription. > [tab] TypeScript > > ```typescript theme={null} > async function downgradeSubscription( > subscriptionId: string, > newProductId: string > ) { > // Preview the downgrade first > const preview = await client.subscriptions.previewChangePlan(subscriptionId, { > product_id: newProductId, > quantity: 1, > proration_billing_mode: 'difference_immediately' > }); > > // customer_credits is positive when credit is added to the balance, negative when credit is used > console.log('Customer credit change:', preview.immediate_charge.summary.customer_credits); > > // Execute the downgrade. change-plan returns 200 with a ChangePlanResponse body. > await client.subscriptions.changePlan(subscriptionId, { > product_id: newProductId, > quantity: 1, > proration_billing_mode: 'difference_immediately' > }); > > // Credits are automatically applied to future renewals > return await client.subscriptions.retrieve(subscriptionId); > } > > // Downgrade from Pro ($80) to Basic ($30) > // $50 credit added to subscription, auto-applied on next renewal > const downgrade = await downgradeSubscription('sub_123', 'pdt_basic_plan'); > ``` > [tab] Python > > ```python theme={null} > def downgrade_subscription(subscription_id: str, new_product_id: str): > # Preview the downgrade first > preview = client.subscriptions.preview_change_plan( > subscription_id=subscription_id, > product_id=new_product_id, > quantity=1, > proration_billing_mode="difference_immediately" > ) > > # customer_credits is positive when credit is added to the balance, negative when credit is used > print(f"Customer credit change: {preview.immediate_charge.summary.customer_credits}") > > # Execute the downgrade. change_plan returns 200 with a ChangePlanResponse body. > client.subscriptions.change_plan( > subscription_id=subscription_id, > product_id=new_product_id, > quantity=1, > proration_billing_mode="difference_immediately" > ) > > # Credits are automatically applied to future renewals > return client.subscriptions.retrieve(subscription_id) > > # Downgrade from Pro ($80) to Basic ($30) > # $50 credit added to subscription, auto-applied on next renewal > downgrade = downgrade_subscription("sub_123", "pdt_basic_plan") > ``` > [tab] Go > > ```go theme={null} > func downgradeSubscription(subscriptionID string, newProductID string) error { > client := dodopayments.NewClient( > option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), > ) > > // Preview the downgrade first > preview, err := client.Subscriptions.PreviewChangePlan( > context.TODO(), > subscriptionID, > dodopayments.SubscriptionPreviewChangePlanParams{ > UpdateSubscriptionPlanReq: dodopayments.UpdateSubscriptionPlanReqParam{ > ProductID: dodopayments.F(newProductID), > Quantity: dodopayments.F(int64(1)), > ProrationBillingMode: dodopayments.F(dodopayments.UpdateSubscriptionPlanReqProrationBillingModeDifferenceImmediately), > }, > }, > ) > if err != nil { > return err > } > > fmt.Printf("Customer credits to be applied: %v\n", preview.ImmediateCharge.Summary.CustomerCredits) > > // Execute the downgrade (returns a SubscriptionChangePlanResponse alongside the error) > _, err = client.Subscriptions.ChangePlan( > context.TODO(), > subscriptionID, > dodopayments.SubscriptionChangePlanParams{ > UpdateSubscriptionPlanReq: dodopayments.UpdateSubscriptionPlanReqParam{ > ProductID: dodopayments.F(newProductID), > Quantity: dodopayments.F(int64(1)), > ProrationBillingMode: dodopayments.F(dodopayments.UpdateSubscriptionPlanReqProrationBillingModeDifferenceImmediately), > }, > }, > ) > return err > } > ``` > [!NOTE] > > Credits from downgrades using `difference_immediately` are subscription-scoped and automatically applied to future renewals. They're distinct from [Credit-Based Billing](/features/credit-based-billing) entitlements. ## Complete Example: Post-Purchase Upsell Flow Here's a complete implementation showing how to offer an upsell after a successful purchase: > [tab] TypeScript > > ```typescript theme={null} > import DodoPayments from 'dodopayments'; > import express from 'express'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'live_mode', > }); > > const app = express(); > > // Store for tracking upsell eligibility (use your database in production) > const eligibleUpsells = new Map(); > > // Webhook handler for initial purchase success > app.post('/webhooks/dodo', express.raw({ type: 'application/json' }), async (req, res) => { > const event = JSON.parse(req.body.toString()); > > switch (event.type) { > case 'payment.succeeded': > // Check if customer is eligible for upsell > const customerId = event.data.customer.customer_id; > const productId = event.data.product_cart?.[0]?.product_id; > > // Define upsell rules (e.g., bought Basic, offer Pro) > const upsellProduct = getUpsellProduct(productId); > > if (upsellProduct) { > eligibleUpsells.set(customerId, { > customerId, > productId: upsellProduct > }); > } > break; > > case 'payment.failed': > console.log('Payment failed:', event.data.payment_id); > // Handle failed upsell payment > break; > } > > res.json({ received: true }); > }); > > // API endpoint to check upsell eligibility > app.get('/api/upsell/:customerId', async (req, res) => { > const { customerId } = req.params; > const upsell = eligibleUpsells.get(customerId); > > if (!upsell) { > return res.json({ eligible: false }); > } > > // Get payment methods > const methods = await client.customers.retrievePaymentMethods(customerId); > > if (methods.items.length === 0) { > return res.json({ eligible: false, reason: 'no_payment_method' }); > } > > // Get product details for display > const product = await client.products.retrieve(upsell.productId); > > res.json({ > eligible: true, > product: { > id: product.product_id, > name: product.name, > price: product.price, > currency: product.price.currency > }, > paymentMethodId: methods.items[0].payment_method_id > }); > }); > > // API endpoint to accept upsell > app.post('/api/upsell/:customerId/accept', async (req, res) => { > const { customerId } = req.params; > const upsell = eligibleUpsells.get(customerId); > > if (!upsell) { > return res.status(400).json({ error: 'No upsell available' }); > } > > try { > const methods = await client.customers.retrievePaymentMethods(customerId); > > // Create one-click purchase > const session = await client.checkoutSessions.create({ > product_cart: [{ product_id: upsell.productId, quantity: 1 }], > customer: { customer_id: customerId }, > payment_method_id: methods.items[0].payment_method_id, > confirm: true, > return_url: `${process.env.APP_URL}/upsell-success`, > feature_flags: { redirect_immediately: true }, > metadata: { upsell: 'true', source: 'post_purchase' } > }); > > // Clear the upsell offer > eligibleUpsells.delete(customerId); > > res.json({ success: true, sessionId: session.session_id }); > } catch (error) { > console.error('Upsell failed:', error); > res.status(500).json({ error: 'Upsell processing failed' }); > } > }); > > // Helper function to determine upsell product > function getUpsellProduct(purchasedProductId: string): string | null { > const upsellMap: Record = { > 'pdt_basic_plan': 'pdt_pro_plan', > 'pdt_starter_course': 'pdt_complete_bundle', > 'pdt_single_license': 'pdt_team_license' > }; > > return upsellMap[purchasedProductId] || null; > } > > app.listen(3000); > ``` > [tab] Python > > ```python theme={null} > import os > from flask import Flask, request, jsonify > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), > environment="live_mode", > ) > > app = Flask(__name__) > > # Store for tracking upsell eligibility (use your database in production) > eligible_upsells = {} > > > @app.route('/webhooks/dodo', methods=['POST']) > def webhook_handler(): > event = request.json > > if event['type'] == 'payment.succeeded': > # Check if customer is eligible for upsell > customer_id = event['data']['customer']['customer_id'] > product_id = (event['data'].get('product_cart') or [{}])[0].get('product_id') > > # Define upsell rules > upsell_product = get_upsell_product(product_id) > > if upsell_product: > eligible_upsells[customer_id] = { > 'customer_id': customer_id, > 'product_id': upsell_product > } > > elif event['type'] == 'payment.failed': > print(f"Payment failed: {event['data']['payment_id']}") > > return jsonify({'received': True}) > > > @app.route('/api/upsell/', methods=['GET']) > def check_upsell(customer_id): > upsell = eligible_upsells.get(customer_id) > > if not upsell: > return jsonify({'eligible': False}) > > # Get payment methods > methods = client.customers.retrieve_payment_methods(customer_id) > > if not methods.items: > return jsonify({'eligible': False, 'reason': 'no_payment_method'}) > > # Get product details for display > product = client.products.retrieve(upsell['product_id']) > > return jsonify({ > 'eligible': True, > 'product': { > 'id': product.product_id, > 'name': product.name, > 'price': product.price, > 'currency': product.price.currency > }, > 'payment_method_id': methods.items[0].payment_method_id > }) > > > @app.route('/api/upsell//accept', methods=['POST']) > def accept_upsell(customer_id): > upsell = eligible_upsells.get(customer_id) > > if not upsell: > return jsonify({'error': 'No upsell available'}), 400 > > try: > methods = client.customers.retrieve_payment_methods(customer_id) > > # Create one-click purchase > session = client.checkout_sessions.create( > product_cart=[{'product_id': upsell['product_id'], 'quantity': 1}], > customer={'customer_id': customer_id}, > payment_method_id=methods.items[0].payment_method_id, > confirm=True, > return_url=f"{os.environ['APP_URL']}/upsell-success", > feature_flags={'redirect_immediately': True}, > metadata={'upsell': 'true', 'source': 'post_purchase'} > ) > > # Clear the upsell offer > del eligible_upsells[customer_id] > > return jsonify({'success': True, 'session_id': session.session_id}) > > except Exception as error: > print(f"Upsell failed: {error}") > return jsonify({'error': 'Upsell processing failed'}), 500 > > > def get_upsell_product(purchased_product_id: str) -> str: > """Determine upsell product based on purchased product.""" > upsell_map = { > 'pdt_basic_plan': 'pdt_pro_plan', > 'pdt_starter_course': 'pdt_complete_bundle', > 'pdt_single_license': 'pdt_team_license' > } > return upsell_map.get(purchased_product_id) > > > if __name__ == '__main__': > app.run(port=3000) > ``` ## Best Practices * **Time strategically**: Offer upsells immediately after a successful purchase when customers are in a buying mindset. Other effective moments: after feature usage milestones, when approaching plan limits, during onboarding completion. * **Validate payment methods**: Before attempting a one-click charge, verify the payment method is compatible with the product's currency, hasn't expired, and belongs to the customer. * **Handle failures gracefully**: When one-click charges fail, fall back to standard checkout flow, notify the customer with clear messaging, and offer to update payment method. * **Provide clear value**: Show what customers are getting vs. their current plan, highlight the price difference (not total price), and use social proof. * **Respect customer choice**: Always provide an easy way to decline, don't show the same upsell repeatedly after decline, and track which upsells convert to optimize offers. ## Webhooks to Monitor Track these webhook events for upsell and downgrade flows: | Event | Trigger | Action | | - | - | - | | `payment.succeeded` | Upsell/cross-sell payment completed | Deliver product, update access | | `payment.failed` | One-click charge failed | Show error, offer retry or fallback | | `subscription.plan_changed` | Upgrade/downgrade completed | Update features, send confirmation | | `subscription.active` | Subscription reactivated after plan change | Grant access to new tier | > [card] [Webhook Integration Guide](/developer-resources/webhooks) > > Learn how to set up and verify webhook endpoints. ## Related Resources > [card] [Subscription Upgrade Guide](/developer-resources/subscription-upgrade-downgrade) > > Detailed guide on plan changes, proration modes, and handling failures. > [card] [Checkout Sessions](/developer-resources/checkout-session) > > Complete reference for creating checkout sessions with all options. > [card] [Customer Payment Methods API](/api-reference/customers/get-customer-payment-methods) > > API reference for listing customer payment methods. > [card] [Add-ons](/features/addons) > > Enhance subscriptions with flexible add-ons for additional revenue. # Event Ingestion Source: https://docs.dodopayments.com/features/usage-based-billing/event-ingestion Send usage events from your application to track customer consumption and power billing. Events are the foundation of usage-based billing. Send events when billable actions occur, and meters aggregate them into charges. > [card] [API Reference — Events Ingestion](/api-reference/usage-events/ingest-events) > > Complete API documentation with examples and response codes. ## Event Structure > [accordion] Required Fields > > **event\_id** `string` *required* > > A unique identifier for the event, used to detect duplicate events on retry. Derive it from the action, for example customer ID + action + timestamp, so a retried event keeps the same ID. A fresh random UUID on each retry lets the same event be counted twice. > > **customer\_id** `string` *required* > > The Dodo Payments customer ID. Must be a valid existing customer. > > **event\_name** `string` *required* > > The event type that matches your meter's event name (case-sensitive). Examples: `api.call`, `image.generated`. > [accordion] Optional Fields > > **timestamp** `string` > > ISO 8601 timestamp (UTC). Defaults to the current server time if omitted. Include for accurate billing with delayed or batch events. Timestamps older than 1 hour or more than 5 minutes in the future are rejected. > > **metadata** `object` > > Additional properties for aggregation and filtering. Up to 50 keys; each key can be up to 100 characters and each value up to 500 characters. > > * Numeric values: `bytes`, `tokens`, `duration_ms` > * Filters: `endpoint`, `method`, `quality` > > ```javascript theme={null} > metadata: { > endpoint: "/v1/orders", > method: "POST", > tokens: 1024 > } > ``` ## Sending Events ```javascript Single Event theme={null} await fetch('https://test.dodopayments.com/events/ingest', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.DODO_PAYMENTS_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [{ event_id: "api_call_1234", customer_id: "cus_abc123", event_name: "api.call", metadata: { endpoint: "/v1/orders" } }] }) }); ``` ```javascript Batch Events theme={null} await fetch('https://test.dodopayments.com/events/ingest', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.DODO_PAYMENTS_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [ { event_id: "call_1", customer_id: "cus_abc", event_name: "api.call" }, { event_id: "call_2", customer_id: "cus_abc", event_name: "api.call" }, { event_id: "call_3", customer_id: "cus_abc", event_name: "api.call" } ] }) }); ``` ```python Python theme={null} import os import requests requests.post( 'https://test.dodopayments.com/events/ingest', headers={'Authorization': f"Bearer {os.environ['DODO_PAYMENTS_API_KEY']}", 'Content-Type': 'application/json'}, json={'events': [{'event_id': 'call_1', 'customer_id': 'cus_abc', 'event_name': 'api.call'}]} ) ``` ```curl cURL theme={null} curl -X POST 'https://test.dodopayments.com/events/ingest' \ -H 'Authorization: Bearer dodo_test_...' \ -H 'Content-Type: application/json' \ -d '{"events": [{"event_id": "call_1", "customer_id": "cus_abc", "event_name": "api.call"}]}' ``` > [!TIP] > > Batch up to 1,000 events per request for better performance. The API enforces a hard limit of 1,000 events per request. ## Ingestion Blueprints Ready-made event patterns for common use cases. Start with a proven blueprint instead of building from scratch. > [card] [LLM Blueprint](/developer-resources/ingestion-blueprints/llm) > > Track AI token usage across OpenAI, Anthropic, Groq, Gemini, and more. > [card] [API Gateway Blueprint](/developer-resources/ingestion-blueprints/api-gateway) > > Meter API requests with endpoint filtering and rate limiting support. > [card] [Object Storage Blueprint](/developer-resources/ingestion-blueprints/object-storage) > > Track file uploads and storage consumption for cloud storage services. > [card] [Stream Blueprint](/developer-resources/ingestion-blueprints/stream) > > Measure streaming bandwidth for video, audio, and real-time data. > [card] [Time Range Blueprint](/developer-resources/ingestion-blueprints/time-range) > > Bill by elapsed time for serverless functions and compute instances. > [card] [View All Blueprints](/features/usage-based-billing/ingestion-blueprints) > > See all available blueprints with detailed implementation guides. ## Best Practices > [accordion] Use Unique Event IDs > > Use deterministic IDs to prevent duplicates: `${customerId}_${action}_${timestamp}`. > [accordion] Implement Retries > > Retry on 5xx and `429` errors with exponential backoff. Don't retry other 4xx errors. > [accordion] Include Timestamps > > Omit timestamps for real-time events. Include them for delayed or batch events for accuracy. > [accordion] Monitor Delivery > > Track success rates and queue failed events for retry. ## Troubleshooting > [accordion] Events not appearing > > * Event name must exactly match the meter (case-sensitive) > * Customer ID must exist in your account > * Check that meter filters aren't excluding events > * Verify timestamps are recent > [accordion] Authentication errors (401) > > Verify the API key is correct and use the format: `Bearer dodo_test_...`. > [accordion] Validation errors (400) > > Ensure all required fields are present: `event_id`, `customer_id`, `event_name`. > [accordion] Metadata not aggregating > > * Metadata keys must match the meter's "Over Property" exactly > * Use numbers, not strings: `tokens: 150` not `tokens: "150"` ## Next Steps > [card] [Create Meters](/features/usage-based-billing/meters) > > Define how your events are aggregated into billable quantities with filters and aggregation functions. > [card] [Ingestion Blueprints](/features/usage-based-billing/ingestion-blueprints) > > Use ready-made blueprints for common use cases like LLM tracking, API gateways, and storage. > [card] [Complete Tutorial](/developer-resources/usage-based-billing-build-ai-image-generator) > > Build a full AI image generator with usage-based billing from scratch. > [card] [API Reference](/api-reference/usage-events/ingest-events) > > Complete API documentation with all parameters, response codes, and interactive testing. # Ingestion Blueprints Source: https://docs.dodopayments.com/features/usage-based-billing/ingestion-blueprints Ready-made event ingestion patterns for common use cases with sample code. Ingestion blueprints are pre-built patterns for tracking usage in common scenarios. Instead of designing event structures and meter configurations from scratch, start with a proven blueprint and customize it for your needs. ## What Are Blueprints? Each blueprint includes: * **Event structure recommendations**: Optimal event naming and metadata design * **Meter configuration**: Suggested aggregation types and filters * **Sample code**: Working implementation examples in multiple languages * **Best practices**: Tips for accuracy, performance, and cost optimization > [!TIP] > > Blueprints save hours of setup time and help you avoid common pitfalls. Start with a blueprint, then adapt it to your specific requirements. ## Why Use Blueprints? > [card] Faster Setup > > Get usage tracking working in minutes instead of hours. Copy proven patterns instead of designing from scratch. > [card] Best Practices Built In > > Avoid common mistakes with tested event structures, proper metadata, and optimal aggregation choices. > [card] Production Ready > > Sample code is based on real-world implementations. Add your API keys and go. ## Available Blueprints Choose the blueprint that matches your use case: > [card] [LLM Blueprint](/developer-resources/ingestion-blueprints/llm) > > Track AI token usage across OpenAI, Anthropic, Groq, Gemini, Vercel AI SDK, and more. > > **Perfect for**: AI chatbots, code generators, content creation tools, AI-powered apps. > > **What you'll track**: Input tokens, output tokens, model usage, request counts. > [card] [API Gateway Blueprint](/developer-resources/ingestion-blueprints/api-gateway) > > Meter API requests at the gateway level with endpoint filtering and rate limiting support. > > **Perfect for**: REST APIs, GraphQL services, webhook providers, API-first platforms. > > **What you'll track**: Request counts, endpoint usage, HTTP methods, response times. > [card] [Object Storage Blueprint](/developer-resources/ingestion-blueprints/object-storage) > > Track file uploads, storage consumption, and bandwidth for cloud storage services. > > **Perfect for**: File hosting, media platforms, backup services, document management. > > **What you'll track**: Bytes stored, file uploads, downloads, storage snapshots. > [card] [Stream Blueprint](/developer-resources/ingestion-blueprints/stream) > > Measure streaming bandwidth for video, audio, and real-time data delivery. > > **Perfect for**: Video streaming, audio platforms, live broadcasts, real-time data feeds. > > **What you'll track**: Bandwidth consumed, stream duration, quality levels, concurrent streams. > [card] [Time Range Blueprint](/developer-resources/ingestion-blueprints/time-range) > > Bill by elapsed time for compute resources, serverless functions, and long-running jobs. > > **Perfect for**: Serverless platforms, container hosting, compute instances, batch processing. > > **What you'll track**: Execution time, compute hours, function invocations, job duration. ## How to Use a Blueprint **1. Choose your blueprint** Select the blueprint that best matches your billing scenario. Each blueprint page includes detailed implementation guides. **2. Review the event structure** Understand the recommended event naming and metadata design. Copy the event structure for your use case. **3. Create the meter** Follow the blueprint's meter configuration instructions. Use the suggested aggregation type and filters. **4. Implement event sending** Copy the sample code for your language or framework. Replace placeholder values with your actual API keys and customer IDs. **5. Test and verify** Send test events and verify they appear in your meter dashboard with correct aggregation. **6. Customize as needed** Adapt the blueprint to your specific requirements: add custom metadata, adjust filters, or modify pricing. ## Blueprint Comparison Not sure which blueprint fits your needs? Here's a quick comparison: | Use Case | Blueprint | Aggregation | Common Metadata | | - | - | - | - | | AI chat app | LLM | Sum (tokens) | model, input\_tokens, output\_tokens | | REST API | API Gateway | Count | endpoint, method, status\_code | | File storage | Object Storage | Sum (bytes) | file\_size, file\_type, operation | | Video platform | Stream | Sum (bandwidth) | duration, quality, bitrate | | Serverless | Time Range | Sum (duration) | function\_name, execution\_time\_ms | ## Custom Implementations Don't see a blueprint for your exact use case? No problem: 1. **Start with the closest blueprint**: Pick the one most similar to your needs. 2. **Adapt the event structure**: Modify metadata fields to match your requirements. 3. **Adjust meter configuration**: Change aggregation type or filters as needed. 4. **Test thoroughly**: Verify billing calculations with sample usage. > [!NOTE] > > All blueprints are starting points. Feel free to mix concepts from different blueprints or create entirely custom implementations. ## Need Help? If you're unsure which blueprint to use or need help customizing: > [card] [Complete Tutorial](/developer-resources/usage-based-billing-build-ai-image-generator) > > Follow our end-to-end tutorial building an AI image generator with usage billing. > [card] [Integration Guide](/developer-resources/usage-based-billing-guide) > > Comprehensive guide covering all aspects of usage-based billing implementation. # Usage-Based Billing Source: https://docs.dodopayments.com/features/usage-based-billing/introduction Charge customers based on what they actually use with flexible metering and automated billing. Usage-based billing charges customers for what they consume—API calls, storage, AI tokens, or any metric you define. Customers pay for what they use. You can add a fixed base fee, or set it to zero. > [!NOTE] > > **Best for**: APIs, AI services, infrastructure platforms, and any product where value scales with usage. ## How It Works **1. Send Usage Events** Your application sends events when billable actions occur. ```javascript theme={null} { "events": [ { "event_id": "evt_123", "customer_id": "cus_abc", "event_name": "api.call", "metadata": { "endpoint": "/v1/users" } } ] } ``` **2. Meters Aggregate Usage** Meters aggregate events into billable quantities using Count, Sum, Max, or Last aggregation. **3. Automatic Billing** Set pricing per unit and optional free thresholds. Customers are billed automatically each cycle. ## Core Concepts ### Events Events represent usage actions in your application. Each event includes: * **Event Name**: Type of usage (e.g., `api.call`) * **Customer ID**: Who used it * **Metadata**: Additional properties for aggregation and filtering ### Meters Meters aggregate events into billable quantities: * **Count**: Total number of events (API calls, uploads) * **Sum**: Sum of numeric values (total bytes, tokens) * **Max**: Highest value in the period (peak users, max storage) * **Last**: Most recent value ![Meter creation interface showing event name, aggregation type, and filtering options](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-2.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=f9d85a463fba231437151db3d4a2052a) ### Products with Usage Pricing Set pricing per unit and optional free thresholds: ![Product pricing configuration for usage-based billing](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-4.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=b2d07bb408fd79e1b788c1b7092b8bca) **Example**: 2,500 calls minus 1,000 free = 1,500 chargeable calls × \$0.02 = \$30.00 ### Credit-Based Deduction Instead of charging per-unit in dollars, you can configure meters to deduct from a customer's [credit balance](/features/credit-based-billing). Credits refresh each billing cycle and apply before any overage charges. ## Quick Start **1. Create a Meter** Go to **Meters** in the dashboard and click **Create Meter**. 1. Enter an event name (e.g., `api.call`) 2. Choose an aggregation type (Count, Sum, Max, or Last) 3. Add optional filters to exclude certain events **2. Add Meter to a Product** Link the meter to a product and set pricing: ![Adding a meter to a product with pricing configuration](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-5.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=fd3851a1a070714baf0aec01cff717b8) 1. Go to **Products** and select or create a product 2. Select **Usage Based Billing** as the pricing type 3. Choose your meter 4. Set the price per unit and optional free threshold **3. Send Events** ```javascript theme={null} await fetch('https://test.dodopayments.com/events/ingest', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.DODO_PAYMENTS_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [{ event_id: "unique_event_id", customer_id: "cus_abc123", event_name: "api.call", metadata: { endpoint: "/v1/users" } }] }) }); ``` **4. Monitor Usage** ![Meter dashboard showing usage trends over time](https://mintcdn.com/dodopayments/16r81mgDWvSgYER7/images/guides/usage-based-billing/meter-quantities-chart.png?fit=max\&auto=format\&n=16r81mgDWvSgYER7\&q=85\&s=1a8a39547bd0259a53d4591d7928c8ea) View your meter's dashboard to see events and aggregated usage. Customers are billed automatically each billing cycle. ## Use Cases > [card] APIs and Infrastructure > > Track API calls, compute hours, bandwidth, or storage. Example: \$0.001 per call after 10,000 free calls. > [card] AI Usage Tracking > > Track tokens, image generations, or processing time. Example: \$0.04 per standard image, \$0.08 per HD image. > [card] Data and Analytics > > Bill by data processed, queries run, or records analyzed. Example: \$5 per GB after 10 GB free. > [card] Communication > > Count messages, minutes, or data transferred. Example: \$0.01 per SMS sent. ## Next Steps > [card] [Event Ingestion](/features/usage-based-billing/event-ingestion) > > Learn how to structure and send usage events from your application. > [card] [Meters Guide](/features/usage-based-billing/meters) > > Master meter configuration, aggregation types, and event filtering. > [card] [Complete Tutorial](/developer-resources/usage-based-billing-build-ai-image-generator) > > Build a complete AI image generator with usage-based billing from scratch. > [card] [Integration Guide](/developer-resources/usage-based-billing-guide) > > Comprehensive guide to implementing usage-based billing in your application. # Meters Source: https://docs.dodopayments.com/features/usage-based-billing/meters Transform raw usage events into billable quantities with aggregation and filtering. Meters convert raw events into billable quantities. They filter events and apply aggregation functions (Count, Sum, Max, Last) to calculate usage per customer. ![Meter creation interface showing event name, aggregation type, and filtering options](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-2.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=f9d85a463fba231437151db3d4a2052a) ## API Resources > [accordion] View Meter API References > > > [card] [Create Meter](/api-reference/meters/create-meter) > > > > Create meters programmatically via API. > > > [card] [List Meters](/api-reference/meters/get-meters) > > > > Retrieve all meters in your account. > > > [card] [Get Meter](/api-reference/meters/retrieve-meter) > > > > Fetch details for a specific meter by ID. > > > [card] [Update Meter](/api-reference/meters/update-meter) > > > > Change a meter's name, description, or measurement unit. > > > [card] [Archive Meter](/api-reference/meters/archive-meter) > > > > Archive a meter to stop tracking usage. > > > [card] [Unarchive Meter](/api-reference/meters/unarchive-meter) > > > > Restore an archived meter to resume tracking. ## Creating a Meter **1. Basic Information** **Meter Name** `string` *required* A descriptive name for the meter (e.g., "API Requests", "Token Usage"). **Event Name** `string` *required* The exact event name to match (case-sensitive). Examples: `api.call`, `image.generated`. **2. Aggregation** **Aggregation Type** `string` *required* Choose how events are aggregated: * **Count**: Total number of events (API calls, uploads) * **Sum**: Sum of numeric values (tokens, bytes) * **Max**: Highest value in the period (peak users) * **Last**: Most recent value **Over Property** `string` The metadata key to aggregate (required for Sum, Max, and Last). Examples: `tokens`, `bytes`, `duration_ms`. **Measurement Unit** `string` *required* The unit label for invoices and reports. Examples: `calls`, `tokens`, `GB`, `hours`. **3. Filtering (Optional)** ![Event filtering interface with AND/OR logic and comparison operators](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-3.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=ce231b0559d31723bc12c22cd9ff9d64) Add conditions to filter which events are counted: * **AND logic**: All conditions must match * **OR logic**: Any condition can match Available comparators: equals, not equals, greater than, greater than or equals, less than, less than or equals, contains, does not contain. Enable filtering, choose your logic, then add conditions with a property key, comparator, and value. **4. Create** Review your configuration and click **Create Meter**. ## Editing a Meter To edit a meter in the dashboard, open the meter's menu and select **Edit**. You can change the **name**, **description**, and **measurement unit**. These fields don't affect billing. The event name, aggregation, and filter are read-only after creation. To change how a meter bills, archive it and create a new meter. Through the API, [Update Meter](/api-reference/meters/update-meter) accepts `name`, `description`, and `measurement_unit` only, and returns `422` for any other field. Send `"description": null` to remove the description. ## Viewing Analytics ![Meter analytics dashboard showing usage overview, events, and customer data](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-1.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=7fb86a266b5aa84f281b680601bd998e) Your meter dashboard displays: * **Overview**: Total usage and usage trends over time * **Events**: Individual events received and their metadata * **Customers**: Per-customer usage totals and charges ## Billing in Credits Instead of Currency By default, meters charge customers per-unit in dollars (or your configured currency). You can instead configure a meter to deduct from a customer's credit balance, so usage consumes credits rather than generating a monetary charge. > [!NOTE] > > Credit-based deduction requires a [Credit Entitlement](/features/credit-based-billing) attached to the same product. Create the credit entitlement first, then link it to the meter. ### When to Use Credit-Based Deduction | Scenario | Standard (currency) | Credit-based | | - | - | - | | Simple per-unit pricing (\$0.01/call) | ✅ Best fit | Unnecessary overhead | | Prepaid credit packs (buy 10K tokens, use over time) | ❌ Can't express | ✅ Best fit | | Bundled usage with subscriptions (Pro plan includes 100K calls) | Possible via free threshold | ✅ Better: credits roll over, expire, and show in portal | | Multi-meter products sharing a credit pool | ❌ Each meter bills separately | ✅ All meters deduct from one balance | ### Configuring a Meter to Deduct Credits **1. Create a Credit Entitlement** First, create a credit entitlement in **Products → Credits**. Define the unit (e.g., "API Calls", "Tokens"), precision, and lifecycle settings (expiry, rollover, overage). See the [Credit-Based Billing guide](/features/credit-based-billing) for detailed instructions. **2. Create or Edit a Usage-Based Product** Go to your usage-based product and open the **Meter** configuration section. **3. Add a Meter** Click the **+** button to attach a meter. Configure the event name, aggregation type, and measurement unit as usual. **4. Enable 'Bill Usage in Credits'** Toggle **Bill usage in Credits** on the meter configuration to reveal credit settings: ![Meter configuration with Bill usage in Credits toggle enabled](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20UBB-5.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=b4ef2fe5079cbf3bb39eb3814f101cbd) Toggle 'Bill usage in Credits' to switch from currency-based to credit-based deduction. **Credit Entitlement** `string` *required* Select which credit entitlement this meter deducts from. **Meter units per credit** `number` *required* The number of usage units required to deduct 1 credit. For example: * `1` = each meter event deducts 1 credit * `100` = 100 meter events deduct 1 credit * `1000` = 1,000 API calls consume 1 credit **5. Free Threshold and Credits** The **Free Threshold** applies to meters billed in money, not to meters billed in credits. When a meter bills in credits, every unit counts toward credit deduction. **Example**: With meter-units-per-credit of 1, a customer who makes 2,500 API calls has 2,500 credits deducted. ### How Credit Deduction Works Once configured, the deduction pipeline runs automatically: 1. **Events arrive** — Your application sends usage events via the [Event Ingestion API](/features/usage-based-billing/event-ingestion). 2. **Meter aggregates** — Events are aggregated per your meter configuration (Count, Sum, Max, Last). 3. **Background worker processes** — Every minute, a worker fetches new events since the last checkpoint. 4. **Credits are deducted** — Aggregated usage is converted to credits using the `meter_units_per_credit` rate and deducted using FIFO ordering (earliest-expiring grants consumed first). 5. **Overage tracked** — If the balance hits zero, further usage is recorded as overage and handled according to the configured behavior (forgiven at reset, billed at next invoice, or carried forward as deficit). Dodo Payments doesn't block usage when the balance runs out. To stop access at zero, check the balance in your application. ```mermaid theme={null} flowchart LR A[Usage Event] --> B[Meter Aggregation] B --> C{Credits Available?} C -->|Yes| D[Deduct from Balance] C -->|No| E{Overage Enabled?} E -->|Yes| F[Track Overage] E -->|No| G[Your App Enforces Limits] D --> H[Update Ledger] F --> H ``` > [!WARNING] > > Credit deduction runs asynchronously (every \~1 minute). There may be a brief delay between event ingestion and balance deduction. Design your application to handle this delay and don't rely on real-time balance checks for access control on individual requests. ### Multiple Meters, One Credit Pool You can link multiple meters on the same product to the same credit entitlement. All meters deduct from one shared balance. **Example**: An AI platform with two meters: * `text.generation` — 1 credit per 1,000 tokens * `image.generation` — 10 credits per image Both deduct from the same "AI Credits" pool. The customer sees a single unified balance in their portal. > [!TIP] > > Use different `meter_units_per_credit` rates across meters to express relative costs. Expensive operations (image generation) cost fewer meter units per credit than cheap ones (text completion). > [card] [List Customer Ledger](/api-reference/credit-entitlements/list-customer-ledger) > > View the full credit deduction history for a customer. > [card] [Get Customer Balance](/api-reference/credit-entitlements/get-customer-balance) > > Check a customer's current credit balance via API. ## Troubleshooting > [accordion] Events not appearing > > * Event name must match exactly (case-sensitive) > * Check that meter filters aren't excluding events > * Verify customer IDs exist in your account > * Temporarily disable filters to test > [accordion] Aggregation not working > > * Verify the Over Property matches the metadata key exactly > * Use numbers, not strings: `tokens: 150` not `tokens: "150"` > * Include required properties in all events > [accordion] Filters not working > > * Match case exactly > * Use correct operators for the data type > * Ensure events include the filtered properties > [accordion] Wrong usage totals > > * Check the Events tab to count actual events received > * Verify the aggregation type (Count vs Sum) > * Ensure values are numeric for Sum and Max ## Next Steps > [card] [Send Events](/features/usage-based-billing/event-ingestion) > > Start sending usage events from your application to your meters. > [card] [View Blueprints](/features/usage-based-billing/ingestion-blueprints) > > Use ready-made meter configurations for common use cases. > [card] [Pricing as Code](/developer-resources/terraform-provider) > > Define meters and usage-based prices with Terraform. # Welcome to Dodo Payments Source: https://docs.dodopayments.com/introduction Dodo Payments is a Merchant of Record for SaaS, AI, and digital products. Sell in 220+ countries while Dodo Payments handles payments, tax, and billing. ![Dodo Payments: Payments and billing built for your product, with dashboard and hosted checkout previews](https://mintcdn.com/dodopayments/nM_mJfYkri-OpC5M/images/introduction/intro-product-cover.png?fit=max\&auto=format\&n=nM_mJfYkri-OpC5M\&q=85\&s=bba7c6c9657aae77ecc960940dc73fab) Dodo Payments is a **Merchant of Record** for SaaS, AI, and digital products. It sells your product to customers in 220+ countries as the legal seller, so payment processing, sales tax and VAT, fraud screening, and chargebacks are handled for you. You add your products, choose how customers check out, and receive payouts. > [card] [Integrate with Your Coding Agent](/developer-resources/build-with-ai-coding-agents) > > Install the Agent Plugin and have your coding agent build the integration. > [card] [Start Integrating](/developer-resources/integration-guide) > > Install an SDK, create a checkout session, and handle webhooks. > [card] [How Merchant of Record Works](/features/mor-introduction) > > What Dodo Payments takes on as the legal seller, and what stays with you. ## What Dodo Payments Handles > [card] [Merchant of Record](/features/mor-introduction) > > Dodo Payments sells to your customers, then calculates and remits the tax on each sale. > [card] [Global Payments](/features/payment-methods) > > 40+ payment methods, including cards, wallets, bank debits, and BNPL (buy now, pay later). > [card] [Local Currencies](/features/adaptive-currency) > > Adaptive Currency shows prices in 80+ local currencies at checkout. > [card] [Flexible Billing](/features/subscription) > > One-time payments, subscriptions, usage-based, credit-based, and seat-based billing, with add-ons. ## Get Started To sell with Dodo Payments, your product must meet the [Merchant Acceptance Policy](/miscellaneous/merchant-acceptance), and your identity document must come from an [eligible country](/miscellaneous/accepted-countries-and-territories). Check both before you sign up. **1. Create Your Account** Sign up at [app.dodopayments.com](https://app.dodopayments.com/signup) and verify your email address. **2. Add Your First Product** Choose the billing model that matches how you charge. > [card] [One-Time Payment](/features/one-time-payment-products) > > A single charge for a download, course, or license. > [card] [Subscription](/features/subscription) > > A recurring charge for SaaS plans and memberships. > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Charge for metered usage such as API calls or tokens. > [card] [Credit-Based Billing](/features/credit-based-billing) > > Grant credits and deduct them as customers consume, with rollover and overage controls. > [card] [Seat-Based Billing](/features/seat-based-billing) > > Charge per user or seat, with proration when a team adds or removes seats. **3. Choose How Customers Check Out** > [tab] Payment Links > > Create a payment link in the dashboard and share it by email, on social media, or on your site. No code is required. > > > [card] [Payment Links](/developer-resources/integration-guide#payment-links) > > > > Create static and dynamic payment links. > [tab] Overlay Checkout > > Open checkout as an overlay on your page, so customers pay without leaving your site. > > > [card] [Overlay Checkout](/developer-resources/overlay-checkout) > > > > Add the overlay to your site and match it to your brand. > [tab] Inline Checkout > > Embed checkout in your page layout and build your own order summary around it. > > > [card] [Inline Checkout](/developer-resources/inline-checkout) > > > > Embed checkout and keep your summary in sync with it. > [tab] API and SDKs > > Create checkout sessions and customers, and manage subscriptions, from your backend with an official SDK, and react to events with webhooks. To have a coding agent write this integration, install the [Agent Plugin](#build-with-ai-coding-agents) first. > > > [card] [Integration Guide](/developer-resources/integration-guide) > > > > Install an SDK and build your first checkout. > > > [card] [API Reference](/api-reference/introduction) > > > > Every endpoint, parameter, and response. **4. Test Your Integration** Build in test mode, which simulates payments, refunds, and failed transactions without moving real money. > [card] [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode) > > What works in each mode and how to switch. > [card] [Testing Process](/miscellaneous/testing-process) > > Test cards, UPI, BNPL, wallets, and bank debits. **5. Verify Your Account to Go Live** You can set up live mode as soon as you sign up. Live payments and payouts turn on after your account passes verification. > [card] [Account Verification](/miscellaneous/verification-process) > > Required documents and how review works. ## Build with AI Coding Agents To integrate Dodo Payments with a coding agent, install the Agent Plugin. It gives your coding agent one MCP server, which searches the Dodo Payments documentation and runs API operations on your account, plus a `dodo-payments` skill that describes how to build each integration. After you install it, describe what you want to build. > [card] [Agent Plugin](/developer-resources/build-with-ai-coding-agents) > > Installs the MCP server and the `dodo-payments` skill in Claude Code, Codex CLI, Cursor, VS Code / GitHub Copilot, Gemini CLI, Grok Build, Kiro, OpenCode, and more. > [card] [Dodo Payments MCP](/developer-resources/mcp-server) > > Searches the docs and the SDK, and runs SDK code against your account after you sign in. To install the plugin in Claude Code, run: ```bash theme={null} claude plugins marketplace add dodopayments/dodo-agent-plugin claude plugins install dodopayments@dodopayments ``` For other agents, see [Build with AI Coding Agents](/developer-resources/build-with-ai-coding-agents#install-the-plugin). To install the skills without the plugin, run: ```bash theme={null} npx skills add dodopayments/skills ``` To install individual skills or set them up in other clients, see [Agent Skills](/developer-resources/agent-skills). To connect an MCP client yourself, add the server at `https://mcp.dodopayments.com/mcp`. If your client only runs local commands, use the `mcp-remote` bridge. This requires Node.js 18 or later: ```json theme={null} { "mcpServers": { "dodopayments": { "command": "npx", "args": ["-y", "mcp-remote@latest", "https://mcp.dodopayments.com/mcp"] } } } ``` Your client signs you in when you add the server. If your client can't sign in, or you only need docs search, use `https://mcp.dodopayments.com/mcp?auth=optional`: the docs tools then work without an account. See the [MCP Server](/developer-resources/mcp-server) guide for per-client setup. Agents that read documentation directly can start from the index at [`docs.dodopayments.com/llms.txt`](https://docs.dodopayments.com/llms.txt). Every page is also available as Markdown: add `.md` to its URL, for example `/api-reference/introduction.md`. ## Developer Tools [Dodo Payments developer integration walkthrough](https://www.youtube.com/embed/gyqFJaJ5Wh4) ### SDKs Official server SDKs are available in nine languages. > [card] [TypeScript](/developer-resources/sdks/typescript) > [card] [Python](/developer-resources/sdks/python) > [card] [Go](/developer-resources/sdks/go) > [card] [PHP](/developer-resources/sdks/php) > [card] [Java](/developer-resources/sdks/java) > [card] [Kotlin](/developer-resources/sdks/kotlin) > [card] [C#](/developer-resources/sdks/csharp) > [card] [Ruby](/developer-resources/sdks/ruby) > [card] [Rust](/developer-resources/sdks/rust) For billing UI such as pricing tables and subscription management, [Billing SDK](/developer-resources/billingsdk) provides free, open-source React components. ### Framework Adaptors Adaptors add checkout, customer portal, and webhook handlers to your framework. > [card] [Next.js](/developer-resources/nextjs-adaptor) > > Route handlers for checkout, the customer portal, and webhooks in the App Router. > [card] [Better Auth](/developer-resources/better-auth-adaptor) > > Create a customer when a user signs up, and add checkout and the customer portal to your auth flow. > [card] [Supabase](/developer-resources/supabase-boilerplate) > > A Next.js and Supabase starter with auth, a database schema, webhooks, and a pricing page. > [card] [Convex](/developer-resources/convex-component) > > Checkout, customer portal, and webhook functions for your Convex backend. > [accordion] All Other Framework Adaptors > > > [card] [SvelteKit](/developer-resources/sveltekit-adaptor) > > > [card] [Nuxt](/developer-resources/nuxt-adaptor) > > > [card] [Remix](/developer-resources/remix-adaptor) > > > [card] [Express](/developer-resources/express-adaptor) > > > [card] [Fastify](/developer-resources/fastify-adaptor) > > > [card] [Hono](/developer-resources/hono-adaptor) > > > [card] [Astro](/developer-resources/astro-adaptor) > > > [card] [TanStack](/developer-resources/tanstack-adaptor) > > > [card] [Bun](/developer-resources/bun-adaptor) ### Mobile Checkout Official checkout SDKs open hosted checkout from Android, iOS, React Native, and Flutter apps and return the result to your app. > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > Checkout, subscriptions, and customization for each platform. > [card] [Expo Boilerplate](/developer-resources/expo-boilerplate) > > An Expo template with checkout and payment handling in TypeScript. ### Dodo CLI The Dodo CLI manages payments, customers, and webhooks from your terminal. It includes an interactive TUI, an AI assistant, and a webhook listener for local testing. To install it, run: ```bash theme={null} curl -fsSL https://dodopayments.com/install.sh | sh ``` > [card] [Dodo CLI](/developer-resources/sdks/cli) > > Commands, the TUI, and local webhook testing. ## Integrations Integrations send Dodo Payments events to the tools you already use, such as team chat, email, CRM, and workflow automation. > [card] [Framer](/integrations/framer-plugin) > > Add payments to Framer sites. > [card] [WooCommerce](/integrations/woocommerce-plugin) > > Accept payments in WooCommerce stores. > [card] [Raycast](/integrations/raycast-extension) > > Manage payments from Raycast. > [card] [Figma](/integrations/figma-plugin) > > Use Dodo Payments inside Figma. > [accordion] Team Notifications > > > [card] [Slack](/integrations/slack) > > > > Post payment events to Slack channels. > > > [card] [Discord](/integrations/discord) > > > > Post payment events to a Discord server. > > > [card] [Microsoft Teams](/integrations/microsoft-teams) > > > > Post payment events to Teams channels. > [accordion] Email > > > [card] [Resend](/integrations/resend) > > > > Send transactional email with Resend. > > > [card] [SendGrid](/integrations/sendgrid) > > > > Send email with SendGrid. > > > [card] [Loops](/integrations/loops) > > > > Trigger email sequences in Loops. > > > [card] [Customer.io](/integrations/customer-io) > > > > Sync customer data to Customer.io. > > > [card] [AutoSend](/integrations/autosend) > > > > Send transactional email with AutoSend. > [accordion] CRM > > > [card] [Close CRM](/integrations/close-crm) > > > > Sync customers and deals to Close. > [accordion] Automation and Analytics > > > [card] [Zapier](/integrations/zapier) > > > > Connect payment events to other apps through Zapier. > > > [card] [n8n](/integrations/n8n) > > > > Build workflows in self-hosted or cloud n8n. > > > [card] [Windmill](/integrations/windmill) > > > > Run custom workflows in Windmill. > > > [card] [Inngest](/integrations/inngest) > > > > Run event-driven functions in Inngest. > > > [card] [Segment](/integrations/segment) > > > > Stream payment events to Segment. > > > [card] [DataFast](/integrations/datafast) > > > > Attribute revenue to marketing channels. > [card] [All Integrations](/integrations/introduction) > > Setup guides for every integration. ## Get Help > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. > [card] [Contact Support](mailto:support@dodopayments.com) > > Email the support team at [support@dodopayments.com](mailto:support@dodopayments.com). # Migrate to Dodo Payments Source: https://docs.dodopayments.com/migrate-to-dodo Move your products, customers, discount codes, and license keys from Lemon Squeezy, Stripe, Polar.sh, or Paddle to Dodo Payments. Dodo Migrate is a CLI tool that moves your data from Lemon Squeezy, Stripe, Polar.sh, or Paddle to Dodo Payments. It prompts you for each choice and can migrate into test mode first, so you can check the result before you move live data. ## What You Can Migrate > [card] Products & Pricing > > Products and their prices. > [card] Customers > > Customer records, including contact details. > [card] Discount Codes > > Discount codes and coupons. > [card] License Keys > > License keys with customer and product mappings (Polar.sh and Lemon Squeezy only). The tool doesn't migrate subscriptions, payment history, or saved cards. To move your existing subscribers and their saved cards from Stripe, Paddle, or another processor, see [Subscription Migration](/miscellaneous/subscription-migration#how-your-cards-move). To move saved cards from Dodo Payments to another processor, see [Request a Card Data Export](/miscellaneous/card-data-export). ## Install the Tool ```bash theme={null} npm install -g dodo-migrate ``` You'll need Node.js 18 or later. ## Run a Migration Choose the command for your current provider: > [tab] Lemon Squeezy > > ```bash theme={null} > dodo-migrate lemonsqueezy > ``` > [tab] Stripe > > ```bash theme={null} > dodo-migrate stripe > ``` > [tab] Polar.sh > > ```bash theme={null} > dodo-migrate polar > ``` > [tab] Paddle > > ```bash theme={null} > dodo-migrate paddle > ``` The tool prompts you for: * Your provider's API key * Your Dodo Payments API key * Whether to test first or go live * Which Dodo Payments brand to migrate to * Which data to migrate (products, customers, discounts, license keys) ## Non-Interactive Mode To skip the prompts, pass values as flags. `--mode` takes `test_mode` or `live_mode`. Use a Dodo Payments API key created in the same mode. If you omit `--dodo-brand-id`, the tool lists your brands and asks you to pick one. The flag that selects what to migrate is `--types` for Lemon Squeezy and `--migrate-types` for the other providers. If you omit it, the tool asks you to choose. When no terminal is attached, Paddle migrates only products and Polar.sh migrates products and discounts. > [tab] Lemon Squeezy > > ```bash theme={null} > dodo-migrate lemonsqueezy \ > --provider-api-key=lsq_XXXXXXXXXXXXXXXX \ > --dodo-api-key=dodo_test_... \ > --mode=test_mode \ > --dodo-brand-id=YOUR_BRAND_ID \ > --types=products,coupons,customers,license_keys > ``` > [tab] Stripe > > ```bash theme={null} > dodo-migrate stripe \ > --provider-api-key=sk_test_XXXXXXXXXXXXXXXX \ > --dodo-api-key=dodo_test_... \ > --mode=test_mode \ > --dodo-brand-id=YOUR_BRAND_ID \ > --migrate-types=products,coupons > ``` > [tab] Polar.sh > > ```bash theme={null} > dodo-migrate polar \ > --provider-api-key=polar_org_XXXXXXXXXXXXXXXX \ > --dodo-api-key=dodo_test_... \ > --mode=test_mode \ > --dodo-brand-id=YOUR_BRAND_ID \ > --migrate-types=products,discounts,customers,license_keys > ``` > [tab] Paddle > > ```bash theme={null} > dodo-migrate paddle \ > --provider-api-key=paddle_XXXXXXXXXXXXXXXX \ > --dodo-api-key=dodo_test_... \ > --mode=test_mode \ > --dodo-brand-id=YOUR_BRAND_ID > ``` ## License Key Migration License keys can be migrated from Polar.sh and Lemon Squeezy. When you select license keys in the interactive prompt, or pass `license_keys` in `--types` (Lemon Squeezy) or `--migrate-types` (Polar.sh), the tool imports your existing keys with the correct customer and product associations. > [!WARNING] > > License key migration requires products and customers to be migrated in the same session. The tool builds an in-memory mapping of provider IDs to Dodo IDs during the run. If products or customers are missing, license keys cannot be linked correctly. ### What Migrates * License key strings * Activation limits * Expiration dates * Customer and product associations ### What Doesn't Migrate * **License key activations** — customers must re-activate on their devices after migration. * **Revoked or disabled keys** — only active keys are migrated. * Keys without a matching product or customer are skipped with a warning. > [!TIP] > > If you re-run the migration, already-imported keys are detected and skipped, so it's safe to retry. ## Get Help * **Tool help**: `dodo-migrate --help` * **Provider-specific help**: `dodo-migrate lemonsqueezy --help` (or `stripe`, `polar`, `paddle`) * **Community**: [Discord](https://discord.gg/bYqAp4ayYh) * **Report issues**: [GitHub](https://github.com/dodopayments/dodo-migrate) ## Update or Uninstall ```bash theme={null} # Update to the latest version npm update -g dodo-migrate # Remove the tool npm uninstall -g dodo-migrate ``` # My Account Source: https://docs.dodopayments.com/miscellaneous/accounts Edit your business profile and personal details, change the email you sign in with, and add more businesses to your Dodo Payments account. ## Business Profile Your business name and logo are set on your primary brand, so you edit them there. **1. Access Your Business Profile** Go to **Settings → Business**. In the **Brands Under \[Your Business]** panel, open the `...` menu next to your primary brand and select **Edit**. **2. Edit and Save Business Details** Update the details, such as the **Brand Logo** and the **Brand Name**, which is the display name your invoices show. Then click **Save Changes**. ## User Account **1. Access Your User Profile** Click the icon in the top-right corner, then select **Profile**. This opens **Settings → Account**. **2. Edit and Save Personal Details** Click **Edit Personal Details**, update your first name, last name, phone number, or profile image, then click **Save Changes**. The **Security** section on the same page holds your password and two-factor authentication settings. ## Active Sessions The **Active sessions** card on **Settings → Account** lists the devices that are signed in to your account. Each row shows the browser and operating system, the IP address, when the session signed in, and when it was last active. Your current session comes first, with a **This device** badge. * To end one session, click **Sign out** on its row. * To end every session except the current one, click **Sign out of other sessions**. * To end every session, including the current one, click **Sign out everywhere**. You then sign in again. A device that you sign out must sign in again. ## Change Your Login Email You can change the email address you use to sign in to Dodo Payments. The change applies to all your businesses, and you verify both your current and your new email address. **1. Open Your Profile Menu** Click the icon in the top-right corner of the dashboard. **2. Go to Profile** Select **Profile** from the menu. **3. Open the Account Tab** Make sure the **Account** tab is selected. **4. Start the Email Change** Click **Change email**, read the summary of the change, and click **Continue**. **5. Enter Your New Email** Type the new email address in **New email address** and again in **Confirm email address**, then click **Continue**. **6. Verify Both Emails** Dodo Payments sends a 6-digit code to your current email address and another to your new one. Each code is valid for 5 minutes. Enter both codes, then click **Verify**. **7. Sign In Again** After the change, Dodo Payments signs you out automatically. Sign in again with your new email address. > [!WARNING] > > After you change your login email, your old email address no longer works for sign-in, whether by password, magic link, or emailed code. Linked social sign-in methods, such as Google or GitHub, are unlinked. Reconnect them if you want to use them again. > [!NOTE] > > Your password, businesses, team access, and verification status don't change. Dodo Payments sends a confirmation email to your previous address to notify you of the change. ## Managing Multiple Businesses If you run more than one business, you can add and verify each one from the same Dodo Payments account. Each business is a separate legal entity with its own KYC and payout account. To run another brand under the same business instead, see [Multi-Brand Setup](/features/multi-brands). **Workflow: Add a New Business** **1. Open the Business Switcher** At the top of the sidebar, click your current business name. It shows a **+** icon when you have one business. **2. Select Add New Business** In the menu that opens, select **Add new business**. **3. Choose to Add a Business** A panel titled **Add new business/brand** opens on the right side of the screen. Under **Add a new business**, click **Add new business**. **4. Enter the Business Details** Enter the **Business Name** and **Website URL**, select the country you operate from and the category of your business, then click **Add business**. **5. Complete the Business Creation Process** Follow the on-screen prompts to finish creating the business. To accept live payments, the new business then goes through [verification](/miscellaneous/verification-process). # Account Verification Source: https://docs.dodopayments.com/miscellaneous/verification-process Complete account verification to turn on live payments and payouts. Learn which forms you need, how identity and business checks work, and how review works. You can use live mode from the day you sign up, but your account can't accept live payments until every required verification form is approved, and it can't receive payouts until compliance review is also complete. To verify, choose your account type, submit your product and payout details, and pass compliance review. > [!NOTE] > > For supported and prohibited product categories and accepted business locations, see the [Merchant Acceptance Policy](/miscellaneous/merchant-acceptance). ## Account Verification The Verification section in your dashboard guides you through four steps: account type, product information, identity verification, and payout details. ### Account Type Choose whether you're an **Individual** or a **Registered Entity** before you start. | Individual | Registered Entity | | - | - | | You're a creator or sole proprietor | Your business is registered (Pvt Ltd, LLP, LLC, etc.) | | Payments and payouts are tied to you personally | You have a GST, EIN, or other business tax ID | | You don't have a company registration or business tax ID | Payouts are tied to your company bank account | ![Verification Dashboard](https://mintcdn.com/dodopayments/uqnIPQF1xKJ8eNrW/images/payouts/verification-dashboard.png?fit=max\&auto=format\&n=uqnIPQF1xKJ8eNrW\&q=85\&s=2508652692201b1b2b479ab8f54641fa) ### Verification Steps **1. Choose your account type** Select **Individual** or **Registered Entity** based on how you operate. **2. Submit product information** Complete the **Product Information Form**. Before you submit, publish your website and check that it matches what you enter. See [Preparing Your Website](#preparing-your-website). **3. Verify your identity** Complete identity verification (KYC) with a government-issued ID. Registered entities also complete business verification (KYB). **4. Submit payout details** Provide your bank account information. Forms unlock sequentially — complete each one before the next appears. > [!NOTE] > > Most reviews finish within 1–3 business days. > [!WARNING] > > Live payments turn on after every required form for your account type is approved. Payouts also need a completed Monitoring Review. See [Live Payments vs. Payouts](#live-payments-vs-payouts). ### Required Forms Forms unlock sequentially. Complete each one before the next appears. | Account Type | Forms (in order) | | - | - | | **Individual** | Product Information → Identity Verification (KYC) → Bank Verification | | **Registered Entity** | Product Information → Identity Verification (KYC) → Business Verification (KYB) → Bank Verification | UK registered entities must also submit the [W-8BEN-E tax form](#w-8ben-e-for-uk-entities). ### Changing Your Account Type You can change your account type while all forms are under review. Once any form is approved, failed, or on hold, you can no longer change it here. To change it after that, for example after you incorporate, the Owner can start an [entity transfer](/features/entity-transfer). If you change your account type after you submit the bank form, while your forms are still under review, your bank verification goes on hold and you must resubmit. Switching from Individual to Registered Entity also requires the Business Verification form. Your Product Information and Identity Verification are preserved. ## Product Information Form All merchants complete this form. To finish it later, select **Save as Draft**. Save as Draft is also available on the Bank Verification and Business Verification forms. The form collects: * **Product website or landing page** — where customers learn about or purchase your product * **Product description** — one sentence explaining what it does * **Product category** — SaaS, digital content, services, marketplace, or physical goods * **Delivery method** — instant access, email, subscriptions, manual fulfillment, etc. * **Level of automation** — fully automated, partially automated, or human-driven * **Compliance-sensitive areas** — any regulated, restricted, or higher-risk product types * **Integration method** — payment links, checkout sessions, APIs, SDKs, etc. * **Product stage and customer acquisition** — maturity and go-to-market approach * **Social media presence** — links to your product or founder profiles * **Confirmation** — acknowledgement that information is accurate and policy-compliant The verification team uses this information for the compliance review. ## Preparing Your Website Your form is reviewed against your live website. Publish your site before you submit. A URL the review team cannot open is a common reason for a hold. Before you submit, verify that a visitor with no account can reach your site and find: * **Pricing** — what you charge, including billing interval for recurring plans * **Terms of Service** — the agreement customers accept when they buy * **Privacy Policy** — how you collect, store, and use customer data * **Refund and Cancellation Policy** — how customers request refunds or cancel subscriptions * **Contact route** — a monitored support address or contact form Link these from a consistent place, such as your footer, so they're reachable from every page. Your live site must match what you enter in the form, including product description, pricing, and delivery method. Mismatches are a common reason for holds. > [!TIP] > > Generate a first draft with the [Policy Generator](https://dodopayments.com/tools/policy-generator) and adapt it to your business. ## Identity Verification (KYC) We use Persona, a global verification provider, to verify your government-issued ID and confirm liveness with a selfie. The process completes within minutes. Your ID must be issued by a country on our [accepted countries list](/miscellaneous/accepted-countries-and-territories). This applies to you as an individual, and to every director and beneficial owner of a registered entity, regardless of where the entity is incorporated. > [!TIP] > > See [Persona's security measures](https://withpersona.com/security). ### Camera Access Issues If you see "Can't access your camera," enable camera permissions for your device and browser: * **Chrome:** Enable through browser settings (Desktop, iPhone & iPad, or Android) * **Safari:** Desktop — enable through preferences. Mobile — Settings → Safari → Camera, set to "Ask" or "Allow" * **iOS Apps:** Settings → Apps → \[Your App] → Allow Camera permissions. Ensure Lockdown Mode is not blocking the app * **Android Apps:** Settings → Apps → \[Your App] → Allow Camera permissions See [Persona's camera access guide](https://help.withpersona.com/articles/3V9VoOoGLp6zRCwthpzpx4/) for detailed troubleshooting. ### If Identity Verification Fails Verification can fail even with genuine documents if the capture doesn't give Persona enough to work with. Common causes: * **Your photo no longer matches your ID.** An old ID may not match your current appearance closely enough for the selfie check. * **You captured from a screen or photocopy.** Use the original physical document. * **The capture is blurry, cropped, or has glare.** Every edge must be visible and all text readable. * **Your document has expired.** * **Your ID is from an unsupported country.** Check the [accepted countries list](/miscellaneous/accepted-countries-and-territories). You get three attempts. After each failure, the dashboard shows the reason and how many attempts remain. Once all three are used, email [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email to re-enable the form. Before retrying, have a valid, unexpired, physical government-issued photo ID ready. Complete the check in a well-lit place with camera permissions already granted. Getting the capture right the first time avoids another round trip. ## Business Verification (KYB) — Registered Entities Only Required only for registered entities. Complete this before Bank Verification. ### Required Details > [accordion] Company Registration Number > > Provide your Company Registration Number and supporting document (Certificate of Incorporation or equivalent for your jurisdiction). > [accordion] Tax ID (Optional) > > If you want your tax number on payout invoices for tax benefits, provide a valid Tax ID and documents. Examples: EIN, CRN, VAT ID, GSTIN. > [accordion] Directors and Beneficial Owners > > Provide details for all directors and beneficial owners. > > **Beneficial Owner(s):** Any natural person who owns or is entitled to 10% or more of shares, capital, or profits, or who exercises control through other means (including the right to appoint the majority of directors or control management or policy decisions). If there are multiple beneficial owners, provide documents for all. > > **Business Director(s):** Individuals currently serving as directors on the board in accordance with local laws. Provide government-issued IDs for all directors. ## Bank Verification Provide your bank account details and contact information. Bank account details must match the verified identity or registered entity name. For individuals, the account holder's name must match your Identity Verification document. For registered entities, it must match your company's legal name. Dodo Payments cannot process payouts to mismatched or third-party accounts. ## W-8BEN-E for UK Entities UK registered entities must submit the W-8BEN-E form to comply with international tax reporting regulations. This ensures smooth payout processing and accurate tax documentation. > [card] [Download W-8BEN-E Form](https://www.irs.gov/pub/irs-pdf/fw8bene.pdf) > > Official IRS W-8BEN-E form (PDF). Complete digitally before printing and signing. ### What is W-8BEN-E? The W-8BEN-E is an IRS form that foreign businesses file to verify their country of residence for tax purposes and certify they qualify for a lower rate of tax withholding. ### How to Fill Out W-8BEN-E > [accordion] Part I – Identification of Beneficial Owner > > **1. Name of Organization** > > Your entity name. > > **2. Country of Incorporation or Organization** > > The country where your business is registered. For a corporation, the country of incorporation. For other entity types, the country under whose laws you are created, organized, or governed. > > **3. Chapter 3 Status** > > Most commonly "Corporation" or "Partnership". For a Private Limited company, check Corporation. For a Limited Liability Partnership, check Partnership. > > **4. Chapter 4 Status (FATCA Status)** > > For SaaS/Digital Products, select "Active NFFE" (Active Non-Financial Foreign Entity). > > **5. Permanent Residence Address** > > Your business's permanent resident address in the country where you claim tax residence. > > **8-10. Tax Identification Information** > > Provide your FTIN (if issued by your jurisdiction of tax residence) on line 9b for treaty benefits. > [accordion] Part XXV – Active NFFE > > Check box 39 to certify: > > * The entity is a foreign entity that is not a bank or financial institution. > * Less than 50% of gross income for the preceding calendar year is passive income. > * Less than 50% of assets held produce or are held for production of passive income. > [accordion] Part XXX – Certification > > Sign and date the form. The person signing must be authorized to sign for the beneficial owner. ### Sample W-8BEN-E Forms > [accordion] Private Limited Company > > **Example:** ABC Technologies PVT LTD, SaaS / Digital Products, India, TIN: PAN > > **Page 1** > > ![W-8 BEN-E Private Limited Sample Page 1](https://mintcdn.com/dodopayments/rsanoiHs7RZfcFW7/images/tax-forms/W8%20-%20BEN%20-%20PLC%20-%20SAMPLE%20-%201.png?fit=max\&auto=format\&n=rsanoiHs7RZfcFW7\&q=85\&s=3b8f15697fccb105a904679359743e65) > > **Page 2** > > ![W-8 BEN-E Private Limited Sample Page 2](https://mintcdn.com/dodopayments/rsanoiHs7RZfcFW7/images/tax-forms/W8%20-%20BEN%20-%20PLC%20-%20SAMPLE%20-%202.png?fit=max\&auto=format\&n=rsanoiHs7RZfcFW7\&q=85\&s=40e3cbf009f507a405d3aac78e825c82) > > **Page 8** > > ![W-8 BEN-E Private Limited Sample Page 8](https://mintcdn.com/dodopayments/rsanoiHs7RZfcFW7/images/tax-forms/W8%20-%20BEN%20-%20PLC%20-%20SAMPLE%20-%208.png?fit=max\&auto=format\&n=rsanoiHs7RZfcFW7\&q=85\&s=d896f1b5e2558ba0c794665efe917e0d) > [accordion] Limited Liability Partnership (LLP) > > **Example:** ABC Technologies LLP, SaaS / Digital Products, India, TIN: PAN > > **Page 1** > > ![W-8 BEN-E LLP Sample Page 1](https://mintcdn.com/dodopayments/rsanoiHs7RZfcFW7/images/tax-forms/W8%20-%20BEN%20-%20LLP%20SAMPLE%20-%201.png?fit=max\&auto=format\&n=rsanoiHs7RZfcFW7\&q=85\&s=968848a298d455d070102e7600b774d6) > > **Page 2** > > ![W-8 BEN-E LLP Sample Page 2](https://mintcdn.com/dodopayments/rsanoiHs7RZfcFW7/images/tax-forms/W8%20-%20BEN%20-%20LLP%20SAMPLE%20-%202.png?fit=max\&auto=format\&n=rsanoiHs7RZfcFW7\&q=85\&s=366eca5999f016cfad7a9b65f9eda637) > > **Page 8** > > ![W-8 BEN-E LLP Sample Page 8](https://mintcdn.com/dodopayments/TzY2I0gw6ehpGkt7/images/tax-forms/W8%20-%20BEN%20-%20LLP%20SAMPLE%20-%208.png?fit=max\&auto=format\&n=TzY2I0gw6ehpGkt7\&q=85\&s=27db0426ff27671ce9c40934dd904f9c) ## Compliance Review After your payout details are approved, our compliance team performs a Monitoring Review per the [Review & Monitoring Policy](/miscellaneous/review-monitoring-policy). This is a standard check for all merchants. We check for: * Compliance with the [Merchant Acceptance Policy](/miscellaneous/merchant-acceptance) * Card-network rules and AML regulations * Potential fraud indicators or unusual activity patterns If your business operates in line with our policies and platform rules, you have nothing to worry about. Most merchants pass smoothly with no action required. Once review is complete, you'll see your payout schedule, next payout date, payout threshold, and eligible balance in the dashboard. ![Account Activated](https://mintcdn.com/dodopayments/zFByO1tBe-g7dwEU/images/payouts/payout-activation2.png?fit=max\&auto=format\&n=zFByO1tBe-g7dwEU\&q=85\&s=e5772baa2b68296742e3c215652f919b) ### Live Payments vs. Payouts Live payments and payouts turn on separately. It's normal to accept live payments while payouts are still inactive. Live payments require every required form for your account type to be approved. See [Required Forms](#required-forms). Payouts require: * Every required form approved, including Bank Verification * Monitoring Review completed If payouts are inactive, check the **Verification** section in your dashboard. A form in draft, under review, or on hold is the usual reason. Completing it moves your account forward. Payouts being active is not the same as a payout being sent. Once enabled, a payout is initiated only when your eligible balance meets your payout threshold and your next payout date arrives. See [Payouts Process](/features/payouts/payout-structure) for cycles and thresholds. If every form is approved and payouts are still inactive, contact [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email. ### Ongoing Monitoring Dodo Payments performs ongoing monitoring periodically to keep accounts compliant over time. If your business remains compliant, you can continue operating without concern. If we have concerns, necessary action is taken per the [Review & Monitoring Policy](/miscellaneous/review-monitoring-policy). ## Additional Information Requests As part of ongoing monitoring, our compliance team may request additional information. These requests are completed from the dashboard and do not block payments or payouts, but failure to submit them may trigger pauses in processing, further reviews, or account restrictions. See the [Review Monitoring Policy](/miscellaneous/review-monitoring-policy) for details. ## Timeline and Support * Typical verification time: 1–3 business days (excludes weekends and public holidays) * If additional review is needed, you'll be notified via email and dashboard * For help, email [support@dodopayments.com](mailto:support@dodopayments.com) ## Resubmitting Documents If the Verification Team finds issues with your documents, they'll request resubmission. Use the **Resubmit** option in your dashboard. Once you submit a form, you cannot edit or resubmit it yourself. The **Resubmit** option appears only after the Verification Team enables it. ### If a Form Is Placed On Hold On Hold means our compliance team needs more information before finishing review. It's not a rejection — your application stays open. When a form is on hold, we email you and raise an **additional verification form** in the **Verification** section. Complete that form to respond to the hold, not the **Resubmit** option. Your dashboard may show resubmissions are temporarily paused. That refers to your original form, which stays locked. If an additional verification form has been raised, complete that instead. **1. Open the Verification section** Find the form marked **On Hold**. The reason is shown alongside it. **2. Fix the underlying issue first** Resolve what caused the hold before you respond. The most common reason is that the review team couldn't open your website — see [Preparing Your Website](#preparing-your-website) for the checklist. **3. Complete the additional verification form** Fill in the additional verification form and submit it. Answer the specific question raised, not just resubmit your original details unchanged. If your dashboard shows a hold but no additional verification form, email [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email and quote the hold reason. Identity Verification works differently — you can retry it yourself while attempts remain. See [If Identity Verification Fails](#if-identity-verification-fails). ### If a Form Is Marked Failed Failed status is not the same as a resubmission request. Resubmission is not reopened automatically, so there's usually no **Resubmit** option. Identity Verification is the exception — it gives you three attempts. See [If Identity Verification Fails](#if-identity-verification-fails). For a failed form, appeal from the **Verification** section: **1. Read the failure reason** Open the **Verification** section to see why the form failed. **2. Fix the underlying issue first** Address what caused the failure before you appeal. For example, point your product URL at a public landing page rather than a login screen, or ensure your live website matches what you described in the form. **3. File your appeal** Submit the appeal with a detailed explanation. A one-line response is unlikely to change the outcome. You can appeal only once, and the decision is final. Write carefully the first time. Appeals typically take more than 48 working hours to review. If your business cannot be supported for reasons of location or product category, an appeal cannot change that outcome. Review [Countries Eligible for Merchant Acceptance](/miscellaneous/accepted-countries-and-territories) and the [Merchant Acceptance Policy](/miscellaneous/merchant-acceptance) to confirm your eligibility first. ### When Resubmission Is Requested Resubmission is requested for: * **Missing or incomplete information** — identification numbers, business name, or other key data * **Document mismatch** — documents don't match the business or personal information provided * **Unreadable or expired documents** — unclear, illegible, or expired uploads * **Additional clarification needed** — further documentation to clarify identity or business information ### How to Resubmit **1. Check your dashboard** Look for a resubmission request (you'll also receive an email notification). **2. Access the resubmit option** The verification team will enable the **Resubmit** option. **3. Upload correct documents** Navigate to the **Verification** section and upload the correct documents. **4. Submit for review** Click **Submit for Review**. > [card] [Merchant Acceptance Policy](/miscellaneous/merchant-acceptance) > > Review our comprehensive acceptance standards, including supported and prohibited products, and ensure your business is eligible for onboarding. > [card] [Review Monitoring Policy](/miscellaneous/review-monitoring-policy) > > Understand how ongoing compliance is monitored, learn about triggers for document review, and stay proactive with your account status. # Agent Skills Source: https://docs.dodopayments.com/developer-resources/agent-skills Enhance your AI coding assistants with official Dodo Payments skills for payment integrations, webhook handling, and billing flows. ## Overview Agent Skills are reusable capabilities that enhance what AI coding assistants can do when working with Dodo Payments. They provide procedural knowledge and best practices that help agents accomplish specific tasks more effectively—from integrating checkout flows to setting up usage-based billing. > [!NOTE] > > **Think of skills as plugins for your AI assistant.** They teach your agent how to implement Dodo Payments features correctly, following recommended patterns and best practices. Skills work with any AI agent that supports the skills protocol, including: * **Claude Code** — Anthropic's CLI coding assistant * **Codex CLI** — OpenAI's CLI coding agent * **Cursor** — AI-first code editor * **VS Code / GitHub Copilot** — via the Agent Plugin, in the editor or the Copilot CLI * **Gemini CLI** — via the Agent Plugin extension * **Grok Build** and **Meta Muse Code** — via the Agent Plugin * **Google Antigravity** and **JetBrains Junie** — via the Agent Plugin * **Kiro** — loads skills as a Power * **OpenCode** — open source AI coding agent * **Other clients** — any agent supporting the skills protocol ## Available Skill The plugin ships one skill, `dodo-payments`. Its `SKILL.md` is a short index that covers when to use the skill, the standard path (create a checkout session, handle the webhook, grant access), client setup, test mode vs live mode, and safety rules. It links to reference topics that your agent opens only when the task needs them. | Reference topic | What it covers | | - | - | | `checkout` | Hosted checkout, payment links, and overlay checkout | | `mobile-checkout` | In-app checkout for React Native, Flutter, iOS, and Android | | `subscriptions` | Subscription lifecycle, trials, plan changes, proration, and on-demand charges | | `webhooks` | Receiving and verifying webhooks using the Standard Webhooks specification | | `usage-billing` | Meters, event ingestion, aggregation, and per-unit pricing | | `credits` | Credit entitlements, balances, ledger, rollover, overage, and meter-based deduction | | `license-keys` | License key activation, validation, and instance management | | `products` | Products, pricing, add-ons, collections, images, and digital product delivery | | `discounts` | Discount codes, eligibility rules, stacking, and subscription-cycle limits | | `localized-pricing` | Localized pricing, adaptive currency, and purchasing power parity | | `customers` | Customers, the self-service portal, saved payment methods, and wallets | | `refunds-disputes` | Issuing refunds, handling disputes and chargebacks, and reconciling access | | `framework-adapters` | Official `@dodopayments/*` route handlers for Next.js, Express, Hono, Astro, Remix, SvelteKit, Nuxt, Fastify, TanStack, Bun, and Convex | | `better-auth` | The `@dodopayments/better-auth` plugin for customer sync, checkout, and portal access | | `billing-sdk` | BillingSDK React components for pricing tables and billing UI | | `testing-go-live` | Test mode, test payment methods, webhook testing, and the production launch checklist | | `mcp` | How to use the Dodo Payments MCP server: which tool to call, test-mode safety, and sign-in | ## Installation Choose your preferred installation method based on your AI coding assistant. > [tab] Agent Plugin (recommended) > > The [Dodo Agent Plugin](/developer-resources/build-with-ai-coding-agents) installs the `dodo-payments` skill plus the MCP server in one step for Claude Code, Codex CLI, Cursor, VS Code / GitHub Copilot, Gemini CLI, Grok Build, Meta Muse Code, Google Antigravity, JetBrains Junie, Kiro, and OpenCode. Skills load automatically when your agent detects a relevant task. > > See the [AI Coding Agents guide](/developer-resources/build-with-ai-coding-agents) for per-agent install commands. > [tab] Skills CLI > > Install skills using the universal skills CLI that works with any agent that supports skills: > > ```bash theme={null} > # Install the Dodo Payments skill > npx skills add dodopayments/skills > ``` > [tab] Claude Code > > Add the Dodo Payments skills marketplace to Claude Code: > > ```bash theme={null} > /plugin marketplace add dodopayments/skills > ``` > > Then install the skill: > > ```bash theme={null} > /plugin install dodo-payments > ``` > [tab] OpenCode > > OpenCode loads skills from directories you point it at. It does **not** scan installed packages, so an explicit `skills.paths` entry is required. > > Using the Agent Plugin package: > > ```bash theme={null} > npm install --save-dev @dodopayments/opencode-plugin > ``` > > ```json theme={null} > { > "$schema": "https://opencode.ai/config.json", > "plugin": ["@dodopayments/opencode-plugin"], > "skills": { > "paths": ["node_modules/@dodopayments/opencode-plugin/skills"] > } > } > ``` > > Relative paths resolve against the **project directory**, so the package must be present in that project's `node_modules`. An absolute path works too, and avoids the local-install requirement. > > > [!WARNING] > > > > A skills path that does not exist is ignored **silently** — no error, no warning. Confirm the skills actually loaded: > > > > ```bash theme={null} > > opencode run "List every skill available to you by name." > > ``` > > > > You should see `dodo-payments`. ## Using Skills Once installed, your AI assistant loads the `dodo-payments` skill automatically when you ask it to implement a Dodo Payments feature. You don't need to name the skill; describe the task instead, and the agent opens the matching reference topic. | Example prompt | Reference topic your agent opens | | - | - | | Create a checkout session for my SaaS product | `checkout` | | Implement a subscription flow with a free trial and multiple pricing tiers | `subscriptions` | | Set up webhook handlers for payment and subscription events | `webhooks` | | Add usage-based billing to track API calls for my AI product | `usage-billing` | | Set up credit entitlements and metered credit deduction for my AI product | `credits` | | Add a Dodo Payments checkout route handler to my Hono app | `framework-adapters` | | Walk me through testing payments and going live | `testing-go-live` | | Look up my recent test-mode payments with the Dodo MCP server | `mcp` | ## How Skills Work Skills provide your AI assistant with: 1. **Procedural Knowledge** — Step-by-step instructions for implementing features 2. **Code Templates** — Production-ready code patterns and snippets 3. **Best Practices** — Recommended approaches for security, error handling, and UX 4. **Context Awareness** — Understanding of how different Dodo Payments features work together The skill keeps topic detail in a `references/` folder next to `SKILL.md`, and your agent opens those files only when the task needs them. When you ask your AI assistant to implement a feature, it uses the relevant skill to understand the correct implementation approach, generate accurate working code, follow Dodo Payments conventions, and handle edge cases and errors properly. > [!NOTE] > > The skill complements the [MCP Server](/developer-resources/mcp-server). Use MCP for API operations and Skills for enhanced AI assistant capabilities. ## Comparison with Other Tools | Tool | Purpose | Best For | | - | - | - | | **Agent Skills** | Enhance AI assistant knowledge | AI-assisted development with any agent that supports skills | | **MCP Server** | Execute API operations | Direct API access from AI assistants | ## Resources > [card] [Skills Repository](https://github.com/dodopayments/skills) > > Browse the source code and contribute to Dodo Payments skills > [card] [MCP Server](/developer-resources/mcp-server) > > Enable AI assistants to execute Dodo Payments API operations > [card] [Build with AI Coding Agents](/developer-resources/build-with-ai-coding-agents) > > Install the Agent Plugin: the skill plus the MCP server in one step > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Get help and share feedback with the community # Astro Adaptor Source: https://docs.dodopayments.com/developer-resources/astro-adaptor Add Dodo Payments checkout, Customer Portal, and webhook endpoints to an Astro project with the @dodopayments/astro package. The `@dodopayments/astro` package gives your Astro project three endpoint handlers. `Checkout` returns checkout URLs, `CustomerPortal` sends a customer to the Customer Portal, and `Webhooks` verifies webhook events and routes them to your code. > [card] [Checkout Handler](#checkout-route-handler) > > Create checkout URLs with static and checkout session flows. > [card] [Customer Portal](#customer-portal-route-handler) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-route-handler) > > Receive and process Dodo Payments webhook events. ## Installation **1. Install the Package** Run this command in your project root: ```bash theme={null} npm install @dodopayments/astro ``` Version 1.0.0 of the package lists Astro 7.2.8 or later, and `zod` 3.25 or later, as peer dependencies. Astro 7 needs Node.js 22.12.0 or later, and some Astro 7 releases need a later Node.js 22 version. For Astro 4 or 5, install version 0.2.11 with `npm install @dodopayments/astro@0.2.11`. The `Checkout`, `CustomerPortal`, and `Webhooks` handlers are the same in both versions. **2. Set Up Environment Variables** Create a `.env` file in your project root. Create the API key under **Developer → API Keys**. Add your webhook endpoint under **Developer → Webhooks**, and copy its **Signing secret** into `DODO_PAYMENTS_WEBHOOK_KEY`: ```env expandable theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret # test_mode or live_mode DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_RETURN_URL=https://yourdomain.com/checkout/success ``` `DODO_PAYMENTS_RETURN_URL` is where customers land after checkout. If you don't pass an environment, the handlers use `live_mode`. A test mode API key works only with `test_mode`. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## Route Handler Examples > [!NOTE] > > The examples are Astro server endpoints in `src/pages/api/`. Endpoints that call Dodo Payments must render on demand, so add a server adapter to your Astro project. In Astro's default `static` output mode, endpoints render at build time, so each example exports `prerender = false` to render the endpoint on each request instead. > [tab] Checkout Handler > > > [!NOTE] > > > > Use this handler to add Dodo Payments checkout to your app. The `GET` handler serves static checkout. The `POST` handler serves checkout sessions. > > ```typescript Astro Route Handler expandable theme={null} > // src/pages/api/checkout.ts > import { Checkout } from "@dodopayments/astro"; > > export const prerender = false; > > export const GET = Checkout({ > bearerToken: import.meta.env.DODO_PAYMENTS_API_KEY, > returnUrl: import.meta.env.DODO_PAYMENTS_RETURN_URL, > environment: import.meta.env.DODO_PAYMENTS_ENVIRONMENT, > type: "static", // optional, defaults to 'static' > }); > > export const POST = Checkout({ > bearerToken: import.meta.env.DODO_PAYMENTS_API_KEY, > returnUrl: import.meta.env.DODO_PAYMENTS_RETURN_URL, > environment: import.meta.env.DODO_PAYMENTS_ENVIRONMENT, > type: "session", // for checkout sessions > }); > ``` > > ```bash Static Checkout cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/checkout?productId=pdt_fqJhl7pxKWiLhwQR042rh' > ``` > > ```bash Checkout Session cURL Example expandable theme={null} > curl --request POST \ > --url https://example.com/api/checkout \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_QMDuvLkbVzCRWRQjLNcs", > "quantity": 1 > } > ], > "customer": { > "email": "customer@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal Handler > > > [!NOTE] > > > > Use this handler to send customers to the Dodo Payments Customer Portal, where they manage their subscriptions and details. > > ```typescript Astro Route Handler expandable theme={null} > // src/pages/api/customer-portal.ts > import { CustomerPortal } from "@dodopayments/astro"; > > export const prerender = false; > > export const GET = CustomerPortal({ > bearerToken: import.meta.env.DODO_PAYMENTS_API_KEY, > environment: import.meta.env.DODO_PAYMENTS_ENVIRONMENT, > }); > ``` > > ```bash Customer Portal cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/customer-portal?customer_id=cus_9VuW4K7O3GHwasENg31m&send_email=true' > ``` > [tab] Webhook Handler > > > [!NOTE] > > > > Use this handler to receive Dodo Payments webhook events in your Astro app and verify their signatures. > > ```typescript Astro Route Handler expandable theme={null} > // src/pages/api/webhook.ts > import { Webhooks } from "@dodopayments/astro"; > > export const prerender = false; > > export const POST = Webhooks({ > webhookKey: import.meta.env.DODO_PAYMENTS_WEBHOOK_KEY, > onPayload: async (payload) => { > // handle the payload > }, > // ... other event handlers for granular control > }); > ``` ## Checkout Route Handler The checkout handler supports all three ways to take payments with Dodo Payments: * **Static Payment Links:** Shareable URLs that collect payments without code. * **Dynamic Payment Links (deprecated):** Payment links you generate with custom details. They use deprecated endpoints. * **Checkout Sessions:** Hosted checkout with a product cart, customer details, and customization options. This is the recommended flow. `Checkout` takes these options: | Option | Type | Description | | - | - | - | | `bearerToken` | `string` | Your Dodo Payments API key. | | `environment` | `string` | `test_mode` or `live_mode`. Defaults to `live_mode`. | | `returnUrl` | `string` | Optional. The URL that checkout redirects the customer to after payment. A `return_url` in a POST body takes precedence. | | `type` | `string` | The checkout flow: `static`, `dynamic`, or `session`. Defaults to `static`. | The handler serves static checkout for `GET` requests. For `POST` requests, it creates a dynamic payment link when `type` is `dynamic`, and a checkout session otherwise. > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_nZuwz45WAs64n3l07zpQR`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's street address. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's ZIP or postal code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > Payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed to checkout as metadata, for example `metadata_orderId=123`. > > A disable flag takes effect only when the matching field has a value, for example `email` with `disableEmail=true`. The handler adds `returnUrl` from its config to the link as `redirect_url`. > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters, or a product that doesn't exist in your account, also return 400. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL. In test mode, the URL uses `test.checkout.dodopayments.com`: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_fqJhl7pxKWiLhwQR042rh?quantity=1&redirect_url=https%3A%2F%2Fyourdomain.com%2Fcheckout%2Fsuccess" > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send the parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. The handler retrieves the product, then creates a subscription if the product is recurring and a one-time payment otherwise. > * The body needs `billing` (with `street`, `city`, `state`, `country`, and `zipcode`) and `customer`, plus `product_id` or `product_cart`. Subscriptions need `product_id`. > * For every supported body field, see: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic checkout proxies the deprecated `POST /payments` and `POST /subscriptions` endpoints. It keeps working for existing integrations, but new integrations should use checkout sessions. > > ### Response Format > > Dynamic checkout returns a JSON response with the payment link as the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/cbq" > } > ``` > [accordion] Checkout Sessions (POST) > > Checkout sessions create a hosted checkout for one-time purchases and subscriptions, with full control over customization. `product_cart` is the only required field, and it needs at least one product. If the body has no `return_url`, the handler uses `returnUrl` from its config. > > Each `checkout_url` works once and expires after 24 hours, or after 15 minutes when you pass `confirm: true`. A session created with `payment_method_id` returns no `checkout_url`, so the handler responds with 400. > > For more details and every supported field, see the [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session). > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa" > } > ``` ## Customer Portal Route Handler The Customer Portal route handler creates a Customer Portal session for the customer you pass and redirects the browser to it. `CustomerPortal` takes the same `bearerToken` and `environment` options as `Checkout`. > [!WARNING] > > The handler doesn't check who is calling it. Anyone who requests it with a customer ID gets that customer's portal. Protect the route with your own authentication, and pass only the signed-in user's customer ID. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, Dodo Payments also emails the portal link to the customer. The handler returns 400 if `customer_id` is missing, and 500 if the portal session can't be created. ## Webhook Route Handler The webhook route handler verifies each request with your webhook secret, passed as `webhookKey`, before it runs your code: * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`, following the Standard Webhooks specification. Returns 401 if verification fails. * **Payload Validation:** Validates the payload with Zod. Returns 400 for an invalid payload. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Internal error during verification * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200. The adaptor doesn't catch errors thrown in your handlers. They propagate to Astro, and the request fails. ### Supported Webhook Event Handlers Every handler is optional and async, and receives the verified payload for its event type: ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` For what each event means, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). ## Prompt for LLM Copy this prompt into your AI coding assistant to have it add the adaptor to your project. To give your agent the Dodo Payments docs and skills as well, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ```text expandable theme={null} You are an expert Astro developer assistant. Your task is to guide a user through integrating the @dodopayments/astro adapter into their existing Astro project. The @dodopayments/astro adapter provides route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed for Astro server endpoints in src/pages/api/. First, install the necessary packages. Use the package manager appropriate for your project (npm, yarn, or bun) based on the presence of lock files (e.g., package-lock.json for npm, yarn.lock for yarn, bun.lockb for bun): npm install @dodopayments/astro The endpoints must render on demand. Make sure the project has an Astro server adapter, and export prerender = false from each endpoint file unless the project uses output: 'server'. Here's how you should structure your response: Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/astro adapter would you like to integrate into your project? You can choose one or more of the following: Checkout Route Handler (for handling product checkouts) Customer Portal Route Handler (for managing customer subscriptions/details) Webhook Route Handler (for receiving Dodo Payments webhook events) All (integrate all three)" Based on the user's selection, provide detailed integration steps for each chosen functionality. If Checkout Route Handler is selected: Purpose: This handler manages static checkout and checkout sessions. Both return JSON responses with checkout URLs for programmatic handling. File Creation: Create a new file at src/pages/api/checkout.ts in your Astro project. Code Snippet: // src/pages/api/checkout.ts import { Checkout } from "@dodopayments/astro"; export const prerender = false; export const GET = Checkout({ bearerToken: import.meta.env.DODO_PAYMENTS_API_KEY, returnUrl: import.meta.env.DODO_PAYMENTS_RETURN_URL, environment: import.meta.env.DODO_PAYMENTS_ENVIRONMENT, type: "static", // optional, defaults to 'static' }); export const POST = Checkout({ bearerToken: import.meta.env.DODO_PAYMENTS_API_KEY, returnUrl: import.meta.env.DODO_PAYMENTS_RETURN_URL, environment: import.meta.env.DODO_PAYMENTS_ENVIRONMENT, type: "session", // for checkout sessions }); Configuration & Usage: bearerToken: Your Dodo Payments API key. It's recommended to set this via the DODO_PAYMENTS_API_KEY environment variable. returnUrl: (Optional) The URL to redirect the user to after a successful checkout. A return_url in the POST body takes precedence. environment: (Optional) Set to "test_mode" for testing, or omit/set to "live_mode" for production. type: (Optional) Set to "static" for GET/static checkout or "session" for POST/checkout sessions. Static Checkout (GET) Query Parameters: productId (required): Product identifier (e.g., ?productId=pdt_nZuwz45WAs64n3l07zpQR) quantity (optional): Quantity of the product Customer Fields (optional): fullName, firstName, lastName, email, country, addressLine, city, state, zipCode Disable Flags (optional, set to true to disable): disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode Advanced Controls (optional): paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts Metadata (optional): Any query parameter starting with metadata_ (e.g., ?metadata_userId=abc123) Returns: {"checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_nZuwz45WAs64n3l07zpQR?quantity=1"} Checkout Sessions (POST) - (Recommended) A more customizable checkout experience. Returns JSON with checkout_url: Parameters are sent as a JSON body, and product_cart is required. Supports both one-time and recurring payments. Returns: {"checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa"}. For a complete list of supported fields, refer to: Checkout Sessions Integration Guide: https://docs.dodopayments.com/developer-resources/checkout-session Error Handling: If productId is missing or other query parameters are invalid, the handler will return a 400 response. If Customer Portal Route Handler is selected: Purpose: This handler redirects a customer to their Dodo Payments customer portal. It does not authenticate the caller, so protect the route and pass only the signed-in user's customer ID. File Creation: Create a new file at src/pages/api/customer-portal.ts in your Astro project. Code Snippet: // src/pages/api/customer-portal.ts import { CustomerPortal } from "@dodopayments/astro"; export const prerender = false; export const GET = CustomerPortal({ bearerToken: import.meta.env.DODO_PAYMENTS_API_KEY, environment: import.meta.env.DODO_PAYMENTS_ENVIRONMENT, }); Query Parameters: customer_id (required): The customer ID for the portal session (e.g., ?customer_id=cus_123) send_email (optional, boolean): If set to true, sends an email to the customer with the portal link. Returns 400 if customer_id is missing. If Webhook Route Handler is selected: Purpose: This handler processes incoming webhook events from Dodo Payments, allowing your application to react to events like successful payments, refunds, or subscription changes. File Creation: Create a new file at src/pages/api/webhook.ts in your Astro project. Code Snippet: // src/pages/api/webhook.ts import { Webhooks } from "@dodopayments/astro"; export const prerender = false; export const POST = Webhooks({ webhookKey: import.meta.env.DODO_PAYMENTS_WEBHOOK_KEY, onPayload: async (payload) => { // handle the payload }, // ... other event handlers for granular control }); Handler Details: Method: Only POST requests are supported. Other methods return 405. Signature Verification: The handler verifies the webhook signature using the webhookKey and returns 401 if verification fails. Payload Validation: The payload is validated with Zod. Returns 400 for invalid payloads. Error Handling: 401: Invalid signature 400: Invalid payload 500: Internal error during verification Event Routing: Calls onPayload for every event, then the event handler that matches the payload type. Supported Webhook Event Handlers: onPayload?: (payload: WebhookPayload) => Promise onPaymentSucceeded?: (payload: WebhookPayload) => Promise onPaymentFailed?: (payload: WebhookPayload) => Promise onPaymentProcessing?: (payload: WebhookPayload) => Promise onPaymentCancelled?: (payload: WebhookPayload) => Promise onRefundSucceeded?: (payload: WebhookPayload) => Promise onRefundFailed?: (payload: WebhookPayload) => Promise onDisputeOpened?: (payload: WebhookPayload) => Promise onDisputeExpired?: (payload: WebhookPayload) => Promise onDisputeAccepted?: (payload: WebhookPayload) => Promise onDisputeCancelled?: (payload: WebhookPayload) => Promise onDisputeChallenged?: (payload: WebhookPayload) => Promise onDisputeWon?: (payload: WebhookPayload) => Promise onDisputeLost?: (payload: WebhookPayload) => Promise onSubscriptionActive?: (payload: WebhookPayload) => Promise onSubscriptionOnHold?: (payload: WebhookPayload) => Promise onSubscriptionRenewed?: (payload: WebhookPayload) => Promise onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise onSubscriptionCancelled?: (payload: WebhookPayload) => Promise onSubscriptionFailed?: (payload: WebhookPayload) => Promise onSubscriptionExpired?: (payload: WebhookPayload) => Promise onSubscriptionUpdated?: (payload: WebhookPayload) => Promise onSubscriptionPaused?: (payload: WebhookPayload) => Promise onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise onLicenseKeyCreated?: (payload: WebhookPayload) => Promise onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise onDunningStarted?: (payload: WebhookPayload) => Promise onDunningRecovered?: (payload: WebhookPayload) => Promise onCreditAdded?: (payload: WebhookPayload) => Promise onCreditDeducted?: (payload: WebhookPayload) => Promise onCreditExpired?: (payload: WebhookPayload) => Promise onCreditRolledOver?: (payload: WebhookPayload) => Promise onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise onCreditOverageCharged?: (payload: WebhookPayload) => Promise onCreditOverageReset?: (payload: WebhookPayload) => Promise onCreditManualAdjustment?: (payload: WebhookPayload) => Promise onCreditBalanceLow?: (payload: WebhookPayload) => Promise onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise onPayoutCreated?: (payload: WebhookPayload) => Promise onPayoutOnHold?: (payload: WebhookPayload) => Promise onPayoutInProgress?: (payload: WebhookPayload) => Promise onPayoutFailed?: (payload: WebhookPayload) => Promise onPayoutSuccess?: (payload: WebhookPayload) => Promise Environment Variable Setup: To ensure the adapter functions correctly, you will need to manually set up the following environment variables in your Astro project's deployment environment (e.g., Vercel, Netlify, AWS, etc.): DODO_PAYMENTS_API_KEY: Your Dodo Payments API Key (required for Checkout and Customer Portal). DODO_PAYMENTS_RETURN_URL: (Optional) The URL to redirect to after a successful checkout (for Checkout handler). DODO_PAYMENTS_WEBHOOK_KEY: Your Dodo Payments Webhook Secret (required for Webhook handler). DODO_PAYMENTS_ENVIRONMENT: test_mode or live_mode. The handlers default to live_mode. Example .env file: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_RETURN_URL=your-return-url Usage in your code: bearerToken: import.meta.env.DODO_PAYMENTS_API_KEY webhookKey: import.meta.env.DODO_PAYMENTS_WEBHOOK_KEY Important: Never commit sensitive environment variables directly into your version control. Use environment variables for all sensitive information. If the user needs assistance setting up environment variables for their specific deployment environment, ask them what platform they are using (e.g., Vercel, Netlify, AWS, etc.), and provide guidance. You can also add comments to their PR or chat depending on the context ``` # Astro Minimal Boilerplate Source: https://docs.dodopayments.com/developer-resources/astro-boilerplate Clone the Astro minimal boilerplate to get a pricing page, checkout sessions, a webhook handler, and a Customer Portal link wired to Dodo Payments. ## Overview The Astro minimal boilerplate is a starter app with Dodo Payments already connected. Add your API keys and product IDs, and you get a pricing page that opens checkout, a webhook endpoint for payment events, and a link to the Customer Portal. > [!NOTE] > > This boilerplate uses Astro 5 with TypeScript, Tailwind CSS 4, and the `@dodopayments/astro` adaptor. To add the same API routes to an existing app, see the [Astro Adaptor](/developer-resources/astro-adaptor). ### Features The boilerplate includes: * **Quick Setup**: Go from clone to a running pricing page in about five minutes. * **Checkout**: A pre-configured checkout flow built on `@dodopayments/astro`. * **Pricing Page**: A dark-themed pricing page styled with Tailwind CSS. * **Webhook Handler**: An endpoint that verifies each webhook signature and runs your code for the event. * **Customer Portal**: A header link that opens the Customer Portal, where customers manage their subscriptions. * **TypeScript**: Typed product definitions and handlers. * **Pre-filled Checkout**: Passes the customer's name and email to checkout, so the customer doesn't retype them. ## Prerequisites Before you begin, you need: * **A Node.js LTS version**, which Astro 5 requires. * **A Dodo Payments account**, to create an API key and a webhook signing secret in the dashboard. ## Quick Start **1. Clone the Repository** ```bash theme={null} git clone https://github.com/dodopayments/dodo-astro-minimal-boilerplate.git cd dodo-astro-minimal-boilerplate ``` **2. Install Dependencies** ```bash theme={null} npm install ``` **3. Get API Credentials** Sign up at [Dodo Payments](https://dodopayments.com/), then get your credentials from the dashboard: * **API Key:** Create a key under [Dashboard → Developer → API Keys](https://app.dodopayments.com/developer/api-keys). * **Webhook Key:** Add an endpoint under [Dashboard → Developer → Webhooks](https://app.dodopayments.com/developer/webhooks), then copy its signing secret. The endpoint URL must be public and use HTTPS. To receive events on your machine, see [Webhook Events](#webhook-events). > [!TIP] > > Create both while the **Live Mode** switch in the sidebar is off. A test mode key works only with `DODO_PAYMENTS_ENVIRONMENT=test_mode`, and test mode payments don't move real money. **4. Configure Environment Variables** Copy the example file to create a `.env` file in the root directory: ```bash theme={null} cp .env.example .env ``` Set the values to your Dodo Payments credentials: ```env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_signing_key_here DODO_PAYMENTS_RETURN_URL=http://localhost:4321/ DODO_PAYMENTS_ENVIRONMENT=test_mode ``` `.env.example` sets `DODO_PAYMENTS_RETURN_URL` to port `3000`. Change it to `4321`, the port the Astro dev server uses, so that checkout returns the customer to your app. The API routes read these variables: * `DODO_PAYMENTS_API_KEY` authenticates the checkout and Customer Portal routes. * `DODO_PAYMENTS_WEBHOOK_KEY` verifies webhook signatures. * `DODO_PAYMENTS_RETURN_URL` is where checkout sends the customer after payment. * `DODO_PAYMENTS_ENVIRONMENT` is `test_mode` or `live_mode`. > [!WARNING] > > Don't commit your `.env` file to version control. The repository's `.gitignore` already excludes it. **5. Add Your Products** Replace the sample products in `src/lib/products.ts` with your own. Set each `product_id` to the ID of a product under **Products** in your dashboard: ```typescript theme={null} export const products: Product[] = [ { product_id: "pdt_001", // Replace with your product ID name: "Basic Plan", description: "Get access to basic features and support", price: 9999, // in cents features: [ "Access to basic features", "Email support", "1 Team member", "Basic analytics", ], }, // ... add more products ]; ``` The pricing page displays `name`, `description`, `price`, and `features` from this file. Checkout charges the price set on the product in Dodo Payments, so keep `price` in sync with it. **6. Run the Development Server** ```bash theme={null} npm run dev ``` Open [http://localhost:4321](http://localhost:4321) to see your pricing page. ## Project Structure The checkout, Customer Portal, and webhook API routes live under `src/pages/api/`: ```text theme={null} src/ ├── components/ │ ├── Footer.astro # Reusable footer │ ├── Header.astro # Navigation header │ └── ProductCard.astro # Product pricing card ├── layouts/ │ └── Layout.astro # Root layout ├── lib/ │ └── products.ts # Product definitions ├── pages/ │ ├── index.astro # Pricing page (home) │ └── api/ │ ├── checkout.ts # Checkout session handler │ ├── customer-portal.ts # Customer portal redirect │ └── webhook.ts # Webhook event handler └── styles/ └── global.css # Global styles with Tailwind ``` ## Customization ### Update Product Information Edit `src/lib/products.ts` to change: * Product IDs, from **Products** in your Dodo Payments dashboard * Prices * Features * Descriptions ### Pre-fill Customer Data The checkout script in `src/components/ProductCard.astro` sends a hardcoded name and email with each checkout request. Replace them with the signed-in user's details: ```typescript theme={null} customer: { name: "John Doe", email: "john@example.com", }, ``` ### Update Customer Portal The **Customer Portal** link in `src/components/Header.astro` opens `/api/customer-portal` with a hardcoded customer ID. Replace it with the customer ID from your authentication system or database: ```typescript theme={null} const CUSTOMER_ID = "cus_001"; // Replace with actual customer ID ``` To get a customer ID for testing, complete a test purchase, then copy the customer's ID from **Customers** in the dashboard. ## Webhook Events The handler in `src/pages/api/webhook.ts` verifies each request with `DODO_PAYMENTS_WEBHOOK_KEY`, then handles two events: * `onSubscriptionActive` runs when a subscription becomes active (`subscription.active`). * `onSubscriptionCancelled` runs when a subscription is cancelled (`subscription.cancelled`). Add your business logic inside these handlers: ```typescript theme={null} onSubscriptionActive: async (payload) => { // Grant access to your product // Update user database // Send welcome email }, ``` To handle more events, add their handlers, such as `onPaymentSucceeded`. The [Astro Adaptor](/developer-resources/astro-adaptor#supported-webhook-event-handlers) lists every supported handler. Dodo Payments can't reach `localhost`. For local development, use a tunnel such as [ngrok](https://ngrok.com/) to expose your local server, and use the tunnel URL as your webhook endpoint. ## Deployment Astro builds the pages as static output, and each API route sets `export const prerender = false` so that it renders on demand. On-demand routes need an Astro adapter for your deployment platform: | Platform | Guide | | - | - | | Vercel | [Deploy to Vercel](https://docs.astro.build/en/guides/deploy/vercel/) | | Netlify | [Deploy to Netlify](https://docs.astro.build/en/guides/deploy/netlify/) | | Cloudflare | [Deploy to Cloudflare](https://docs.astro.build/en/guides/deploy/cloudflare/) | For other platforms, see [Astro's deployment guides](https://docs.astro.build/en/guides/deploy/). In your hosting platform, add the four environment variables and set `DODO_PAYMENTS_RETURN_URL` to your production URL. ### Update Webhook URL After deploying, add your production webhook URL in the [Dodo Payments Dashboard](https://app.dodopayments.com/developer/webhooks): ```text theme={null} https://your-domain.com/api/webhook ``` Each endpoint has its own signing secret. Set `DODO_PAYMENTS_WEBHOOK_KEY` in your production environment to the signing secret of this endpoint. ## Troubleshooting > [accordion] Module not found or build errors > > Delete `node_modules` and `package-lock.json`, then reinstall dependencies: > > ```bash theme={null} > rm -rf node_modules package-lock.json > npm install > ``` > [accordion] Checkout redirect fails > > Check for these common causes: > > * The product ID doesn't exist in your Dodo Payments dashboard. > * The API key or `DODO_PAYMENTS_ENVIRONMENT` in `.env` is wrong. A test mode key works only with `test_mode`. > > Look for the error in the browser console and in the terminal that runs `npm run dev`. > [accordion] Webhooks not receiving events > > For local testing, use [ngrok](https://ngrok.com) to expose your server: > > ```bash theme={null} > ngrok http 4321 > ``` > > In your [Dodo dashboard](https://app.dodopayments.com/developer/webhooks), add an endpoint with the ngrok HTTPS URL followed by `/api/webhook`. Copy that endpoint's signing secret into `DODO_PAYMENTS_WEBHOOK_KEY` in your `.env` file. > [accordion] Customer portal link doesn't work > > Replace the hardcoded `CUSTOMER_ID` in `src/components/Header.astro` with the ID of a customer in your Dodo Payments dashboard. > > In production, get the customer ID from your authentication system and database instead. > [accordion] Build fails with adapter error > > The API routes render on demand, and the repository doesn't include a deployment adapter. Install the Astro adapter for your platform before you build for production. > > See [Astro's deployment guides](https://docs.astro.build/en/guides/deploy/) for details. ## Learn More * [Dodo Payments Documentation](https://docs.dodopayments.com/) * [Checkout Sessions Documentation](https://docs.dodopayments.com/developer-resources/checkout-session) * [Webhooks Documentation](https://docs.dodopayments.com/developer-resources/webhooks) * [Astro Adaptor](/developer-resources/astro-adaptor): options for the `Checkout`, `CustomerPortal`, and `Webhooks` handlers * [Astro Documentation](https://docs.astro.build/) ## Support For help with the boilerplate: * Ask questions in the [Discord community](https://discord.gg/bYqAp4ayYh). * Report issues and follow updates in the [GitHub repository](https://github.com/dodopayments/dodo-astro-minimal-boilerplate). * Email the [support team](mailto:support@dodopayments.com). # Better Auth Adaptor Source: https://docs.dodopayments.com/developer-resources/better-auth-adaptor Add Dodo Payments to Better Auth: create customers at sign-up, open checkout sessions and the Customer Portal, record usage, and handle webhooks. # Overview The Better Auth adaptor, `@dodopayments/better-auth`, is a Better Auth plugin that connects your users to Dodo Payments. It provides: * Optional customer creation or email-based customer linking on sign-up * Checkout sessions, the preferred checkout method, with product slug mapping * A self-service Customer Portal * Usage ingestion and reporting endpoints for usage-based billing * Webhook event processing with signature verification * TypeScript types for every endpoint > [!NOTE] > > You need a Dodo Payments account and API keys to use this integration. # Prerequisites * Node.js 16 or later * Access to your Dodo Payments dashboard * An existing project that uses [Better Auth](https://www.npmjs.com/package/better-auth) 1.4 or a later 1.x release # Installation **1. Install Dependencies** Run this command in your project root: ```bash theme={null} npm install @dodopayments/better-auth dodopayments better-auth zod ``` > [!TIP] > > The adaptor, the Dodo Payments SDK, Better Auth, and Zod are installed. # Setup **1. Configure Environment Variables** Add these variables to your `.env` file. Create the API key under **Developer → API Keys** in the dashboard. You get the webhook secret when you add the webhook endpoint, as described under Webhooks on this page. `BETTER_AUTH_SECRET` is a random string of at least 32 characters. ```env expandable theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_secret_here BETTER_AUTH_URL=http://localhost:3000 BETTER_AUTH_SECRET=your_better_auth_secret_here ``` > [!WARNING] > > Never commit API keys or secrets to version control. **2. Set Up Server-Side Integration** Create or update `src/lib/auth.ts`: ```typescript expandable theme={null} import { betterAuth } from "better-auth"; import { dodopayments, checkout, portal, webhooks, usage, } from "@dodopayments/better-auth"; import DodoPayments from "dodopayments"; export const dodoPayments = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY!, environment: "test_mode", // or "live_mode" for production }); export const auth = betterAuth({ plugins: [ dodopayments({ client: dodoPayments, createCustomerOnSignUp: true, use: [ checkout({ products: [ { productId: "pdt_xxxxxxxxxxxxxxxxxxxxx", slug: "premium-plan", }, ], successUrl: "/dashboard/success", authenticatedUsersOnly: true, }), portal(), webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, onPayload: async (payload) => { console.log("Received webhook:", payload.type); }, }), usage(), ], }), ], }); ``` The plugin adds a `dodoCustomerId` field to the Better Auth `user` table, where it stores each user's Dodo Payments customer ID. After you add the plugin, update your database schema with the [Better Auth CLI](https://www.better-auth.com/docs/concepts/cli). > [!TIP] > > Set `environment` to `live_mode` for production. **3. Set Up Client-Side Integration** Create or update `src/lib/auth-client.ts`: ```typescript expandable theme={null} import { createAuthClient } from "better-auth/react"; import { dodopaymentsClient } from "@dodopayments/better-auth/client"; export const authClient = createAuthClient({ baseURL: process.env.BETTER_AUTH_URL || "http://localhost:3000", plugins: [dodopaymentsClient()], }); ``` # Usage Examples > [!NOTE] > > Use `authClient.dodopayments.checkoutSession` for new integrations. The > legacy `checkout` method is deprecated and kept only for backward > compatibility. ## Creating a Checkout Session (Preferred) Create a checkout session from a configured slug or from a product cart, then redirect the customer to the returned URL: ```typescript Using a slug theme={null} const { data: session, error } = await authClient.dodopayments.checkoutSession({ // Option A: use a configured slug slug: "premium-plan", // Your internal ID, stored in the payment metadata as referenceId referenceId: "order_123", }); if (session) { window.location.href = session.url; } ``` ```typescript Using product cart theme={null} const { data: session, error } = await authClient.dodopayments.checkoutSession({ // Option B: pass a product cart directly product_cart: [ { product_id: "pdt_xxxxxxxxxxxxxxxxxxxxx", quantity: 1, } ], // Your internal ID, stored in the payment metadata as referenceId referenceId: "order_123", }); if (session) { window.location.href = session.url; } ``` `checkoutSession` fills in some fields for you: * **Billing address:** Not required up front, because checkout collects it from the customer. To pre-fill it, pass `billing_address`. * **Customer:** For a signed-in user, the plugin uses the email and name from their Better Auth session and ignores any `customer` object you pass. Without a signed-in user, it uses the `customer` object. * **Other fields:** The argument accepts the same fields as the request body of the [Create Checkout Session](https://docs.dodopayments.com/api-reference/checkout-sessions/create) endpoint, plus `slug` and `referenceId`. If the slug isn't configured, or you pass neither `slug` nor `product_cart`, the request fails with a 400 error. > [!NOTE] > > The return URL comes from the `successUrl` configured in the server plugin, > resolved against your app's URL. The plugin ignores any `return_url` in the > client payload. ## Legacy Checkout (Deprecated) > [!WARNING] > > The `authClient.dodopayments.checkout` method is deprecated. Use > `checkoutSession` instead for new implementations. The legacy method requires `billing` and `customer`, and creates a payment link through the deprecated dynamic checkout flow. To migrate, replace the call with [`checkoutSession`](#creating-a-checkout-session-preferred), keep `slug` and `referenceId`, and remove `billing`, because checkout collects the address from the customer. To pre-fill the address, pass it as `billing_address`. ## Accessing the Customer Portal The portal endpoints require a signed-in user with a verified email address. If the user has no Dodo Payments customer yet, the plugin finds one by email or creates one. `customer.portal()` returns the portal URL: ```typescript expandable theme={null} const { data: customerPortal, error } = await authClient.dodopayments.customer.portal(); if (customerPortal && customerPortal.redirect) { window.location.href = customerPortal.url; } ``` ## Listing Customer Data List the signed-in customer's subscriptions and payments. `page` starts at 1, and `status` filters the results: ```typescript expandable theme={null} // Get subscriptions const { data: subscriptions, error: subscriptionsError } = await authClient.dodopayments.customer.subscriptions.list({ query: { limit: 10, page: 1, status: "active", }, }); // Get payment history const { data: payments, error: paymentsError } = await authClient.dodopayments.customer.payments.list({ query: { limit: 10, page: 1, status: "succeeded", }, }); ``` ## Tracking Metered Usage Enable the `usage()` plugin on the server to record usage events for usage-based billing and let customers see their usage. Both methods require a signed-in user with a verified email address. * `authClient.dodopayments.usage.ingest` records an event for the signed-in user. * `authClient.dodopayments.usage.meters.list` lists the signed-in customer's usage events. It accepts `page_number`, `page_size`, `event_name`, `meter_id`, `start`, and `end` query parameters. ```typescript expandable theme={null} // Record a metered event (e.g., an API request) const { error: ingestError } = await authClient.dodopayments.usage.ingest({ event_id: crypto.randomUUID(), event_name: "api_request", metadata: { route: "/reports", method: "GET", }, // Optional Date; defaults to now if omitted timestamp: new Date(), }); if (ingestError) { console.error("Failed to record usage", ingestError); } // List recent usage for the current customer const { data: usage, error: usageError } = await authClient.dodopayments.usage.meters.list({ query: { page_size: 20, meter_id: "mtr_yourMeterId", // optional }, }); if (usage?.items) { usage.items.forEach((event) => { console.log(event.event_name, event.timestamp, event.metadata); }); } ``` > [!TIP] > > Dodo Payments rejects events with timestamps more than one hour in the past > or more than five minutes in the future. If you omit `meter_id`, the list includes all of the customer's usage events. With `meter_id`, it includes only the events that match that meter. # Webhooks > [!NOTE] > > The webhooks plugin verifies the signature of each Dodo Payments event and > calls your handlers. The default endpoint is > `/api/auth/dodopayments/webhooks`. **1. Generate and Set Webhook Secret** In the dashboard, go to **Developer → Webhooks** and add your endpoint URL, for example `https:///api/auth/dodopayments/webhooks`. Copy the endpoint's signing secret into your `.env` file: ```env theme={null} DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_secret_here ``` **2. Handle Webhook Events** Pass a handler for each event you want to process. `onPayload` runs for every event: ```typescript expandable theme={null} webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, onPayload: async (payload) => { console.log("Received webhook:", payload.type); }, }); ``` If signature verification fails or a handler throws an error, the endpoint responds with 400. After your handlers finish, it returns `{ received: true }`. ### Supported Webhook Event Handlers Each handler receives the verified payload for its event type: ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` # Configuration Reference > [accordion] Plugin Options > > * **client** (required): DodoPayments client instance > * **createCustomerOnSignUp** (optional): Create a Dodo Payments customer when a user signs up, or link an existing customer with the same email. The plugin also updates the customer when the user's details change. > * **use** (required): Array of plugins to enable (checkout, portal, usage, webhooks) > * **getCustomerParams** (optional): Function that receives the Better Auth `User` and returns extra fields to attach to the Dodo Payments customer on creation and update (e.g. `metadata`, `phone_number`). It can be async. > > ```typescript theme={null} > dodopayments({ > client: dodoPayments, > createCustomerOnSignUp: true, > use: [portal()], > getCustomerParams: (user) => ({ > metadata: { userId: user.id }, > phone_number: user.phoneNumber ?? null, > }), > }) > ``` > [accordion] Checkout Plugin Options > > * **products**: Array of `{ productId, slug }` objects, or an async function that returns one > * **successUrl**: URL to redirect to after successful payment > * **authenticatedUsersOnly**: Require user authentication (default: `false`) # Troubleshooting & Tips > [accordion] Common Issues > > * **Invalid API key**: Check `DODO_PAYMENTS_API_KEY` in `.env`, and check that the key's mode matches `environment`. > * **Webhook signature mismatch**: Check that the webhook secret matches the one set in the Dodo Payments dashboard. > * **Customer not created**: Check that `createCustomerOnSignUp` is set to `true`. > * **Portal or usage requests return 401**: The user's email address isn't verified. > [accordion] Best Practices > > * Use environment variables for all secrets and keys. > * Test in `test_mode` before you switch to `live_mode`. > * Log webhook events for debugging and auditing. # Prompt for LLMs Copy this prompt into your AI coding assistant to have it add the adaptor to your project. To give your agent the Dodo Payments docs and skills as well, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ```text expandable theme={null} You are a skilled developer helping to integrate the @dodopayments/better-auth adapter into a typescript web application with better-auth. This adapter enables seamless payment processing through Dodo Payments with automatic customer management, checkout flows, and webhook handling. STAGE 1: BASIC SETUP This stage covers the foundational setup needed before implementing any plugins. Complete this stage first. STEP 1: Installation Install the required dependencies: npm install @dodopayments/better-auth dodopayments better-auth zod STEP 2: Environment Variables Setup You will need to complete these external setup tasks. I will provide you with a TODO list for the actions you need to take outside of the code: TODO LIST FOR USER: 1. Generate Dodo Payments API Key: - Go to your Dodo Payments Dashboard > Developer > API Keys - Create a new API key (or use existing) - Copy the API key value - Set environment variable: DODO_PAYMENTS_API_KEY=dodo_test_... 2. Generate Better Auth Secret: - Generate a random secret key (32+ characters) - Set environment variable: BETTER_AUTH_SECRET=your_better_auth_secret_here 3. Set Application URL: - For development: BETTER_AUTH_URL=http://localhost:3000 - For production: BETTER_AUTH_URL=https://your-domain.com 4. Webhook Secret (only if implementing webhooks plugin): - This will be provided after you specify your domain name in Stage 2 - Set environment variable: DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_secret_here Add these environment variables to your .env file: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_secret_here BETTER_AUTH_URL=http://localhost:3000 BETTER_AUTH_SECRET=your_better_auth_secret_here STEP 3: Server Configuration Create or update your better-auth setup file (src/lib/auth.ts): import { betterAuth } from "better-auth"; import { dodopayments } from "@dodopayments/better-auth"; import DodoPayments from "dodopayments"; // Create DodoPayments client export const dodoPayments = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY!, environment: "test_mode", // Change to "live_mode" for production }); // Configure better-auth with dodopayments adapter export const auth = betterAuth({ plugins: [ dodopayments({ client: dodoPayments, createCustomerOnSignUp: true, // Auto-create customers on signup use: [], // We'll add plugins here in Stage 2 // Optional: attach metadata or phone_number to DodoPayments customer records // getCustomerParams: (user) => ({ // metadata: { userId: user.id }, // phone_number: user.phoneNumber ?? null, // }), }), ], }); The plugin adds a dodoCustomerId field to the Better Auth user table. Update the database schema with the Better Auth CLI after adding the plugin. STEP 4: Client Configuration Create or update your auth client file (src/lib/auth-client.ts): import { createAuthClient } from "better-auth/react"; import { dodopaymentsClient } from "@dodopayments/better-auth/client"; export const authClient = createAuthClient({ baseURL: process.env.BETTER_AUTH_URL || "http://localhost:3000", plugins: [dodopaymentsClient()], }); STAGE 2: PLUGIN IMPLEMENTATION After completing Stage 1, you can selectively implement any of these plugins based on your needs. Each plugin is independent and can be added or removed as needed. PLUGIN SELECTION: Before implementing any plugins, ask the user which plugins they want to implement: "Which plugins would you like to implement? You can choose any combination of: 1. CHECKOUT - Enables secure payment processing and checkout flows 2. PORTAL - Provides customer self-service portal for subscriptions and payments 3. USAGE - Tracks metered events and exposes usage history for billing beyond included allowances 4. WEBHOOKS - Handles real-time payment events from Dodo Payments Please specify which plugins you want (e.g., 'checkout and usage', 'all four', 'just portal', etc.)" If the user doesn't respond or you cannot prompt the user, implement all four plugins by default. Based on the user's selection, implement only the requested plugins from the sections below: CHECKOUT PLUGIN Purpose: Enables secure payment processing using Checkout Sessions (preferred) with product slug mapping. A legacy checkout endpoint is also exposed for backward compatibility but is deprecated. SETUP TODO LIST FOR USER: 1. Create products in Dodo Payments Dashboard: - Go to Dodo Payments Dashboard > Products - Create your products (e.g., subscription plans, one-time purchases) - Copy each product ID (starts with "pdt_") - Note down the product names for creating friendly slugs 2. Plan your checkout URLs: - Decide on your success URL (e.g., "/dashboard/success", "/thank-you") - Ensure this URL exists in your application Configuration: Add checkout to your imports in src/lib/auth.ts: import { dodopayments, checkout } from "@dodopayments/better-auth"; Add checkout plugin to the use array in your dodopayments configuration: use: [ checkout({ products: [ { productId: "pdt_xxxxxxxxxxxxxxxxxxxxx", // Your actual product ID from Dodo Payments slug: "premium-plan", // Friendly slug for checkout }, // Add more products as needed ], successUrl: "/dashboard/success", // Your success page URL authenticatedUsersOnly: true, // Require login for checkout }), ], Usage Example (Preferred - Checkout Sessions): const { data: session, error } = await authClient.dodopayments.checkoutSession({ // Use the slug from your configuration OR provide product_cart directly slug: "premium-plan", // product_cart: [{ product_id: "pdt_xxxxxxxxxxxxxxxxxxxxx", quantity: 1 }], referenceId: "order_123", // Optional reference }); if (session) { window.location.href = session.url; } Deprecated (Legacy Checkout): const { data: checkout, error } = await authClient.dodopayments.checkout({ slug: "premium-plan", customer: { email: "customer@example.com", name: "John Doe", }, billing: { city: "San Francisco", country: "US", state: "CA", street: "123 Market St", zipcode: "94103", }, }); if (checkout) { window.location.href = checkout.url; } Options: - products: Array of products or async function returning products - successUrl: URL to redirect after successful payment - authenticatedUsersOnly: Require user authentication (default: false) PORTAL PLUGIN Purpose: Provides customer self-service capabilities for managing subscriptions and viewing payment history. Configuration: Add portal to your imports in src/lib/auth.ts: import { dodopayments, portal } from "@dodopayments/better-auth"; Add portal plugin to the use array in your dodopayments configuration: use: [ portal(), ], Usage Examples: // Access customer portal const { data: customerPortal, error: portalError } = await authClient.dodopayments.customer.portal(); if (customerPortal && customerPortal.redirect) { window.location.href = customerPortal.url; } // List customer subscriptions const { data: subscriptions, error: subscriptionsError } = await authClient.dodopayments.customer.subscriptions.list({ query: { limit: 10, page: 1, status: "active", }, }); // List customer payments const { data: payments, error: paymentsError } = await authClient.dodopayments.customer.payments.list({ query: { limit: 10, page: 1, status: "succeeded", }, }); Note: All portal methods require user authentication and a verified email address. USAGE PLUGIN (METERED BILLING) Purpose: Records metered events (like API requests) for usage-based plans and surfaces recent usage history per customer. SETUP TODO LIST FOR USER: 1. Create or identify usage meters in the Dodo Payments Dashboard: - Dashboard > Products > Meters - Copy the meter IDs (prefixed with mtr_) used by your usage-based plans 2. Decide which event names and metadata you will capture (e.g., api_request, route, method) 3. Ensure BetterAuth users verify their email addresses (the plugin enforces this before ingesting usage) Configuration: Add usage to your imports in src/lib/auth.ts: import { dodopayments, usage } from "@dodopayments/better-auth"; Add the plugin to the use array: use: [ usage(), ], Usage Examples: // Record a metered event for the signed-in customer const { error: ingestError } = await authClient.dodopayments.usage.ingest({ event_id: crypto.randomUUID(), event_name: "api_request", metadata: { route: "/reports", method: "GET", }, // Optional Date or ISO string; defaults to now timestamp: new Date(), }); if (ingestError) { console.error("Failed to record usage", ingestError); } // List recent usage for the current customer const { data: usage, error: usageError } = await authClient.dodopayments.usage.meters.list({ query: { page_size: 20, meter_id: "mtr_yourMeterId", // optional filter }, }); if (usage?.items) { usage.items.forEach((event) => { console.log(event.event_name, event.timestamp, event.metadata); }); } Notes: The plugin exposes authClient.dodopayments.usage.ingest and authClient.dodopayments.usage.meters.list. Timestamps older than one hour or more than five minutes in the future are rejected. If you do not pass meter_id when listing usage, all of the customer's usage events are returned. With meter_id, only the events that match that meter are returned. WEBHOOKS PLUGIN Purpose: Handles real-time payment events from Dodo Payments with secure signature verification. BEFORE CONFIGURATION - Setup Webhook URL: First, I need your domain name to generate the webhook URL and provide you with setup instructions. STEP 1: Domain Name Input What is your domain name? Please provide: - For production: your domain name (e.g., "myapp.com", "api.mycompany.com") - For staging: your staging domain (e.g., "staging.myapp.com") - For development: use "localhost:3000" (or your local port) STEP 2: After receiving your domain name, I will: - Generate your webhook URL: https://[YOUR-DOMAIN]/api/auth/dodopayments/webhooks - Provide you with a TODO list for webhook setup in Dodo Payments dashboard - Give you the exact environment variable setup instructions WEBHOOK SETUP TODO LIST (will be provided after domain input): 1. Configure webhook in Dodo Payments Dashboard: - Go to Dodo Payments Dashboard > Developer > Webhooks - Click "Add Webhook" or "Create Webhook" - Enter webhook URL: https://[YOUR-DOMAIN]/api/auth/dodopayments/webhooks - Select events you want to receive (or select all) - Copy the generated webhook secret 2. Set webhook secret in your environment: - For production: Set DODO_PAYMENTS_WEBHOOK_KEY in your hosting provider environment - For staging: Set DODO_PAYMENTS_WEBHOOK_KEY in your staging environment - For development: Add DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_secret_here to your .env file 3. Deploy your application with the webhook secret configured STEP 3: Add webhooks to your imports in src/lib/auth.ts: import { dodopayments, webhooks } from "@dodopayments/better-auth"; STEP 4: Add webhooks plugin to the use array in your dodopayments configuration: use: [ webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, // Generic handler for all webhook events onPayload: async (payload) => { console.log("Received webhook:", payload.type); }, // Payment event handlers onPaymentSucceeded: async (payload) => { console.log("Payment succeeded:", payload); }, onPaymentFailed: async (payload) => { console.log("Payment failed:", payload); }, onPaymentProcessing: async (payload) => { console.log("Payment processing:", payload); }, onPaymentCancelled: async (payload) => { console.log("Payment cancelled:", payload); }, // Refund event handlers onRefundSucceeded: async (payload) => { console.log("Refund succeeded:", payload); }, onRefundFailed: async (payload) => { console.log("Refund failed:", payload); }, // Dispute event handlers onDisputeOpened: async (payload) => { console.log("Dispute opened:", payload); }, onDisputeExpired: async (payload) => { console.log("Dispute expired:", payload); }, onDisputeAccepted: async (payload) => { console.log("Dispute accepted:", payload); }, onDisputeCancelled: async (payload) => { console.log("Dispute cancelled:", payload); }, onDisputeChallenged: async (payload) => { console.log("Dispute challenged:", payload); }, onDisputeWon: async (payload) => { console.log("Dispute won:", payload); }, onDisputeLost: async (payload) => { console.log("Dispute lost:", payload); }, // Subscription event handlers onSubscriptionActive: async (payload) => { console.log("Subscription active:", payload); }, onSubscriptionOnHold: async (payload) => { console.log("Subscription on hold:", payload); }, onSubscriptionRenewed: async (payload) => { console.log("Subscription renewed:", payload); }, onSubscriptionPlanChanged: async (payload) => { console.log("Subscription plan changed:", payload); }, onSubscriptionCancelled: async (payload) => { console.log("Subscription cancelled:", payload); }, onSubscriptionFailed: async (payload) => { console.log("Subscription failed:", payload); }, onSubscriptionExpired: async (payload) => { console.log("Subscription expired:", payload); }, onSubscriptionUpdated: async (payload) => { console.log("Subscription updated:", payload); }, // License key event handlers onLicenseKeyCreated: async (payload) => { console.log("License key created:", payload); }, // Abandoned checkout event handlers onAbandonedCheckoutDetected: async (payload) => { console.log("Abandoned checkout detected:", payload); }, onAbandonedCheckoutRecovered: async (payload) => { console.log("Abandoned checkout recovered:", payload); }, // Dunning event handlers onDunningStarted: async (payload) => { console.log("Dunning started:", payload); }, onDunningRecovered: async (payload) => { console.log("Dunning recovered:", payload); }, // Credit event handlers onCreditAdded: async (payload) => { console.log("Credit added:", payload); }, onCreditDeducted: async (payload) => { console.log("Credit deducted:", payload); }, onCreditExpired: async (payload) => { console.log("Credit expired:", payload); }, onCreditRolledOver: async (payload) => { console.log("Credit rolled over:", payload); }, onCreditRolloverForfeited: async (payload) => { console.log("Credit rollover forfeited:", payload); }, onCreditOverageCharged: async (payload) => { console.log("Credit overage charged:", payload); }, onCreditManualAdjustment: async (payload) => { console.log("Credit manual adjustment:", payload); }, onCreditBalanceLow: async (payload) => { console.log("Credit balance low:", payload); }, }), ], Supported Webhook Event Handlers: - onPayload: Generic handler for all webhook events - onPaymentSucceeded: Payment completed successfully - onPaymentFailed: Payment failed - onPaymentProcessing: Payment is being processed - onPaymentCancelled: Payment was cancelled - onRefundSucceeded: Refund completed successfully - onRefundFailed: Refund failed - onDisputeOpened: Dispute was opened - onDisputeExpired: Dispute expired - onDisputeAccepted: Dispute was accepted - onDisputeCancelled: Dispute was cancelled - onDisputeChallenged: Dispute was challenged - onDisputeWon: Dispute was won - onDisputeLost: Dispute was lost - onSubscriptionActive: Subscription became active - onSubscriptionOnHold: Subscription was put on hold - onSubscriptionRenewed: Subscription was renewed - onSubscriptionPlanChanged: Subscription plan was changed - onSubscriptionCancelled: Subscription was cancelled - onSubscriptionFailed: Subscription failed - onSubscriptionExpired: Subscription expired - onSubscriptionUpdated: Subscription was updated - onSubscriptionPaused: Subscription was paused - onSubscriptionUnpaused: Subscription was unpaused - onSubscriptionUpdatePaymentMethod: Subscription payment method was updated - onLicenseKeyCreated: License key was created - onAbandonedCheckoutDetected: Abandoned checkout was detected - onAbandonedCheckoutRecovered: Abandoned checkout was recovered - onDunningStarted: Dunning process started - onDunningRecovered: Dunning process recovered - onCreditAdded: Credits were added - onCreditDeducted: Credits were deducted - onCreditExpired: Credits expired - onCreditRolledOver: Credits were rolled over - onCreditRolloverForfeited: Credit rollover was forfeited - onCreditOverageCharged: Credit overage was charged - onCreditOverageReset: Credit overage was reset - onCreditManualAdjustment: Manual credit adjustment was made - onCreditBalanceLow: Credit balance is low - onEntitlementGrantCreated: Entitlement grant was created - onEntitlementGrantDelivered: Entitlement grant was delivered - onEntitlementGrantFailed: Entitlement grant failed - onEntitlementGrantRevoked: Entitlement grant was revoked - onPayoutCreated: Payout was created - onPayoutOnHold: Payout was put on hold - onPayoutInProgress: Payout is in progress - onPayoutFailed: Payout failed - onPayoutSuccess: Payout succeeded COMBINING SELECTED PLUGINS: After implementing the user's selected plugins, update your src/lib/auth.ts file to include all chosen plugins in the imports and use array: Example for all four plugins: import { dodopayments, checkout, portal, usage, webhooks, } from "@dodopayments/better-auth"; use: [ checkout({ // checkout configuration }), portal(), usage(), webhooks({ // webhook configuration }), ]; Example for checkout + portal + usage: import { dodopayments, checkout, portal, usage } from "@dodopayments/better-auth"; use: [ checkout({ // checkout configuration }), portal(), usage(), ]; Example for just webhooks: import { dodopayments, webhooks } from "@dodopayments/better-auth"; use: [ webhooks({ // webhook configuration }), ]; IMPORTANT NOTES: 1. Complete Stage 1 before implementing any plugins 2. Ask the user which plugins they want to implement, or implement all four if no response 3. Only implement the plugins the user specifically requested 4. ALWAYS provide TODO lists for external actions the user needs to complete: - API key generation and environment variable setup - Product creation in Dodo Payments dashboard (for checkout plugin) - Usage meter configuration and API event definition (for usage plugin) - Webhook setup in Dodo Payments dashboard (for webhooks plugin) - Domain name collection for webhook URL generation 5. For webhook plugin: Ask for the user's domain name and generate the exact webhook URL: https://[domain]/api/auth/dodopayments/webhooks 6. The usage plugin requires the BetterAuth session user to exist and have a verified email before ingesting or listing usage 7. All client methods return { data, error } objects for proper error handling 8. Use test_mode for development and live_mode for production 9. The webhook endpoint is automatically created and secured with signature verification (if webhooks plugin is selected) 10. Customer portal and subscription listing require user authentication and a verified email (if portal plugin is selected) 11. Handle errors appropriately and test webhook functionality in development before going live 12. Present all external setup tasks as clear TODO lists with specific environment variable names 13. Use getCustomerParams to attach metadata or phone_number to DodoPayments customer records — the function receives the BetterAuth User object and runs on every customer creation and update ``` # Cursor Billing Model Source: https://docs.dodopayments.com/developer-resources/billing-deconstructions/cursor Deconstruct Cursor's model-weighted credit system and build the same hybrid subscription-plus-credits model using Dodo Payments. ## How Cursor Bills Cursor combines a monthly subscription with a depleting pool of included usage. Users pay a predictable price, and Cursor covers the variable cost of different AI models from that pool. **Pricing Tiers**: Cursor offers tiers from Hobby to Ultra. Cursor's plans include usage pools charged at each model's API price, not fixed request counts ([Cursor pricing docs](https://cursor.com/docs/account/pricing)). The request allowances in the table are illustrative values this deconstruction models. | Plan | Price | Premium Requests | Slow Requests | | :- | :- | :- | :- | | Hobby | Free | 50/month | Unlimited | | Pro | \$20/month | 500/month | Unlimited | | Pro+ | \$60/month | Unlimited premium | - | | Ultra | \$200/month | Unlimited premium | - | **Model-Weighted Depletion**: Each request consumes credits based on the cost of the underlying model. One subscription covers several model providers, and expensive operations draw more from the pool. Cursor doesn't publish per-request credit costs, so the weights below are illustrative. | Request Type | Model | Credit Cost | | :- | :- | :- | | Tab Completion | Default | 0 | | Chat | GPT-4o Mini | 1 | | Chat | Claude 3.5 Sonnet | 1 | | Composer | GPT-4o | 5 | | Agent | Claude 3.5 Sonnet | 10 | | Agent | o1-preview | 25 | **Credit Exhaustion and Overages**: When credits run out, users move to a "Slow" queue with cheaper models instead of being cut off. Users can also enable on-demand usage to keep premium access, billed at the end of the cycle. ```mermaid theme={null} flowchart TD A[User Makes Request] --> B[Determine Model and Type] B --> C[Calculate Credit Cost] C --> D{Credits Remaining?} D -->|Yes| E[Deduct Credits] E --> F[Process with Premium Model] D -->|No| G{Overage Enabled?} G -->|Yes| H[Bill Overage at End of Cycle] H --> F G -->|No| I[Route to Slow Queue] I --> J[Process with Basic Model] ``` **Enterprise**: On the Enterprise plan, the whole organization shares one usage pool. Heavy users draw from the same pool as everyone else, so one person's limit doesn't block them while teammates have unused capacity. Cursor lists pooled usage as an Enterprise feature on [its pricing page](https://cursor.com/pricing). ## What Makes It Unique Cursor's model balances user experience against infrastructure cost in four ways: * **Provider Abstraction**: One subscription wraps several LLM providers, such as OpenAI and Anthropic. Cursor handles the provider pricing and API keys. * **Weighted Depletion**: Powerful models cost more credits, so the price of a request tracks its cost. * **Graceful Degradation**: The "Slow" queue replaces a hard cutoff. Users stay in the product, and the slower experience encourages an upgrade. * **Pooled Credits**: An organization-level pool lets a team share capacity instead of managing individual limits. ## Build This with Dodo Payments You can build this model with Dodo Payments credit entitlements and usage-based billing. The steps below create the credit, the plans, the meter, the slow-queue logic, and the checkout. **1. Create a Custom Unit Credit Entitlement** Go to **Products → Credits** and click **Create Credit**. This credit represents the "Premium Requests" that come with each subscription. Use these settings: * **Credit Type:** Custom Unit * **Unit Name:** "Premium Requests" * **Precision:** 0 (a request can't be split) * **Credit Expiry:** 30 days (credits reset each billing cycle) * **Rollover:** Disabled (unused requests don't carry over) * **Allow Overage:** Enabled * **Price Per Unit:** \$0.04 (the cost of each request after the included pool is used) * **Overage Behavior:** Bill overage at billing (the overage cost is added to the next invoice) Each user gets a fixed pool of requests per cycle and pays for extra requests at the per-unit price. **2. Create Subscription Products** Create one subscription product per tier. Attach the same credit entitlement to each product with a different **Credits issued per billing cycle** value. One credit system across all tiers keeps upgrades and downgrades simple. * **Hobby:** \$0/month, 50 credits/cycle * **Pro:** \$20/month, 500 credits/cycle * **Pro+:** \$60/month, 5000 credits/cycle (effectively unlimited for most users) * **Ultra:** \$200/month, 50000 credits/cycle (effectively unlimited) When a customer subscribes, Dodo Payments grants the product's credits for the billing cycle and grants them again at each renewal. **3. Create a Usage Meter Linked to Credits** Create a meter with the event name `ai.request`, **Sum** aggregation, and `credit_cost` as the **Over Property**. On your usage-based product, toggle **Bill usage in Credits**, select the credit entitlement, and set **Meter units per credit** to 1. Your application decides the credit cost of each request from the model and the action type, then sends it in the event: ```typescript theme={null} import DodoPayments from 'dodopayments'; /** * Determines the credit cost for a given request type and model. * This logic lives in your application and can be updated without * changing your billing configuration. */ function getCreditCost(requestType: string, model: string): number { const costs: Record> = { 'tab_completion': { 'default': 0 }, 'chat': { 'gpt-4o-mini': 1, 'gpt-4o': 1, 'claude-sonnet': 1 }, 'composer': { 'gpt-4o-mini': 2, 'gpt-4o': 5, 'claude-sonnet': 5 }, 'agent': { 'gpt-4o': 10, 'claude-sonnet': 10, 'o1': 25 } }; // Default to 1 credit if the combination isn't found return costs[requestType]?.[model] ?? 1; } /** * Ingests usage events into Dodo Payments. * The meter sums credit_cost, so one event carries the full weight of the request. */ async function trackRequest(customerId: string, requestType: string, model: string) { const creditCost = getCreditCost(requestType, model); // Tab completions are free, so we don't need to track them for billing if (creditCost === 0) return; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); await client.usageEvents.ingest({ events: [{ event_id: `req_${Date.now()}_${Math.random().toString(36).slice(2)}`, customer_id: customerId, event_name: 'ai.request', timestamp: new Date().toISOString(), metadata: { request_type: requestType, model: model, credit_cost: creditCost } }] }); } ``` > [!TIP] > > A **Sum** meter over `credit_cost` lets a single event carry any weight. You send one event per request instead of one event per credit, which keeps high-volume ingestion small. **4. Handle Credit Exhaustion (Slow Queue)** Subscribe to the `credit.balance_low` webhook. When a customer's balance falls below the **Low Balance Threshold** set on the product, move them to a slow queue in your application. This is the graceful degradation logic. ```typescript theme={null} import DodoPayments from 'dodopayments'; import express from 'express'; const app = express(); app.use(express.raw({ type: 'application/json' })); const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, }); // updateUserTier, getUserTier, and notifyUser are your application's own functions. app.post('/webhooks/dodo', async (req, res) => { try { const event = client.webhooks.unwrap(req.body.toString(), { headers: { 'webhook-id': req.headers['webhook-id'] as string, 'webhook-signature': req.headers['webhook-signature'] as string, 'webhook-timestamp': req.headers['webhook-timestamp'] as string, }, }); if (event.type === 'credit.balance_low') { const customerId = event.data.customer_id; await updateUserTier(customerId, 'slow'); await notifyUser(customerId, 'You have used most of your premium requests. Switching to standard models.'); } res.json({ received: true }); } catch (error) { res.status(401).json({ error: 'Invalid signature' }); } }); /** * Routes a request based on the user's current tier. * This function is called before every AI request to determine the model and queue. */ async function routeRequest(customerId: string, requestType: string) { const tier = await getUserTier(customerId); if (tier === 'slow') { // Route to a cheaper model and a lower priority queue // This saves costs while keeping the user active in the product return { model: 'gpt-4o-mini', queue: 'standard' }; } // Premium routing for users with remaining credits // This provides the best possible performance and model quality return { model: 'claude-sonnet', queue: 'priority' }; } ``` **5. Create Checkout** Create a checkout session when a user subscribes to a plan. Dodo Payments processes the payment, calculates tax, and grants the plan's credits. ```typescript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); /** * Creates a checkout session for a new subscription. * This is typically called when a user clicks an "Upgrade" button. */ const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_cursor_pro', quantity: 1 } ], customer: { email: 'developer@example.com' }, return_url: 'https://yourapp.com/dashboard' }); ``` ## Accelerate with the LLM Ingestion Blueprint The credit-weighted events above drive billing. To also record raw token consumption per provider, run the [LLM Ingestion Blueprint](/developer-resources/ingestion-blueprints/llm) alongside your credit system. ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` ```typescript theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import OpenAI from 'openai'; import Anthropic from '@anthropic-ai/sdk'; // Track raw token usage for analytics alongside credit-weighted billing const openaiTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'analytics.openai_tokens', }); const anthropicTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'analytics.anthropic_tokens', }); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); // Wrap each provider separately const trackedOpenAI = openaiTracker.wrap({ client: openai, customerId: 'cus_abc123' }); const trackedAnthropic = anthropicTracker.wrap({ client: anthropic, customerId: 'cus_abc123' }); // Token tracking is automatic, credit deduction still uses your weighted system const response = await trackedOpenAI.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }], }); ``` Each tracked call sends `inputTokens`, `outputTokens`, `totalTokens`, and `model` in the event metadata. You get two layers of data: credit-weighted events for billing and raw token counts for cost and margin analysis. > [!TIP] > > The LLM Blueprint supports OpenAI, Anthropic, Groq, Google Gemini, OpenRouter, and the Vercel AI SDK. See the [full blueprint documentation](/developer-resources/ingestion-blueprints/llm) for all supported providers. ## Pooled Team Credits (Enterprise) Cursor's Enterprise plan pools usage across a team. To build this with Dodo Payments, create one subscription for the organization instead of one per user. The team's usage then accrues to a single billing entity, which larger customers expect. ### Implementation Strategy 1. **Organization-Level Customer:** Create one Dodo Payments customer for the whole organization. This customer holds the shared credit pool, and all invoices and credit grants belong to its `customer_id`. 2. **Seat-Based Billing:** Charge a per-user platform fee with a seat add-on, as described in [Seat-Based Billing](/features/seat-based-billing). When the team adds a member, change the add-on quantity. Revenue grows with the number of users, and the credit pool stays separate. 3. **Shared Usage Tracking:** Send every team member's requests with the organization's `customer_id`, so each request depletes the same pool. To report on individual users, add a `user_id` to the event metadata. Each member pays a predictable platform fee, and the team shares one pool of credits for the expensive AI resources. Members don't manage their own limits. ## Comparison with Traditional SaaS Billing Traditional SaaS billing uses flat-rate tiers, for example \$10/month for 100 units. A user who needs 101 units must often jump to a \$50/month tier. This "cliff" frustrates users and drives churn. Flat tiers also ignore the different costs of different kinds of usage, which matter for AI products. A Cursor-style model built on Dodo Payments avoids these problems: * **No "Cliff" Effects:** Users don't have to upgrade when they hit a limit. They can pay for overage or accept slower performance, so they keep working in the product. * **Cost Alignment:** Revenue follows infrastructure cost. Users of expensive models pay more, through credits or overage, which protects your margins on high-cost features. * **Better Retention:** Users who reach their limit can keep working instead of being cut off. Continued use builds loyalty and raises customer lifetime value. ## Handling Model Updates and Evolution AI providers update and replace models often, and a new model can have a different cost. Because credit costs live in your application, you can price a new model without migrating billing data. To add a more expensive model, give it a higher cost in `getCreditCost`. You don't change the credit entitlement, the meter, or existing subscriptions. Billing stays separate from application logic, so you can ship model changes without touching billing. ## User Notifications and Transparency Show users how many credits they have used so they can manage cost and trust the bill. The `credit.balance_low` webhook fires when a balance drops below the product's **Low Balance Threshold**. For more checkpoints, such as 50% and 80% usage, compare the balance in `credit.deducted` events against the plan's allocation. Send these alerts by email, in-app message, or Slack. A timely warning lets users reduce usage or upgrade before they reach the slow queue, which reduces support tickets. ## Security and Fraud Prevention Credits have direct monetary value, so protect the system that spends them. * **Idempotency:** Give every usage event a unique `event_id`. Dodo Payments uses `event_id` to detect duplicates, so a network retry with the same ID doesn't charge the user twice. * **Rate Limiting:** Limit request rates in your application so one user can't exhaust their credits, or your provider budget, too quickly. * **Monitoring:** Watch usage for anomalies such as account sharing or automated abuse. The meter dashboard's **Customers** view shows per-customer usage totals. ## Best Practices for Credit Systems Keep these practices in mind when you design a credit system: 1. **Keep it Simple:** Users should understand what a request costs and how many credits they have left. 2. **Provide Value:** Price requests so users feel the credits are worth it. A cost that feels too high for a small action reads as nickel-and-diming. 3. **Be Transparent:** Show the current credit balance and usage history. Customers can also see both in the Customer Portal. 4. **Automate Everything:** Use Dodo Payments webhooks and APIs to automate billing tasks and remove manual work. ## Key Dodo Features Used > [card] [Credit-Based Billing](/features/credit-based-billing) > > Manage depleting credit pools and overages with custom units. > [card] [Subscriptions](/features/subscription) > > Set up recurring billing for different tiers with integrated credits. > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Track events and bill based on consumption. > [card] [Event Ingestion](/features/usage-based-billing/event-ingestion) > > Send high-volume usage data to Dodo Payments. > [card] [Webhooks](/developer-resources/webhooks/intents/credit) > > React to credit balance changes and automate user tiering. > [card] [LLM Ingestion Blueprint](/developer-resources/ingestion-blueprints/llm) > > Automatic token tracking across multiple LLM providers. # ElevenLabs Billing Model Source: https://docs.dodopayments.com/developer-resources/billing-deconstructions/elevenlabs Deconstruct ElevenLabs' character-based billing with rollover credits and tiered overage pricing, then build the same model using Dodo Payments. ElevenLabs bills its AI voice products from a single pool of credits tied to the subscription tier. For text-to-speech, one character costs about one credit, so the character is the unit most users track. Text-to-speech, voice cloning, and dubbing all draw from the same pool. ## How ElevenLabs Bills ElevenLabs sells fixed monthly quotas through subscription tiers. Higher tiers include more characters and more advanced features, such as Professional Voice Cloning and commercial rights. | Plan | Price | Credits/Month | | :- | :- | :- | | Free | \$0 | 10,000 | | Starter | \$6/month | 30,000 | | Creator | \$22/month | 121,000 | | Pro | \$99/month | 600,000 | | Scale | \$299/month | 1,800,000 | | Business | \$990/month | 6,000,000 | 1. **Character-based pricing**: Characters, counted as credits, are the shared unit across the platform. Text-to-speech, dubbing, and voice cloning all draw from the same balance, so users track one number. 2. **Rollover mechanics**: Unused credits roll over to the next billing cycle instead of expiring. ElevenLabs caps rollover at two months of unused quota, so a balance can reach at most three times the monthly quota. Rollover requires an active paid plan and doesn't apply to the Free plan ([ElevenLabs pricing FAQ](https://elevenlabs.io/pricing)). 3. **Tiered overages**: Overage depends on the subscription tier. Enterprise and legacy Creator, Pro, Scale, and Business plans can opt in to usage-based billing, which charges a plan-specific price for each extra 1,000 credits. New self-serve subscriptions use Pay As You Go top-up credits instead ([ElevenLabs billing docs](https://elevenlabs.io/docs/overview/administration/billing)). ## What Makes It Unique Four choices make the ElevenLabs model good at retaining users and driving upgrades: * **Character Rollover**: Rollover reduces "use it or lose it" anxiety. A quiet month doesn't waste the subscription. * **Tiered Overage Pricing**: Overage rates fall as plan size grows, so heavy users have a strong financial reason to upgrade. * **Unified Consumption**: One pool for all services means users don't juggle separate quotas. * **Opt-in Overages**: Professional users can turn on overage for continuity, and casual users keep the safety of a hard cap. The diagram shows one billing cycle, from fresh credits to rollover: ```mermaid theme={null} flowchart TD A[New Billing Cycle] --> B[Fresh Credits + Rolled Over] B --> C[User Generates Audio] C --> D{Characters Left?} D -->|Yes| C D -->|No| E{Overage Enabled?} E -->|Yes| F[Bill at Tier Rate] F --> C E -->|No| G[Generation Blocked] D -->|Cycle Ends| H[Unused Credits Roll Over] H --> A ``` ## Build This with Dodo Payments You can build this model with Dodo Payments credit-based billing and usage metering. **1. Create a Custom Unit Credit Entitlement** Define the "Characters" unit that serves as your platform's currency. 1. Go to **Products → Credits** in your Dodo Payments dashboard. 2. Click **Create Credit**. 3. Set **Credit Type** to **Custom Unit**. 4. Set **Unit Name** to "Characters". 5. Set **Precision** to 0, because characters are whole units. 6. Set **Credit Expiry** to 30 days to match the monthly billing cycle. 7. Enable **Rollover** with these settings: * **Max Rollover Percentage**: 100% (all unused characters carry over). * **Rollover Timeframe**: 1 Month. * **Max Rollover Count**: 2 (credits can roll over twice, matching ElevenLabs' two-month cap, then they're forfeited). **2. Create Tiered Subscription Products** Create five subscription products. Attach the same "Characters" credit to each, with a different configuration per tier. | Product | Price | Credits/Cycle | Overage Enabled | Overage Price (per 1K chars) | | :- | :- | :- | :- | :- | | Free | \$0/mo | 10,000 | No | - | | Starter | \$5/mo | 30,000 | Yes (opt-in) | \$0.30 | | Creator | \$22/mo | 100,000 | Yes | \$0.24 | | Pro | \$99/mo | 500,000 | Yes | \$0.15 | | Scale | \$330/mo | 2,000,000 | Yes | \$0.10 | When you attach the credit to each product, turn off **Import Default Credit Settings**. You can then set this tier's own **Price Per Unit** for overage. Because one credit is one character, enter the per-character price: \$0.24 per 1K characters is \$0.00024 per credit. Set **Overage Behavior** to **Bill overage at billing**, and set a **Low Balance Threshold** at 10% of the tier's quota. **3. Create a Usage Meter** The usage meter connects activity in your application to the credit balance. 1. Create a meter with the event name `tts.characters`. 2. Set **Aggregation** to **Sum** and **Over Property** to `characters`. The meter adds up the `characters` value from every event. 3. On your usage-based product, toggle **Bill usage in Credits** and select the "Characters" credit. 4. Set **Meter units per credit** to 1, so one character used in your app deducts one credit. **4. Send Usage Events** Send an event to Dodo Payments each time a user generates audio. ```typescript theme={null} import DodoPayments from 'dodopayments'; async function trackGeneration( customerId: string, text: string, service: 'tts' | 'dubbing' | 'cloning' ) { const characterCount = text.length; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); await client.usageEvents.ingest({ events: [{ event_id: `gen_${Date.now()}_${Math.random().toString(36).slice(2)}`, customer_id: customerId, event_name: 'tts.characters', timestamp: new Date().toISOString(), metadata: { characters: characterCount, service: service, voice_id: 'voice_abc123' } }] }); } ``` **5. Handle Low Balance and Overage** Use webhooks to tell users about their character usage. ```typescript theme={null} import DodoPayments from 'dodopayments'; import express from 'express'; const app = express(); app.use(express.raw({ type: 'application/json' })); const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, }); // notifyUser and logUsage are your application's own functions. app.post('/webhooks/dodo', async (req, res) => { try { const event = client.webhooks.unwrap(req.body.toString(), { headers: { 'webhook-id': req.headers['webhook-id'] as string, 'webhook-signature': req.headers['webhook-signature'] as string, 'webhook-timestamp': req.headers['webhook-timestamp'] as string, }, }); switch (event.type) { case 'credit.balance_low': await notifyUser(event.data.customer_id, 'You are running low on characters. Consider upgrading your plan for more characters and lower overage rates.' ); break; case 'credit.deducted': await logUsage(event.data); break; case 'credit.overage_charged': await notifyUser(event.data.customer_id, 'You have exceeded your character quota. Overage charges will appear on your next invoice.' ); break; } res.json({ received: true }); } catch (error) { res.status(401).json({ error: 'Invalid signature' }); } }); ``` **6. Create Checkout** When a user is ready to subscribe, create a checkout session for the chosen tier. This snippet reuses the `client` from the webhook step. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_elevenlabs_pro', quantity: 1 } ], customer: { email: 'creator@example.com' }, return_url: 'https://yourapp.com/dashboard' }); ``` ## Accelerate with the Stream Ingestion Blueprint To track audio output alongside character-based billing, use the [Stream Ingestion Blueprint](/developer-resources/ingestion-blueprints/stream). It meters the bytes each generation produces. ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` ```typescript theme={null} import { Ingestion, trackStreamBytes } from '@dodopayments/ingestion-blueprints'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'tts.audio_bytes', }); // generateSpeech, text, voiceId, and customerId come from your application. const audioBuffer = await generateSpeech(text, voiceId); await trackStreamBytes(ingestion, { customerId: customerId, bytes: audioBuffer.byteLength, metadata: { voice_id: voiceId, service: 'tts', format: 'mp3', }, }); ``` The byte counts show the infrastructure cost of each generation, while the character-based credits handle billing. > [!TIP] > > Each `trackStreamBytes` call sends one event. See the [full blueprint documentation](/developer-resources/ingestion-blueprints/stream) for more usage patterns. ## Upgrade Incentive: Tiered Overage Pricing ElevenLabs uses overage rates to drive upgrades. Because each extra character costs less on a higher tier, the question changes from "how much do I need?" to "how much can I save?". | Tier | Included Chars | Overage (per 1K) | Effective Cost at 500K Chars | | :- | :- | :- | :- | | Creator | 100,000 | \$0.24 | \$22 + (400 \* \$0.24) = \$118 | | Pro | 500,000 | \$0.15 | \$99 (No overage) | A user who uses 500,000 characters a month on the Creator plan pays \$118 in subscription plus overage. The Pro plan covers the same usage for \$99, a saving of \$19 per month. As usage grows, upgrading becomes the cheaper choice. To build this with Dodo Payments, turn off **Import Default Credit Settings** when you attach the credit to each subscription product. You can then set a different **Price Per Unit** for each tier and give your largest customers the lowest rates. ## Key Dodo Features Used > [card] [Credit-Based Billing](/features/credit-based-billing) > > Manage character quotas, rollovers, and expirations. > [card] [Subscriptions](/features/subscription) > > Set up the recurring tiers that deliver monthly character allowances. > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Track character consumption across your services. > [card] [Event Ingestion](/features/usage-based-billing/event-ingestion) > > Send high-volume usage data to Dodo Payments. > [card] [Webhooks](/developer-resources/webhooks/intents/credit) > > React to low balances and overage events. > [card] [Stream Ingestion Blueprint](/developer-resources/ingestion-blueprints/stream) > > Track audio streaming bandwidth for usage-based billing. # Billing Deconstructions Source: https://docs.dodopayments.com/developer-resources/billing-deconstructions/introduction Study how six AI companies charge their users, then rebuild each billing model with Dodo Payments credits, meters, and subscriptions. ## Overview Each deconstruction breaks down the billing model of a real AI company and shows you how to rebuild it with Dodo Payments. The table below compares the six models by the metric each one charges for. | App | Primary Metric | Unique Innovation | Dodo Feature | | :- | :- | :- | :- | | OpenAI | Tokens (fiat-denominated) | Prepaid fiat credits with a long-lived balance | Credit-Based Billing (Fiat Credits) | | Cursor | Premium Requests | Model-weighted credit depletion (different costs per model) | Credit-Based Billing (Custom Unit) | | ElevenLabs | Characters | Character quotas with rollover + tiered overage pricing | Credit-Based Billing (Rollover + Overage) | | Midjourney | GPU Time | "Relax Mode" unlimited fallback after quota | Subscription + Usage Meters | | Replicate | Execution Seconds | Per-second hardware-specific pure metering | Pure Usage-Based Billing | | Lovable | Messages (credits) | Daily bonus drip + team-wide shared credit pool | Credit-Based Billing (Custom Unit) + Subscription | Third-party prices change often. Each page describes the company's model at the time of writing, so check the company's pricing page before you copy a number. Pick the app closest to what you are building: > [card] [OpenAI](/developer-resources/billing-deconstructions/openai) > > Replicate the token-based prepaid credit model. > [card] [Cursor](/developer-resources/billing-deconstructions/cursor) > > Build model-weighted usage limits. > [card] [ElevenLabs](/developer-resources/billing-deconstructions/elevenlabs) > > Implement character quotas with rollover and overages. > [card] [Midjourney](/developer-resources/billing-deconstructions/midjourney) > > Combine subscriptions with usage-based fallback. > [card] [Replicate](/developer-resources/billing-deconstructions/replicate) > > Set up pure per-second consumption metering. > [card] [Lovable](/developer-resources/billing-deconstructions/lovable) > > Replicate message-credit subscriptions with daily bonus drip. ## Dodo Features Every deconstruction combines some of these Dodo Payments features: > [card] [Credit-Based Billing](/features/credit-based-billing) > > Manage prepaid credits and virtual units. > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Meter consumption with usage events. > [card] [Subscriptions](/features/subscription) > > Handle recurring billing and plan management. > [card] [Hybrid Billing](/features/hybrid-billing) > > Combine subscriptions, usage, and credits in one product. ## Ingestion Blueprints Each deconstruction also shows an [Ingestion Blueprint](/features/usage-based-billing/ingestion-blueprints): a helper from the `@dodopayments/ingestion-blueprints` package that builds and sends usage events for a common pattern. Use a blueprint instead of constructing each usage event by hand. > [card] [LLM Blueprint](/developer-resources/ingestion-blueprints/llm) > > Automatic token tracking for OpenAI, Anthropic, Groq, and more. > [card] [Stream Blueprint](/developer-resources/ingestion-blueprints/stream) > > Track audio and video streaming bandwidth. > [card] [Time Range Blueprint](/developer-resources/ingestion-blueprints/time-range) > > Bill by compute duration in milliseconds, seconds, or minutes. # Lovable Billing Model Source: https://docs.dodopayments.com/developer-resources/billing-deconstructions/lovable Deconstruct Lovable's message-credit subscription with daily bonus drip, team-wide sharing, and separate cloud metering, then build the same model using Dodo Payments. Lovable (lovable.dev) is an AI web app builder that charges in credits instead of tokens. Users spend credits by sending messages to the AI builder. A monthly credit pool supports bursts of work, and a daily bonus drip rewards users who come back every day. ## Lovable's Billing Model Lovable's pricing combines message credits with separate metering for cloud hosting and AI features. | Plan | Price | Monthly Credits | Daily Bonus | Key Features | | :- | :- | :- | :- | :- | | Free | \$0/month | 0 | 5/day (up to 30/month) | Public projects only | | Pro | \$25/month | 100 | 5/day | On-demand top-ups, usage-based Cloud + AI, custom domains | | Business | \$50/month | 100 | 5/day | SSO, team workspace, design templates, security center | | Enterprise | Custom | Custom | Custom | SCIM, dedicated support, audit logs | Lovable's pricing FAQ describes these rules ([lovable.dev/pricing](https://lovable.dev/pricing)): * **Credit-based subscription**: Messages to the AI spend credits. In Plan Mode, 1 credit = 1 message. In Default Mode, the cost varies with task complexity. * **Credits are shared across unlimited users**: Every member of a workspace draws from one pool. Plans are priced by credits, not per seat. * **Monthly credits refresh on renewal**: Each renewal adds the plan's credits. Unused monthly credits expire two months after they're issued. * **On-demand credit top-ups**: Users can buy more credits if they run out. Top-up credits last 12 months. * **Separate usage-based Cloud + AI billing**: Hosting and AI features in user apps have their own monthly grant, then draw from the credit balance. * **Daily bonus credits reset each day**: A use-it-or-lose-it daily drip of 5 credits that doesn't roll over. ## What Makes It Unique * **Message-based simplicity**: Users think in messages, not tokens or model weights. This deconstruction models the simplest form, 1 credit = 1 message. * **Daily drip + monthly pool hybrid**: The 5 daily bonus credits reward daily use, and the 100 monthly credits cover bursts of work. * **Team-wide shared pool**: Credits are shared across unlimited users for a flat team price, not per seat. * **Two-layer billing**: Credits pay for AI interactions, and cloud infrastructure is metered separately. ## Build This with Dodo Payments You can build Lovable's hybrid model with Dodo Payments credit entitlements and usage-based meters. **1. Create a Custom Unit Credit Entitlement** In your Dodo Payments dashboard, go to **Products → Credits** and create the message credit. This credit holds the monthly pool. * **Credit Type**: Custom Unit * **Unit Name**: "Messages" * **Precision**: 0 * **Credit Expiry**: 60 days (matches Lovable's two-month expiry for monthly credits) * **Allow Overage**: Disabled Dodo Payments doesn't block usage when a balance reaches zero. To enforce a hard cap, check the balance in your application before you accept a message. **2. Create Subscription Products** Create your plans and attach the credit to the paid ones. Your application handles the Free plan's daily bonus. * **Free**: \$0/mo, 0 credits (daily bonus handled by app logic) * **Pro**: \$25/mo, 100 credits/cycle, attach credit entitlement * **Business**: \$50/mo, 100 credits/cycle, attach credit entitlement ```typescript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_lovable_pro', quantity: 1 } ], customer: { email: 'user@example.com' }, return_url: 'https://yourapp.com/dashboard' }); ``` **3. Create a Usage Meter for Cloud + AI** Lovable bills cloud infrastructure separately from messages. Create a meter to track it. * **Event name**: `cloud.compute_seconds` * **Aggregation**: Sum, with `compute_seconds` as the **Over Property** Add this meter to your subscription products with a price per unit. Dodo Payments calculates the charge from the usage you send. This snippet reuses the `client` from the previous step. ```typescript theme={null} await client.usageEvents.ingest({ events: [{ event_id: `compute_${Date.now()}`, customer_id: 'cus_abc123', event_name: 'cloud.compute_seconds', timestamp: new Date().toISOString(), metadata: { compute_seconds: 3600, project_id: 'proj_abc' } }] }); ``` **4. Implement Daily Bonus Credits (Application Logic)** Your application handles the daily bonus drip. Reset a daily counter with a scheduled job, and spend bonus credits before the Dodo Payments balance. Bonus messages use a separate event name, `ai.message.bonus`, that no credit-linked meter uses. They're recorded for analytics without deducting from the monthly pool. ```typescript theme={null} // Example cron job logic (pseudo-code) // Every day at midnight UTC: // 1. Reset 'daily_bonus_used' to 0 for all users in your DB // db is your application's database client. The user's dodo_customer_id is the // Dodo Payments customer ID (cus_...) you stored when they subscribed. async function handleMessage(userId: string) { const user = await db.users.findUnique({ where: { id: userId } }); if (user.daily_bonus_used < 5) { // Use daily bonus await db.users.update({ where: { id: userId }, data: { daily_bonus_used: { increment: 1 } } }); // Track for analytics but don't deduct from Dodo credits yet await client.usageEvents.ingest({ events: [{ event_id: `msg_bonus_${Date.now()}`, customer_id: user.dodo_customer_id, event_name: 'ai.message.bonus', timestamp: new Date().toISOString(), metadata: { type: 'daily_bonus' } }] }); } else { // Deduct from Dodo credit entitlement await client.usageEvents.ingest({ events: [{ event_id: `msg_${Date.now()}`, customer_id: user.dodo_customer_id, event_name: 'ai.message', timestamp: new Date().toISOString(), metadata: { type: 'subscription_credit' } }] }); } } ``` **5. Send Usage Events for Messages** Track each AI message as a usage event. Create a **Count** meter for the `ai.message` event, toggle **Bill usage in Credits** on it, select the "Messages" credit, and set **Meter units per credit** to 1. ```typescript theme={null} await client.usageEvents.ingest({ events: [{ event_id: `msg_${Date.now()}`, customer_id: 'cus_abc123', event_name: 'ai.message', timestamp: new Date().toISOString(), metadata: { content_length: 450, project_id: 'proj_abc', feature_type: 'editor' } }] }); ``` **6. Handle Webhooks for Low Balance** Notify users when their credits run low so they can top up or upgrade. ```typescript theme={null} import DodoPayments from 'dodopayments'; import express from 'express'; const app = express(); app.use(express.raw({ type: 'application/json' })); const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, }); // notifyUser is your application's own function. app.post('/webhooks/dodo', async (req, res) => { try { const event = client.webhooks.unwrap(req.body.toString(), { headers: { 'webhook-id': req.headers['webhook-id'] as string, 'webhook-signature': req.headers['webhook-signature'] as string, 'webhook-timestamp': req.headers['webhook-timestamp'] as string, }, }); if (event.type === 'credit.balance_low') { const { customer_id, available_balance } = event.data; await notifyUser(customer_id, `Your balance is low: ${available_balance} messages left.`); } res.json({ received: true }); } catch (error) { res.status(401).json({ error: 'Invalid signature' }); } }); ``` ## Accelerate with the LLM Ingestion Blueprint The [LLM Ingestion Blueprint](/developer-resources/ingestion-blueprints/llm) wraps your AI client and sends a usage event for every call. ```typescript theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import OpenAI from 'openai'; const tracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'ai.message', }); const trackedClient = tracker.wrap({ client: new OpenAI(), customerId: 'cus_abc123', }); // Sends one ai.message event; the Count meter above deducts 1 credit per event await trackedClient.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Build a landing page' }], }); ``` > [!TIP] > > Each event also carries `inputTokens`, `outputTokens`, `totalTokens`, and `model` in its metadata. See the [full blueprint documentation](/developer-resources/ingestion-blueprints/llm) for more details on automatic tracking. ## Architecture Overview The sequence below shows one message: the app spends the daily bonus first, then the Dodo Payments credit balance, and meters cloud usage separately. ```mermaid theme={null} sequenceDiagram participant U as User participant A as Your App participant D as Dodo Payments participant L as LLM Provider participant C as Cloud Infrastructure U->>A: Send Message A->>A: Check Daily Bonus Pool alt Daily Bonus Available A->>A: Deduct Daily Bonus else No Daily Bonus A->>D: Check Credit Balance D-->>A: Balance Available A->>D: Ingest Message Event end A->>L: Call LLM L-->>A: AI Response A->>C: Execute Compute/Hosting A->>D: Ingest Cloud Usage Event A-->>U: Return Response ``` ## Key Dodo Features Used These Dodo Payments features power the implementation: > [card] [Credit-Based Billing](/features/credit-based-billing) > > Manage message credits and shared team pools. > [card] [Subscriptions](/features/subscription) > > Set up recurring plans for Pro and Business tiers. > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Meter cloud infrastructure usage separately from AI credits. > [card] [Event Ingestion](/features/usage-based-billing/event-ingestion) > > Send high-volume message and compute events to Dodo Payments. > [card] [Webhooks](/developer-resources/webhooks/intents/credit) > > Automate notifications for low credit balances. > [card] [LLM Ingestion Blueprint](/developer-resources/ingestion-blueprints/llm) > > Simplify AI usage tracking with pre-built integrations. # Midjourney Billing Model Source: https://docs.dodopayments.com/developer-resources/billing-deconstructions/midjourney Deconstruct Midjourney's GPU-time subscription with Relax Mode fallback and build the same model using Dodo Payments. Midjourney is a generative AI platform that bills by GPU time instead of by image count. A complex, high-resolution render uses more GPU time, and so more of the plan, than a quick low-resolution draft. ## How Midjourney Bills Each Midjourney subscription includes a monthly allowance of "Fast GPU Time", the computing time spent on your generations. The figures below come from [Midjourney's plan comparison](https://docs.midjourney.com/hc/en-us/articles/27870484040333-Comparing-Midjourney-Plans). | Plan | Price | Fast GPU Hours | Relax Mode | Stealth Mode | | :- | :- | :- | :- | :- | | Basic | \$10/month | \~3.3 hrs | No | No | | Standard | \$30/month | 15 hrs | Unlimited | No | | Pro | \$60/month | 30 hrs | Unlimited | Yes | | Mega | \$120/month | 60 hrs | Unlimited | Yes | 1. **Pricing Tiers**: Midjourney offers four subscription levels from \$10 to \$120 per month. Each includes a set amount of Fast GPU time. 2. **Relax Mode**: Standard and higher plans include unlimited image generations in a low-priority queue after Fast time runs out, so users don't hit a hard wall. 3. **Extra GPU Hours**: Users can buy extra Fast GPU time for \$4 per hour when they need fast results after using their monthly allowance. 4. **Metering in GPU Seconds**: Usage is measured as the GPU time each generation takes, so complex renders cost more than simple drafts. 5. **Community Loop**: Users can earn free GPU time by rating images, which also helps train Midjourney's models. ## What Makes It Unique The Midjourney model ties what a user pays to the resources they consume: * **GPU-time billing** prices complex renders higher than simple drafts, in line with their compute cost. * **Relax Mode** is an unlimited fallback that reduces churn, because users keep access after the monthly allowance runs out. * **The Fast vs Relax split** encourages upgrades by selling priority processing to users who value speed. * **Extra GPU Hours** give power users a mid-month top-up for high-priority capacity. ## Build This with Dodo Payments You can build this model with Dodo Payments by combining subscriptions, usage meters, and logic in your application. **1. Create a Usage Meter** Create a meter that tracks the GPU seconds each customer uses. * **Event name**: `gpu.fast_seconds` * **Aggregation**: **Sum**, with `gpu_seconds` as the **Over Property** Send events only for Fast mode generations. Relax mode generations aren't metered for billing. **2. Create Subscription Products with Usage Pricing** Create your subscription products and add the usage meter with a **Free Threshold** equal to the plan's Fast GPU allowance. | Product | Base Price | Free Threshold (seconds) | Overage Rate | | :- | :- | :- | :- | | Basic | \$10/month | 12,000 (3.3 hrs) | N/A (Hard Cap) | | Standard | \$30/month | 54,000 (15 hrs) | \$0.00 (Relax Mode) | | Pro | \$60/month | 108,000 (30 hrs) | \$0.00 (Relax Mode) | | Mega | \$120/month | 216,000 (60 hrs) | \$0.00 (Relax Mode) | Set the price per unit to \$0 on every plan, so usage above the threshold isn't charged. Dodo Payments doesn't stop usage at the threshold. Your application enforces the Basic plan's hard cap and routes the other plans to Relax Mode once the meter passes the threshold. **3. Implement Application-Level Relax Mode** Relax Mode isn't a billing feature. Your application sends requests to a slower queue when the Dodo Payments usage meter shows the customer has passed the plan's threshold. ```typescript theme={null} // getCustomerUsage, getSubscription, getThresholdForPlan, and queueGeneration are // your application's own functions. getCustomerUsage can sum this cycle's events // from client.usageEvents.list() or read a counter your app maintains. async function handleGenerationRequest(customerId: string, prompt: string) { const usage = await getCustomerUsage(customerId, 'gpu.fast_seconds'); const subscription = await getSubscription(customerId); const threshold = getThresholdForPlan(subscription.product_id); if (usage.current >= threshold) { if (subscription.product_id === 'pdt_basic') { throw new Error('Fast GPU hours exhausted. Upgrade to Standard for Relax Mode.'); } // Relax Mode. Route to low-priority queue return await queueGeneration(customerId, prompt, { priority: 'low', mode: 'relax', model: 'standard' }); } // Fast Mode. Priority processing return await queueGeneration(customerId, prompt, { priority: 'high', mode: 'fast', model: 'premium' }); } ``` **4. Send Usage Events (Fast Mode Only)** Send a usage event to Dodo Payments only when a generation runs in Fast mode. ```typescript theme={null} import DodoPayments from 'dodopayments'; async function trackFastGeneration(customerId: string, gpuSeconds: number, jobId: string) { // Only track Fast mode generations. Relax mode is free and unlimited const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); await client.usageEvents.ingest({ events: [{ event_id: `gen_${jobId}`, customer_id: customerId, event_name: 'gpu.fast_seconds', timestamp: new Date().toISOString(), metadata: { gpu_seconds: gpuSeconds, resolution: '1024x1024', mode: 'fast' } }] }); } ``` **5. Sell Extra Fast Hours (One-Time Top-Up)** Create a one-time payment product called "Extra Fast GPU Hour" priced at \$4. When a customer buys it, raise their threshold in your application by 3,600 seconds per hour purchased. ```typescript theme={null} // After customer purchases extra hours const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_extra_gpu_hour', quantity: 5 } ], customer: { customer_id: customerId }, return_url: 'https://yourapp.com/dashboard' }); ``` **6. Create Checkout for Subscription** Create a checkout session for the subscription plan. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_mj_standard', quantity: 1 } ], customer: { email: 'artist@example.com' }, return_url: 'https://yourapp.com/studio' }); ``` ## Accelerate with the Time Range Ingestion Blueprint The [Time Range Ingestion Blueprint](/developer-resources/ingestion-blueprints/time-range) provides helpers for duration-based billing that make GPU time tracking shorter to write. ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` ```typescript theme={null} import { Ingestion, trackTimeRange } from '@dodopayments/ingestion-blueprints'; const ingestion = new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'gpu.fast_seconds', }); // runGeneration, prompt, settings, and customerId come from your application. const startTime = Date.now(); const result = await runGeneration(prompt, settings); const durationMs = Date.now() - startTime; await trackTimeRange(ingestion, { customerId: customerId, durationMs: durationMs, metadata: { mode: 'fast', resolution: '1024x1024', }, }); ``` The blueprint builds the event and sends the duration in its metadata. You provide the customer ID and the elapsed time. This example sends `durationMs`, so set the meter's **Over Property** to `durationMs`, or send `durationSeconds` to match a meter over seconds. > [!TIP] > > The Time Range Blueprint accepts durations in milliseconds, seconds, or minutes. See the [full blueprint documentation](/developer-resources/ingestion-blueprints/time-range) for all duration options and best practices. ## The Fast vs Relax Architecture The two queues work by routing each request based on the customer's current usage. ```mermaid theme={null} flowchart TD A[Generation Request] --> B{GPU Usage < Threshold?} B -->|Yes| C[Fast Queue] C --> D[Priority Processing] D --> E[Meter GPU Seconds] B -->|No| F{Plan Has Relax Mode?} F -->|Yes| G[Relax Queue] G --> H[Low Priority, Unmetered] F -->|No| I[Request Blocked] ``` 1. All requests go through your application. 2. The application compares the customer's Fast GPU usage with the plan's free threshold. 3. If usage is under the threshold, the request goes to the Fast queue and is metered. 4. If usage is over the threshold, the request goes to the Relax queue, which is unmetered and lower priority. 5. The Basic plan has no Relax fallback, so the application blocks requests once the limit is reached. > [!NOTE] > > Relax Mode is an application-level pattern, not a Dodo Payments billing feature. Dodo Payments records your customers' Fast GPU usage. Your application decides whether to block the user or send them to a slower queue. ## Key Dodo Features Used > [card] [Subscriptions](/features/subscription) > > Manage recurring billing and plan tiers. > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Track and bill based on actual resource consumption. > [card] [Event Ingestion](/features/usage-based-billing/event-ingestion) > > Send high-volume usage events to the Dodo Payments API. > [card] [Meters](/features/usage-based-billing/meters) > > Define how usage events are aggregated and billed. > [card] [One-Time Payments](/features/one-time-payment-products) > > Sell extra hours or top-ups as one-time purchases. > [card] [Time Range Blueprint](/developer-resources/ingestion-blueprints/time-range) > > Simplified GPU time tracking with duration-based helpers. # OpenAI Billing Model Source: https://docs.dodopayments.com/developer-resources/billing-deconstructions/openai Deconstruct OpenAI's token-based billing with prepaid fiat credits, then rebuild it with Dodo Payments credit entitlements, usage meters, and rate tiers. OpenAI combines prepaid fiat credits for API usage with flat-rate subscriptions for its consumer products. The prepaid side gives OpenAI cash up front, and developers can scale usage without a sales conversation. Many AI companies copy this model. ## Why OpenAI's Model is the Standard Traditional SaaS billing doesn't handle the variable cost of AI usage well. OpenAI's model solves three problems at once: 1. **Predictable Revenue and Low Risk**: Because API usage is prepaid, users can't run up bills they can't pay. OpenAI receives the money up front, and the user spends it as they use the service. 2. **Scalability for Developers**: A \$5 top-up is a low barrier to entry. As an application grows, developers can automate top-ups or buy larger packs. Starting is cheap, and usage can grow without a plan change. 3. **User Psychology**: Credits denominated in US dollars, instead of abstract "tokens" or "points", make the value clear. The balance works like a prepaid account for AI services, which makes budgeting easier for companies. ## How OpenAI Bills OpenAI runs two billing models for different users. 1. **API (Pay-as-you-go)**: The API uses prepaid, dollar-denominated credits. Users top up their accounts with \$5, \$10, \$50, or more. The credits show a dollar value but can't be used outside OpenAI. OpenAI bills per token, with different rates for input and output tokens. Purchased credits expire one year after purchase and are non-refundable ([OpenAI Help Center](https://help.openai.com/en/articles/8264644-setting-up-and-managing-prepaid-api-billing)). When a balance reaches \$0, API calls fail. 2. **ChatGPT Plus, Business, and Enterprise**: These are flat-rate subscriptions. ChatGPT Plus costs \$20 per month, and the Business plan (formerly Team) costs \$25 per user per month when billed monthly. They have soft usage caps: heavy users move to a smaller model instead of being blocked. 3. **Spend-based rate tiers**: As total spend grows over time, the account unlocks higher API rate limits. Access grows with billing history. The token prices below are the published rates at the time of writing: | Model | Pricing | Input Tokens | Output Tokens | | :- | :- | :- | :- | | GPT-4o | Usage-based | \$2.50 / 1M | \$10.00 / 1M | | GPT-4o-mini | Usage-based | \$0.15 / 1M | \$0.60 / 1M | | o1 | Usage-based | \$15.00 / 1M | \$60.00 / 1M | | Plan | Price | Type | | :- | :- | :- | | Free | \$0 | Limited access | | Plus | \$20 / mo | Subscription with soft caps | | Business | \$25 / user / mo | Per-seat subscription | | Enterprise | Custom | Invoiced billing | ## What Makes It Unique Four characteristics make OpenAI's billing effective for AI services: * **Fiat-denominated credits**: Credits are in US dollars, so they feel like money. Developers can read the price of a request directly. * **Long expiry**: Purchased credits last a year, which reduces "use it or lose it" pressure. Users are comfortable topping up larger amounts. * **Multi-dimensional metering**: Input and output tokens are tracked separately but deduct from the same balance. OpenAI can price expensive output tokens higher than input tokens. * **Trust tiers**: Rate limits that rise with total spend reward long-term customers and encourage them to stay. ## Strategic Advantages The model reinforces itself. Low entry costs bring in developers. Prepaid credits provide immediate cash flow. Usage-based pricing means OpenAI earns more as developers succeed. Subscriptions add a steady baseline of revenue from non-developers. ## Build This with Dodo Payments You can build OpenAI's billing model with Dodo Payments. Use Credit-Based Billing for the API side and standard subscriptions for the ChatGPT Plus side. **1. Create a Fiat Credit Entitlement** In your Dodo Payments dashboard, go to **Products → Credits** and click **Create Credit**. This credit is the central balance for each user. * **Credit Type:** Fiat Credits, with **Unit Currency** set to USD * **Credit Expiry:** Custom, 365 days (matches OpenAI's one-year expiry), or Never * **Rollover:** Not needed (credits don't reset each cycle) * **Allow Overage:** Disabled Fiat credits use two decimal places, so one credit is one dollar and balances track cents. Dodo Payments doesn't block usage when a balance reaches zero. To make API calls fail at \$0 like OpenAI, check the balance in your application before each request (see **Handle Balance Depletion** below). **2. Create Top-Up Products** Create one-time payment products for different credit packs, such as \$5, \$10, \$50, and \$100. Attach your fiat credit to each product. Set the number of credits issued to the pack's dollar value. A \$50 pack issues 50 credits. ```typescript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_credit_pack_50', quantity: 1 } ], customer: { email: 'developer@example.com' }, return_url: 'https://yourapp.com/dashboard' }); ``` **3. Create Usage Meters** Create two meters to track token usage: * `llm.input_tokens`: Sum aggregation on the `tokens` property. * `llm.output_tokens`: Sum aggregation on the `tokens` property. On your usage-based product, toggle **Bill usage in Credits** on both meters and select the fiat credit. Then set **Meter units per credit** for each. ### Calculating Meter Units per Credit To match OpenAI's GPT-4o pricing, work out how many tokens cost \$1, which is one fiat credit: * **Input Tokens:** 1,000,000 tokens / \$2.50 = 400,000 tokens per \$1. * **Output Tokens:** 1,000,000 tokens / \$10.00 = 100,000 tokens per \$1. In the Dodo Payments dashboard, set **Meter units per credit** to 400,000 for input and 100,000 for output. Dodo Payments divides each meter's aggregated tokens by this value to get the credits to deduct. **4. Send Usage Events** After each LLM request, send the usage to Dodo Payments. One request can carry both the input and the output event. This snippet reuses the `client` from the previous step. ```typescript theme={null} // requestId and customerId come from your application's request context. await client.usageEvents.ingest({ events: [{ event_id: `req_${requestId}`, customer_id: customerId, event_name: 'llm.input_tokens', timestamp: new Date().toISOString(), metadata: { model: 'gpt-4o', tokens: 1500 } }, { event_id: `req_${requestId}_out`, customer_id: customerId, event_name: 'llm.output_tokens', timestamp: new Date().toISOString(), metadata: { model: 'gpt-4o', tokens: 800 } }] }); ``` **5. Handle Balance Depletion** Check the user's balance before you process an API request. If the balance is zero or negative, reject the request, for example with a `402` status. ```typescript theme={null} async function checkCreditsBeforeRequest(customerId: string) { const balance = await client.creditEntitlements.balances.retrieve(customerId, { credit_entitlement_id: 'cde_your_credit_entitlement_id', }); if (Number(balance.balance) <= 0) { throw new Error('Insufficient credits. Please top up your account.'); } } ``` ### Handling Low Balance Webhooks Notify users before they reach \$0. Set a **Low Balance Threshold** when you attach the credit, then send an email or in-app notification when the `credit.balance_low` webhook arrives. ```typescript theme={null} import DodoPayments from 'dodopayments'; import express from 'express'; const app = express(); app.use(express.raw({ type: 'application/json' })); const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, }); // sendLowBalanceEmail is your application's own function. app.post('/webhooks/dodo', async (req, res) => { try { const event = client.webhooks.unwrap(req.body.toString(), { headers: { 'webhook-id': req.headers['webhook-id'] as string, 'webhook-signature': req.headers['webhook-signature'] as string, 'webhook-timestamp': req.headers['webhook-timestamp'] as string, }, }); if (event.type === 'credit.balance_low') { const { customer_id, available_balance } = event.data; await sendLowBalanceEmail(customer_id, available_balance); } res.json({ received: true }); } catch (error) { res.status(401).json({ error: 'Invalid signature' }); } }); ``` > [!TIP] > > OpenAI offers auto recharge, which buys more credits when the balance falls below a threshold the user sets. **6. Build the ChatGPT Subscription Side (Optional)** To offer a subscription plan like ChatGPT Plus, create a separate subscription product in Dodo Payments. It doesn't need a credit entitlement. For a Team plan, use [seat-based billing](/features/seat-based-billing): a per-seat add-on whose quantity is the number of users. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_plus_subscription', quantity: 1 } ], customer: { email: 'user@example.com' }, return_url: 'https://yourapp.com/billing' }); ``` ### Implementing Soft Caps To build soft caps, track subscription users' usage with the same meters but without linking them to a credit. In your application, check the usage for the current billing period. ```typescript theme={null} // getUsageForCurrentPeriod and SOFT_CAP_THRESHOLD are defined in your application. async function checkSubscriptionUsage(customerId: string) { const usage = await getUsageForCurrentPeriod(customerId); if (usage > SOFT_CAP_THRESHOLD) { // Route to a smaller model instead of blocking return 'gpt-4o-mini'; } return 'gpt-4o'; } ``` ## Accelerate with the LLM Ingestion Blueprint The steps above build and send usage events by hand. The [LLM Ingestion Blueprint](/developer-resources/ingestion-blueprints/llm) instead wraps your OpenAI client and tracks tokens automatically. ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` ```typescript theme={null} import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import OpenAI from 'openai'; const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); const tracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: 'llm.chat_completion', }); // customerId and prompt come from your application. const trackedClient = tracker.wrap({ client: openai, customerId: customerId, }); // Every API call now automatically tracks token usage const response = await trackedClient.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: prompt }], }); // inputTokens, outputTokens, and totalTokens are sent automatically console.log('Tokens used:', response.usage); ``` The blueprint reads `inputTokens`, `outputTokens`, and `totalTokens` from every API response and sends them, with `model`, as event metadata. Set your meter's **Over Property** to the token key you want to bill. > [!TIP] > > The LLM Blueprint supports OpenAI, Anthropic, Groq, Google Gemini, OpenRouter, and the Vercel AI SDK. See the [full blueprint documentation](/developer-resources/ingestion-blueprints/llm) for provider-specific examples and advanced configuration. ## Implementing Spend-Based Rate Tiers OpenAI's rate tiers manage capacity by trust. To build them, track each customer's lifetime spend. 1. **Track Lifetime Spend:** Listen for `payment.succeeded` webhooks and add the payment amount to a `total_spend` field for that customer in your database. Amounts are in the smallest currency unit, so 5000 is \$50.00. 2. **Define Tiers:** Map spend amounts to rate limits: * Tier 1: \$0 - \$50 spend -> 3 RPM * Tier 2: \$50 - \$250 spend -> 10 RPM * Tier 3: \$250+ spend -> 50 RPM 3. **Enforce Limits:** In your API middleware, look up the customer's tier and apply its rate limit. ```typescript theme={null} // db and the TIER_*_LIMITS constants are defined in your application. async function getRateLimitForCustomer(customerId: string) { const customer = await db.customers.findUnique({ where: { id: customerId } }); const totalSpend = customer.total_spend; if (totalSpend >= 25000) return TIER_3_LIMITS; // $250.00 if (totalSpend >= 5000) return TIER_2_LIMITS; // $50.00 return TIER_1_LIMITS; } ``` ## Full Implementation Example: The API Proxy In production, an API proxy usually sits between your users and the LLM provider. The proxy authenticates the request, checks credits, and reports usage. ```mermaid theme={null} sequenceDiagram participant U as User participant P as Your API Proxy participant D as Dodo Payments participant O as OpenAI U->>P: API Request P->>D: Check Credit Balance D-->>P: Balance Available P->>O: Forward Request O-->>P: Response + Token Count P->>D: Ingest Usage Events D-->>P: Events Accepted P-->>U: Return Response ``` The handler below implements the proxy: ```typescript theme={null} import DodoPayments from 'dodopayments'; import OpenAI from 'openai'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); export async function handleApiRequest(req, res) { const { customerId, prompt, model } = req.body; try { // 1. Check credit balance const balance = await client.creditEntitlements.balances.retrieve(customerId, { credit_entitlement_id: 'cde_your_credit_entitlement_id', }); if (Number(balance.balance) <= 0) { return res.status(402).json({ error: 'Insufficient credits. Please top up.' }); } // 2. Call OpenAI const completion = await openai.chat.completions.create({ model: model, messages: [{ role: 'user', content: prompt }], }); const { prompt_tokens, completion_tokens } = completion.usage; // 3. Ingest usage events to Dodo await client.usageEvents.ingest({ events: [ { event_id: `req_${completion.id}_in`, customer_id: customerId, event_name: 'llm.input_tokens', timestamp: new Date().toISOString(), metadata: { model, tokens: prompt_tokens } }, { event_id: `req_${completion.id}_out`, customer_id: customerId, event_name: 'llm.output_tokens', timestamp: new Date().toISOString(), metadata: { model, tokens: completion_tokens } } ] }); // 4. Return response to user res.json(completion); } catch (error) { console.error('API Error:', error); res.status(500).json({ error: 'Internal server error' }); } } ``` ## Handling Edge Cases A billing system like OpenAI's has several edge cases to plan for. ### Race Conditions A user with a low balance can send several requests at once and exceed the balance before any event is processed. To prevent this, keep a small buffer, or hold a distributed lock on the customer's balance during each request. ### Event Ingestion Latency Dodo Payments deducts credits asynchronously. A background worker processes new events about once a minute, so a deduction can lag the API call. For strict real-time enforcement, keep a local cache of each user's balance and update it as you serve requests. ### Refund Handling Refunding a credit pack purchase doesn't remove the credits it granted. When you refund, deduct those credits yourself with a debit: use **Apply Credit/Debit** on the customer's **Credits** tab, or the [Create Ledger Entry](/api-reference/credit-entitlements/create-ledger-entry) API. Then update your application's view of the balance, so users can't spend credits they no longer have. ### Multi-Model Support To support several models with different prices, choose one of two options: 1. **Separate Meters:** Create one set of meters per model, for example `gpt-4o.input_tokens` and `gpt-4o-mini.input_tokens`, each with its own **Meter units per credit**. 2. **Weighted Events:** Use one meter and multiply `tokens` by a weight before sending the event. For example, if GPT-4o costs 10 times as much as GPT-4o-mini, send 10 times the tokens for GPT-4o requests. OpenAI publishes a separate rate for each model, and separate meters map to that structure most directly. ## Architecture Overview The loop below shows the prepaid flow from purchase to blocked calls: ```mermaid theme={null} flowchart LR A[Buy Credit Pack] --> B[Credits Added to Balance] B --> C[API Request] C --> D[Count Tokens] D --> E[Deduct Credits] E --> F{Balance > 0?} F -->|Yes| C F -->|No| G[Block API Calls] G --> A ``` The meters track tokens and deduct their dollar value from the user's credit balance at your configured rates. Your application blocks calls when the balance reaches zero. ## Conclusion With Dodo Payments, you can combine usage-based billing with the predictability of prepaid credits, as OpenAI does. Customers pay up front, spend as they go, and top up when they need more. The same pieces work for a large LLM platform or a small AI tool: a fiat credit, top-up products, token meters, and a balance check before each request. ## Key Dodo Features Used These Dodo Payments features power the implementation: > [card] [Credit-Based Billing](/features/credit-based-billing) > > Manage prepaid fiat credits and entitlements for your users. > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Track granular usage like tokens and bill for it. > [card] [One-Time Payments](/features/one-time-payment-products) > > Sell credit packs and top-ups through checkout. > [card] [Event Ingestion](/features/usage-based-billing/event-ingestion) > > Send high-volume usage data to Dodo Payments. > [card] [Webhooks](/developer-resources/webhooks/intents/credit) > > Stay updated on credit balance changes and low balance alerts. > [card] [LLM Ingestion Blueprint](/developer-resources/ingestion-blueprints/llm) > > Automatic token tracking for OpenAI and other LLM providers. # Replicate Billing Model Source: https://docs.dodopayments.com/developer-resources/billing-deconstructions/replicate Deconstruct Replicate's per-second hardware-specific billing and build the same pure usage-based model using Dodo Payments. Replicate is a platform for running open-source machine learning models in the cloud, and one of the purest examples of usage-based pricing in AI. There is no monthly subscription and no flat rate per model run. Most models are billed for the compute time they use, measured per second, at a rate that depends on the hardware. Some models are billed by input and output instead, such as per image or per token ([Replicate pricing](https://replicate.com/pricing)). Per-second billing suits AI workloads because run times are unpredictable. One user might run a lightweight model for a few seconds, and another a large generative model for several minutes. Because the price follows the compute used rather than the model, it stays transparent at any scale. ## How Replicate Bills Replicate's time-based pricing doesn't depend on the model. Whether you generate an image with SDXL or run Llama 3, the bill depends on the hardware tier and the run time. Replicate can host thousands of open-source models without a separate price for each. | Hardware | Price per Second | Price per Hour | | :- | :- | :- | | CPU | \$0.000100 | \$0.36 | | NVIDIA T4 GPU | \$0.000225 | \$0.81 | | NVIDIA L40S GPU | \$0.000975 | \$3.51 | | NVIDIA A100 (80GB) GPU | \$0.001400 | \$5.04 | | NVIDIA H100 GPU | \$0.001525 | \$5.49 | The implementation below also uses example meters for A40 and A100 (40GB) tiers, which Replicate's pricing page no longer lists. Create one meter for each hardware tier you offer. Each run is metered on the meter for the hardware it used: ```mermaid theme={null} flowchart TD A[Model Execution Completes] --> B[Measure Execution Time] B --> C{Which Hardware?} C -->|CPU| D[CPU Meter] C -->|T4 GPU| E[T4 GPU Meter] C -->|A40 GPU| F[A40 GPU Meter] C -->|A40 Large GPU| G[A40 Large GPU Meter] C -->|A100 40GB GPU| H[A100 40GB GPU Meter] C -->|A100 80GB GPU| I[A100 80GB GPU Meter] D --> J[Bill per Second at Tier Rate] E --> J F --> J G --> J H --> J I --> J ``` 1. **Hardware-Specific Rates**: The price per second depends on the compute resources used. Each hardware tier has its own rate. 2. **Pure Usage-Based Model**: There are no monthly fees, no included quotas, and no overages. Users pay for exact compute time, for example "12.4 seconds on an A100", not per generation. 3. **Per-Second Granularity**: Providers that bill by the hour or minute charge for unused time on short tasks. Per-second billing removes that waste for small experiments and large production workloads alike. > [!NOTE] > > For public models, Replicate charges only for the time a model is actively processing your request. Setup (cold boot) and idle time are free. Private models and deployments run on dedicated hardware, so you pay for all the time their instances are online: setup, idle, and active ([Replicate billing docs](https://replicate.com/docs/topics/billing)). ## What Makes It Unique * **Hardware-specific metering:** The same model costs more on faster hardware, so users trade speed against cost. A T4 GPU suits tasks that aren't time-sensitive, and an A100 suits real-time applications. * **Per-second granularity:** Billing is calculated to the second, so users don't pay for unused time on short tasks. * **No subscription:** Users start with no commitment, and cost scales with usage. This suits startups and developers trying different models. * **Model-agnostic:** The same billing logic applies to image generation, text processing, audio transcription, and video synthesis. The platform supports a large model catalog without complex pricing tables. ## Build This with Dodo Payments You can build this model with Dodo Payments usage-based billing. Create one meter per hardware tier and attach all of them to a single product. **1. Create Usage Meters (One Per Hardware Class)** Create a separate meter for each hardware tier. Each tier has its own price per second, so separate meters let Dodo Payments price each tier and itemize the invoice. | Meter Name | Event Name | Aggregation | Property | | :- | :- | :- | :- | | CPU Compute | `compute.cpu` | Sum | `execution_seconds` | | GPU T4 Compute | `compute.gpu_t4` | Sum | `execution_seconds` | | GPU A40 Compute | `compute.gpu_a40` | Sum | `execution_seconds` | | GPU A40 Large Compute | `compute.gpu_a40_large` | Sum | `execution_seconds` | | GPU A100 40GB Compute | `compute.gpu_a100_40` | Sum | `execution_seconds` | | GPU A100 80GB Compute | `compute.gpu_a100_80` | Sum | `execution_seconds` | **Sum** aggregation over `execution_seconds` gives the total compute time per hardware tier for the billing period. **2. Create a Usage-Based Product** Create a product in the Dodo Payments dashboard with these settings: * **Pricing type:** Usage Based Billing * **Base Price:** \$0/month (no subscription fee) * **Billing frequency:** Monthly Add every meter with its price per unit: | Meter | Price Per Unit (per second) | | :- | :- | | compute.cpu | \$0.000100 | | compute.gpu\_t4 | \$0.000225 | | compute.gpu\_a40 | \$0.000575 | | compute.gpu\_a40\_large | \$0.000725 | | compute.gpu\_a100\_40 | \$0.001150 | | compute.gpu\_a100\_80 | \$0.001400 | Set the **Free Threshold** to 0 on every meter, so every second of execution is billable. **3. Send Usage Events** Send a usage event to Dodo Payments when each model run completes. Give each prediction a unique `event_id`, so a retried event isn't counted twice. ```typescript theme={null} import DodoPayments from 'dodopayments'; type HardwareTier = 'cpu' | 'gpu_t4' | 'gpu_a40' | 'gpu_a40_large' | 'gpu_a100_40' | 'gpu_a100_80'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); async function trackModelExecution( customerId: string, modelId: string, hardware: HardwareTier, executionSeconds: number, predictionId: string ) { const eventName = `compute.${hardware}`; await client.usageEvents.ingest({ events: [{ event_id: `pred_${predictionId}`, customer_id: customerId, event_name: eventName, timestamp: new Date().toISOString(), metadata: { execution_seconds: executionSeconds, model_id: modelId, hardware: hardware } }] }); } // Example: SDXL image generation on A100 await trackModelExecution( 'cus_abc123', 'stability-ai/sdxl', 'gpu_a100_80', 8.3, // 8.3 seconds of A100 time 'pred_xyz789' ); ``` **4. Measure Execution Time Precisely** Time each model run with `performance.now()`, and round to the nearest tenth of a second for billing. ```typescript theme={null} // executeModel is your application's own function that runs the model. async function runModelWithMetering( customerId: string, modelId: string, hardware: HardwareTier, input: Record ) { const predictionId = `pred_${Date.now()}`; const startTime = performance.now(); try { const result = await executeModel(modelId, input, hardware); const executionSeconds = (performance.now() - startTime) / 1000; const billedSeconds = Math.round(executionSeconds * 10) / 10; await trackModelExecution( customerId, modelId, hardware, billedSeconds, predictionId ); return result; } catch (error) { // This example bills compute time for failed runs longer than 1 second. // Replicate doesn't charge for failed runs on public models; remove this block to match. const executionSeconds = (performance.now() - startTime) / 1000; if (executionSeconds > 1) { await trackModelExecution( customerId, modelId, hardware, Math.round(executionSeconds * 10) / 10, predictionId ); } throw error; } } ``` **5. Create Checkout** When a user signs up, create a checkout session for the usage-based product. Dodo Payments then bills the usage each cycle and issues the invoices. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_compute_payg', quantity: 1 } ], customer: { email: 'ml-engineer@example.com' }, return_url: 'https://yourplatform.com/dashboard' }); ``` ## Accelerate with the Time Range Ingestion Blueprint The [Time Range Ingestion Blueprint](/developer-resources/ingestion-blueprints/time-range) shortens per-second compute tracking. Create one ingestion instance per hardware tier, and call `trackTimeRange` after each run. ```bash theme={null} npm install @dodopayments/ingestion-blueprints ``` ```typescript theme={null} import { Ingestion, trackTimeRange } from '@dodopayments/ingestion-blueprints'; // Create one ingestion instance per hardware tier function createHardwareIngestion(hardware: string) { return new Ingestion({ apiKey: process.env.DODO_PAYMENTS_API_KEY, environment: 'live_mode', eventName: `compute.${hardware}`, }); } const ingestions: Record = { cpu: createHardwareIngestion('cpu'), gpu_t4: createHardwareIngestion('gpu_t4'), gpu_a40: createHardwareIngestion('gpu_a40'), gpu_a40_large: createHardwareIngestion('gpu_a40_large'), gpu_a100_40: createHardwareIngestion('gpu_a100_40'), gpu_a100_80: createHardwareIngestion('gpu_a100_80'), }; // executeModel, modelId, input, hardware, and customerId come from your application. const startTime = performance.now(); const result = await executeModel(modelId, input, hardware); const durationMs = performance.now() - startTime; await trackTimeRange(ingestions[hardware], { customerId: customerId, durationMs: durationMs, metadata: { model_id: modelId, hardware: hardware, }, }); ``` The blueprint builds and sends the event, with the duration as `durationMs` in the metadata. Set each meter's **Over Property** to `durationMs`, or send `durationSeconds` to keep per-second pricing. With one ingestion instance per hardware tier, this maps directly to Replicate's multi-tier metering. > [!TIP] > > For long-running jobs, combine the Time Range Blueprint with interval-based heartbeat tracking, shown in [Advanced: Heartbeat Metering](#advanced-heartbeat-metering). See the [full blueprint documentation](/developer-resources/ingestion-blueprints/time-range) for more patterns. ## Cost Estimation for Users Usage-based bills can be hard to predict, so show users a cost estimate before they run a model. Estimates prevent surprise bills and build trust. ### Example Cost Calculations | Model | Hardware | Avg Time | Cost Per Run | | :- | :- | :- | :- | | SDXL (image) | A100 80GB | \~8 sec | \~\$0.0112 | | Llama 3 (text) | A100 40GB | \~3 sec | \~\$0.0035 | | Whisper (audio) | GPU T4 | \~15 sec | \~\$0.0034 | ### Building a Cost Calculator This function multiplies the tier's per-second rate by the estimated run time: ```typescript theme={null} function estimateCost(hardware: HardwareTier, estimatedSeconds: number): number { const rates: Record = { 'cpu': 0.000100, 'gpu_t4': 0.000225, 'gpu_a40': 0.000575, 'gpu_a40_large': 0.000725, 'gpu_a100_40': 0.001150, 'gpu_a100_80': 0.001400 }; return Number((rates[hardware] * estimatedSeconds).toFixed(4)); } // Show the user before running: "This will cost approximately $0.0119" const estimate = estimateCost('gpu_a100_80', 8.5); ``` ## Enterprise: Reserved Capacity For customers who need dedicated capacity and no cold boots, Replicate offers deployments: dedicated instances billed for all the time they're online. To model reserved capacity with Dodo Payments, sell it as a subscription product: * **Product Type:** Subscription * **Price:** Fixed monthly price (for example, "Reserved A100 Instance - \$500/month") * **Billing Cycle:** Monthly You can still send usage events for monitoring and analytics, while the subscription covers the cost. As a customer's volume grows, reserved capacity often costs less than pay-as-you-go. ## Advanced: Heartbeat Metering For tasks that run for minutes or hours, one event at the end is risky: if the process crashes, you lose the usage data. Instead, send a usage event every 30 to 60 seconds while the task runs. ```typescript theme={null} // executeLongTask is your application's own function. trackModelExecution is defined above. async function runLongTaskWithHeartbeat( customerId: string, modelId: string, hardware: HardwareTier ) { const predictionId = `pred_${Date.now()}`; let totalSeconds = 0; const heartbeatInterval = setInterval(async () => { try { await trackModelExecution( customerId, modelId, hardware, 30, `${predictionId}_${totalSeconds}` ); totalSeconds += 30; } catch (error) { console.error('Heartbeat tracking failed:', error, { predictionId, totalSeconds }); } }, 30000); try { await executeLongTask(); } finally { clearInterval(heartbeatInterval); } } ``` ## Key Dodo Features Used > [card] [Usage-Based Billing](/features/usage-based-billing/introduction) > > Set up products that bill based on consumption. > [card] [Meters](/features/usage-based-billing/meters) > > Define the metrics you want to track and bill for. > [card] [Event Ingestion](/features/usage-based-billing/event-ingestion) > > Send usage data to Dodo Payments as it happens. > [card] [Subscriptions](/features/subscription) > > Manage recurring billing for reserved capacity and enterprise plans. > [card] [Time Range Blueprint](/developer-resources/ingestion-blueprints/time-range) > > Per-second compute tracking with duration helpers. # Billing SDK Source: https://docs.dodopayments.com/developer-resources/billingsdk Add pricing tables, subscription management, and usage meters to your app, and generate Dodo Payments API routes with the open-source Billing SDK CLI. [Billing SDK | Dodo Payments](https://www.youtube.com/embed/32RVbEllEi0) Billing SDK is an open-source set of React billing components, with a CLI that connects your project to Dodo Payments. The CLI generates the API routes, React hook, and Dodo Payments client for your framework, and adds components such as pricing tables and usage meters. ## Overview Billing SDK includes: * **React Components**: Pre-built, customizable billing components for React applications. * **CLI Tooling**: A command-line interface that initializes projects and adds components. * **Framework Support**: Templates for Next.js, Express.js, Hono, Fastify, NestJS, and React. * **Payment Provider**: Full integration with Dodo Payments. ## Quick Start To set up Billing SDK in an existing project, run the CLI from the project root: **1. Install the CLI** Run the CLI with `npx`, without installing it: ```bash theme={null} npx @billingsdk/cli --help ``` Or install it globally for frequent use. The global install adds the `billingsdk` command, for example `billingsdk init`: ```bash theme={null} npm install -g @billingsdk/cli ``` **2. Initialize a Project** Run the interactive setup to add billing to your project: ```bash theme={null} npx @billingsdk/cli init ``` The CLI prompts you to select: * Your framework: Next.js, Express.js, React, Hono, Fastify, or NestJS. The CLI detects your framework and marks it as detected. * Your payment provider: select **Dodo Payments**. **3. Add Components** Add individual billing components to your project: ```bash theme={null} npx @billingsdk/cli add pricing-table-one npx @billingsdk/cli add subscription-management ``` ## Supported Frameworks Billing SDK has a Dodo Payments template for each of these frameworks: | Framework | Dodo Payments | | - | - | | Next.js | Yes | | Express.js | Yes | | Hono | Yes | | React | Yes | | Fastify | Yes | | NestJS | Yes | ## CLI Commands ### `@billingsdk/cli init` `init` sets up billing in your project: it installs the framework template with the Dodo Payments integration, and the dependencies that the template needs. **What it does:** 1. **Framework Selection**: You choose your framework and payment provider. 2. **Template Installation**: The CLI downloads the template for your framework and provider from the Billing SDK registry, and installs its files. 3. **Dependency Management**: The CLI installs the template's dependencies, such as `dodopayments`, `standardwebhooks`, and `zod`, with npm, pnpm, Yarn, or Bun. 4. **File Generation**: The CLI writes the configuration files and boilerplate code. For Express.js, Fastify, Hono, and NestJS, it writes them under `src/`. **Example:** ```bash theme={null} npx @billingsdk/cli init ``` To run `init` without prompts, pass `--framework`, `--provider`, and `--yes`, for example `npx @billingsdk/cli init --framework nextjs --provider dodopayments --yes`. Add `--dry-run` to list the files without writing them, `--no-install` to skip the dependency install, or `--package-manager` to choose `npm`, `pnpm`, `yarn`, or `bun`. ### `@billingsdk/cli add` `add` installs one billing component in your project through the shadcn/ui registry system. It runs `shadcn@latest add @billingsdk/` with your package manager's runner. **Examples:** ```bash theme={null} # Add a pricing table npx @billingsdk/cli add pricing-table-one # Add subscription management npx @billingsdk/cli add subscription-management # Add usage monitoring npx @billingsdk/cli add usage-meter-circle ``` **What happens:** 1. The `shadcn` CLI downloads the component configuration from the registry. 2. It installs the component files in your `components/billingsdk/` directory. 3. It updates your project configuration if needed. 4. It installs any additional dependencies. ## Generated Files Structure After you run `init`, your project contains: * **API Routes**: Endpoints for checkout, customers, customer payments, products, subscriptions, and webhooks. The React template has no API routes. * **Hooks**: A `useBilling` React hook for billing operations, for React and Next.js. * **Library Files**: The Dodo Payments client setup and helper functions, in `lib/dodopayments.ts`. * **Environment Configuration**: An example environment file, `.env.example`. ### Next.js Example Structure For Next.js, `init` writes these files: ```text theme={null} your-project/ ├── app/api/ │ ├── checkout/route.ts │ ├── customer/route.ts │ ├── customer/payments/route.ts │ ├── customer/subscriptions/route.ts │ ├── product/route.ts │ ├── products/route.ts │ └── webhook/route.ts ├── hooks/ │ └── useBilling.ts ├── lib/ │ └── dodopayments.ts └── .env.example ``` ## Environment Configuration After initialization, set your environment variables. Get the API key from **Developer → API Keys** and the webhook key from **Developer → Webhooks** in the dashboard: ```bash theme={null} # DodoPayments DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_key_here # App URL NEXT_PUBLIC_APP_URL=http://localhost:3000 ``` Set `DODO_PAYMENTS_ENVIRONMENT` to `test_mode` or `live_mode`. The generated Dodo Payments client throws an error for any other value. > [!WARNING] > > Store your API keys in environment variables. Never commit them to version control. ## Available Components Billing SDK provides React components in these groups: * **Pricing Tables**: Eight variants, `pricing-table-one` through `pricing-table-eight`, for displaying product pricing. * **Subscription Management**: `subscription-management`, plus cards and dialogs to cancel a subscription or update a plan. * **Usage Monitoring**: Circular and linear usage meters, and usage tables for usage-based billing. * **Checkout Components**: A payment method selector, payment details forms, and a payment failure card. * **Customer Portal**: Billing settings, a billing screen, invoice history, and upcoming charges, for customer self-service. To browse every component with a live preview, see the [component library](https://billingsdk.com/docs/components). ## Open Source Billing SDK is open source: * **Transparency**: You can read how every component works. * **Community**: Developers build it for other developers. * **Security**: Anyone can review the code for security issues. * **Innovation**: Community contributions speed up development. > [!NOTE] > > Billing SDK is released under the GNU General Public License v3.0 (GPL-3.0), which keeps the project open and free. ## Getting Help For help with Billing SDK, use these resources: * **GitHub Issues**: [Open an issue](https://github.com/dodopayments/billingsdk/issues) * **Documentation**: Visit [billingsdk.com/docs](https://billingsdk.com/docs) * **LLMs Full Documentation**: [billingsdk.com/llms-full.txt](https://billingsdk.com/llms-full.txt) ## Contributing Billing SDK welcomes contributions. The [contribution guide](https://billingsdk.com/docs/contribution-open-source) explains how to: * Report bugs * Request features * Submit pull requests * Add new components * Improve documentation ## Learn More > [card] [Full Documentation](https://billingsdk.com/docs) > > Complete guide to Billing SDK with examples and best practices > [card] [CLI Reference](https://billingsdk.com/docs/cli) > > Detailed CLI documentation for all commands and options > [card] [Component Library](https://billingsdk.com/docs/components) > > Browse all available components with live examples # Build an AI Chat App with AI SDK & LLM Blueprint Source: https://docs.dodopayments.com/developer-resources/build-an-ai-chat-app-with-usage-based-billing Build an AI chat app with the AI SDK and Google Gemini. The LLM Blueprint tracks token usage, and Dodo Payments bills customers for the tokens they use. > [!TIP] > > To have your coding agent write the integration, install the [Dodo Agent Plugin](/developer-resources/build-with-ai-coding-agents). It adds the Dodo Payments skills and MCP servers to Claude Code, Codex CLI, Cursor, VS Code / GitHub Copilot, Kiro, and OpenCode. You'll build an **AI chat application** that bills customers for the tokens they use. You create the billing meter, the product, and the application code that runs conversations and reports token usage as it happens. > [!NOTE] > > This tutorial builds a complete application with a backend and a frontend. The chat app uses Google Gemini, and the LLM Blueprint reports token usage for each response, so you don't count tokens yourself. When you finish, you'll have a chat application that: * Runs AI conversations with Google Gemini through the AI SDK. * Tracks token usage automatically, with no counting code. * Charges customers for the tokens they actually use. * Includes a chat interface that keeps the conversation history. ![Chat interface of the finished AI chat app, showing a conversation with token counts under each response](https://mintcdn.com/dodopayments/oig3NPG69DDpua_S/images/cookbooks/ai-chat-app/ai-chat-demo.png?fit=max\&auto=format\&n=oig3NPG69DDpua_S\&q=85\&s=9d9932fb528b64632cfbedaad98c09f3) ## What We're Building The chat service works like this: * **Service**: AI chat with Google Gemini through the AI SDK * **Pricing Model**: Pay per token (\$0.01 per 1,000 tokens) * **Free Tier**: 10,000 free tokens per customer per month * **Features**: Conversation history and automatic token tracking Before you start, you need: * A Dodo Payments account. * A Google AI API key. [Get one from Google AI Studio](https://aistudio.google.com/api-keys). * Node.js 22 or later. *** ## Step 1: Create Your Usage Meter Create a meter in the Dodo Payments dashboard to track AI token usage. > [!TIP] > > **What you're building**: A meter named "AI Token Usage Meter" that adds up the tokens used in chat conversations. **1. Open the Meters Section** 1. Log in to the Dodo Payments dashboard. 2. Click **Products** in the sidebar. 3. Click **Meters**. 4. Click **Create Meter**. ![Meters page in the Dodo Payments dashboard with the Create Meter button](https://mintcdn.com/dodopayments/oig3NPG69DDpua_S/images/cookbooks/ai-chat-app/create-meter.png?fit=max\&auto=format\&n=oig3NPG69DDpua_S\&q=85\&s=e5aa342d55a4a9c7323cf68015f737e4) The meter form opens. **2. Enter the Meter Details** Enter the details for the chat service: **Meter Name** → `AI Token Usage Meter` **Description** → `Tracks token consumption from AI chat conversations using AI SDK` **Event Name** → `ai_chat_usage` > [!WARNING] > > The event name `ai_chat_usage` must match the event name the application code sends. Event names are case-sensitive. **3. Configure How Tokens Are Counted** Set the aggregation, which controls how the meter combines events: **Aggregation Type**: **Sum** **Over Property**: `totalTokens` **Measurement Unit**: `tokens` > [!NOTE] > > **Sum** adds up the tokens from every chat message. The LLM Blueprint sends `inputTokens`, `outputTokens`, and `totalTokens` in each event's metadata, and this meter sums `totalTokens`. **4. Create the Meter** 1. Check that every setting matches the values above. After you create a meter, you can't change its event name, aggregation, or filter. 2. Click **Create Meter**. ![Meter form filled in with the AI Token Usage Meter name, the ai\_chat\_usage event, and Sum aggregation](https://mintcdn.com/dodopayments/4L3_sb2jJa5trJWD/images/cookbooks/ai-chat-app/meter-configuration.png?fit=max\&auto=format\&n=4L3_sb2jJa5trJWD\&q=85\&s=c5b4f56326b6825847c9fc7666056102) > [!TIP] > > **Meter created.** The "AI Token Usage Meter" is ready to count tokens. Next, connect it to a billing product. ## Step 2: Get Your API Keys Collect the two API keys the app needs. **1. Get a Dodo Payments API Key** 1. In the Dodo Payments dashboard, go to **Developer → API Keys**. 2. Click **Create New Key**. 3. Enter a **Key Name**, then use **Select all** and choose **Write**. 4. Click **Create Key**. 5. Copy the API key. > [!NOTE] > > Create the key in test mode: a test mode key works only with test mode. You add the key to the `.env` file in Step 5. **2. Get a Google AI API Key** 1. Go to [aistudio.google.com](https://aistudio.google.com/api-keys). 2. Click **Get API Key**. 3. Create an API key or use an existing one. 4. Copy the key. > [!NOTE] > > Keep this key private. You add it to the `.env` file in Step 5. *** ## Step 3: Create Your Billing Product Create a product that defines the pricing: \$0.01 per 1,000 tokens, with 10,000 free tokens. The product connects the meter to billing. > [!TIP] > > **What you're building**: A product called "AI Chat Service" that charges for token usage above a free tier. **1. Navigate to Products** 1. In the Dodo Payments dashboard, click **Products** in the sidebar. 2. Click **Add Product**. 3. Under **Pricing Type**, select **Usage Based Billing**. With this pricing type, Dodo Payments bills from meter usage instead of a fixed subscription price. **2. Enter Product Details** Fill in the required details: **Product Name**: → `AI Chat Service` **Description**: → `AI-powered chat service with automatic token-based billing` **Product Image**: Upload a relevant image. > [!NOTE] > > The name and description appear on customer invoices. **3. Connect Your Meter** Check that the product's pricing type is **Usage Based Billing**. Set the **Price** to `0`, so customers pay only for usage, with no base fee. Then link the meter you created: 1. Scroll to the **Associated Meters** section. 2. Click **Add meters**. 3. Select **"AI Token Usage Meter"** from the dropdown. 4. Confirm that the meter appears in the product configuration. > [!TIP] > > The meter is connected to the product. **4. Set Your Pricing** Define the per-token price and the free tier: **Price per unit**: → `0.00001`. That's \$0.00001 per token, or \$0.01 per 1,000 tokens. **Free Threshold**: → `10000`. Each customer gets 10,000 free tokens per month. ![Meter pricing on the AI Chat Service product, with price per unit and free threshold filled in](https://mintcdn.com/dodopayments/4L3_sb2jJa5trJWD/images/cookbooks/ai-chat-app/product-pricing.png?fit=max\&auto=format\&n=4L3_sb2jJa5trJWD\&q=85\&s=e92dcb98316e970c1b921e0572f10b43) > [!TIP] > > **How billing works**: A customer who uses 25,000 tokens in a month pays for 15,000 tokens (25,000 − 10,000 free). 15,000 × \$0.00001 = \$0.15. **5. Save Your Product** 1. Review the settings: * Name: AI Chat Service * Meter: AI Token Usage Meter * Price: \$0.01 per 1,000 tokens * Free tier: 10,000 tokens 2. Click **Save Changes**. > [!TIP] > > **Product created.** Billing is configured, and customers are charged for the tokens they use. ## Step 4: Make a Test Purchase Create a test customer by buying the product. The app sends usage events for this customer. **1. Get Your Payment Link** 1. In the Dodo Payments dashboard, go to **Products**. 2. Find the "AI Chat Service" product. 3. Click **Share** next to the product. 4. Copy the payment link. **2. Complete a Test Purchase** 1. Open the payment link in a new browser tab. 2. Enter [test payment details](/miscellaneous/testing-process) and complete the purchase. > [!TIP] > > After the payment succeeds, the purchase creates a customer. The application code uses that customer's ID. **3. Find Your Customer ID** 1. Go back to the Dodo Payments dashboard. 2. Go to **Sales → Customers** in the sidebar. 3. Find the customer you created, by its test email address. 4. Copy the customer ID. It starts with `cus_`. > [!NOTE] > > Save this customer ID. You use it when you test the chat application. ## Step 5: Build the Chat Application With billing set up and a test customer created, build the chat application. **1. Set Up Your Project** Create a directory and initialize the project: ```bash theme={null} mkdir ai-chat-app cd ai-chat-app npm init -y ``` **2. Install Dependencies** Install the packages: ```bash theme={null} npm install express ai@5 @ai-sdk/google@2 @dodopayments/ingestion-blueprints dotenv npm install --save-dev typescript @types/express @types/node tsx ``` **3. Configure TypeScript** Create `tsconfig.json`: ```json tsconfig.json theme={null} { "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "node", "esModuleInterop": true, "strict": true, "skipLibCheck": true, "outDir": "./dist", "rootDir": "./src" }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` Update `package.json` to add the module type and scripts: ```json package.json theme={null} { "type": "module", "scripts": { "dev": "tsx src/server.ts", "build": "tsc", "start": "node dist/server.js" } } ``` **4. Create the Project Structure** Create the source and static-file folders: ```bash theme={null} mkdir src public ``` **5. Set Up Environment Variables** Create a `.env` file in the project root: ```bash .env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_ENVIRONMENT=test_mode GOOGLE_GENERATIVE_AI_API_KEY=your_google_api_key_here PORT=3000 ``` Replace the placeholder values with the API keys from Step 2. The Google provider for the AI SDK reads `GOOGLE_GENERATIVE_AI_API_KEY` by default. **6. Create the Backend Server** Create `src/server.ts` and paste in the server code below. The complete chat server with billing, plus the matching `.env` and `package.json`: ```typescript src/server.ts expandable theme={null} import express, { Request, Response } from 'express'; import { generateText } from 'ai'; import { google } from '@ai-sdk/google'; import { createLLMTracker } from '@dodopayments/ingestion-blueprints'; import 'dotenv/config'; const app = express(); app.use(express.json()); app.use(express.static('public')); // Replace with your test customer ID const CUSTOMER_ID = 'cus_123'; // Create tracker once with your meter event name const llmTracker = createLLMTracker({ apiKey: process.env.DODO_PAYMENTS_API_KEY!, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as 'test_mode' | 'live_mode', eventName: 'ai_chat_usage', // Must match your meter configuration }); // Chat endpoint with conversation support app.post('/chat', async (req: Request, res: Response) => { try { const { messages } = req.body; if (!messages || !Array.isArray(messages)) { return res.status(400).json({ error: 'Missing required field: messages (array)' }); } // Wrap AI SDK with automatic token tracking const trackedClient = llmTracker.wrap({ client: { generateText }, customerId: CUSTOMER_ID }); // Generate AI response - tokens are automatically tracked! const response = await trackedClient.generateText({ model: google('gemini-2.5-flash'), messages: messages }); res.json({ message: response.text, usage: { totalTokens: response.usage.totalTokens } }); } catch (error: any) { console.error('Chat error:', error); res.status(500).json({ error: 'Failed to process chat', details: error.message }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`🚀 Server running at http://localhost:${PORT}`); console.log(`📊 Tracking event: ai_chat_usage`); console.log(`👤 Customer ID: ${CUSTOMER_ID}`); console.log(`🔧 Environment: ${process.env.DODO_PAYMENTS_ENVIRONMENT}`); }); ``` ```bash .env theme={null} # Add your API keys here DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_ENVIRONMENT=test_mode GOOGLE_GENERATIVE_AI_API_KEY=your_google_api_key_here PORT=3000 ``` ```json package.json expandable theme={null} { "name": "ai-chat-app", "version": "1.0.0", "type": "module", "scripts": { "dev": "tsx src/server.ts", "build": "tsc", "start": "node dist/server.js" }, "dependencies": { "express": "^4.18.2", "ai": "^5.0.51", "@ai-sdk/google": "^2.0.16", "@dodopayments/ingestion-blueprints": "latest", "dotenv": "^16.0.3" }, "devDependencies": { "typescript": "^5.0.0", "@types/express": "^4.17.17", "@types/node": "^20.0.0", "tsx": "^3.12.7" } } ``` *** ## Step 6: Add the Chat Interface Add a chat interface that keeps the full conversation history. Create `public/index.html`: ```html public/index.html expandable theme={null} AI Chat with Usage Billing

🤖 AI Chat Assistant

Powered by AI-SDK & Dodo Payments

💬

Start a Conversation

Ask me anything! Your token usage is automatically tracked.

``` *** ## Step 7: Test Your Chat Application Test the chat app end to end and watch the usage reach Dodo Payments. > [!TIP] > > **What you're testing**: You chat with the AI, confirm that the token events reach Dodo Payments, and check the billing calculation. **1. Start the Server** 1. Check that the `.env` file has both API keys from Step 2. 2. Start the development server: ```bash theme={null} npm run dev ``` The server logs: ```text theme={null} 🚀 Server running at http://localhost:3000 📊 Tracking event: ai_chat_usage 👤 Customer ID: {YOUR CUSTOMER_ID} 🔧 Environment: test_mode ``` > [!TIP] > > The server is running. **2. Open the Chat Interface** 1. Open your browser. 2. Go to `http://localhost:3000`. The chat interface loads. > [!NOTE] > > Before you chat, set `CUSTOMER_ID` in `server.ts` to the test customer ID from Step 4, then restart the server. **3. Have Your First Conversation** Send these messages: 1. **"What is artificial intelligence?"** 2. **"How does machine learning work?"** 3. **"Can you explain neural networks?"** Each response shows the number of tokens it used. > [!TIP] > > If the AI responds and token counts appear, the app works. **4. Check Your Dodo Payments Dashboard** Confirm that Dodo Payments receives the events: 1. Open the Dodo Payments dashboard. 2. Go to **Products → Meters** and open **AI Token Usage Meter**. 3. Select the **Events** tab. 4. Find your chat events in the list. **What to look for:** * Event name: `ai_chat_usage` * Customer ID: your test customer ID ![Events tab of the AI Token Usage Meter listing ai\_chat\_usage events](https://mintcdn.com/dodopayments/4L3_sb2jJa5trJWD/images/cookbooks/ai-chat-app/meter-event.png?fit=max\&auto=format\&n=4L3_sb2jJa5trJWD\&q=85\&s=041f2bd60ce174a0e67f051e206d25b0) > [!TIP] > > The list has one event for each message you sent. **5. Verify Token Counting** Send a few more messages, then check the aggregation: 1. In the meter, select the **Customers** tab. 2. Find your test customer. 3. Check the **Consumed Units** column. It shows the total tokens used. ![Customers tab of the meter showing consumed units for the test customer](https://mintcdn.com/dodopayments/oig3NPG69DDpua_S/images/cookbooks/ai-chat-app/aggregation.png?fit=max\&auto=format\&n=oig3NPG69DDpua_S\&q=85\&s=58fa883c91fae2d4e7d59e266ca8913b) > [!NOTE] > > The meter sums the `totalTokens` value from every event. **6. Test the Free Tier** Use enough tokens to pass the free tier: 1. Have several more conversations, until the total passes about 15,000 tokens. 2. Open the meter's **Customers** tab again. 3. Check the values: * Consumed Units: 15,000+ tokens * Chargeable Units: 5,000 (10,000 free tokens applied) * Total Price: \~\$0.05 ![Customers tab of the meter showing consumed units, chargeable units, and total price after the free tier](https://mintcdn.com/dodopayments/oig3NPG69DDpua_S/images/cookbooks/ai-chat-app/free-tier-test.png?fit=max\&auto=format\&n=oig3NPG69DDpua_S\&q=85\&s=5ffc1f234acfbaaa2ab0c34805812785) > [!TIP] > > **Usage-based billing works.** Customers are charged for the tokens they use. *** ## Troubleshooting Common problems and their fixes: > [accordion] Events not appearing in dashboard > > **Possible causes:** > > * Event name doesn't match meter configuration exactly > * Customer ID doesn't exist in your account > * API key is invalid or expired > * Network connectivity issues > > **Solutions:** > > 1. Check that the event name matches the meter exactly. It's case-sensitive: `ai_chat_usage`. > 2. Check that the customer ID exists in the Dodo Payments dashboard. > 3. Test the API key with a simple API call. > 4. Check the server logs for errors. > [accordion] Token counts showing zero > > **Possible causes:** > > * Model not returning usage information > * Incorrect SDK version > > **Solutions:** > > 1. Check whether the model returns usage: > > ```typescript theme={null} > const response = await generateText({ model: google('gemini-2.5-flash'), prompt: 'Hello' }); > console.log('Usage:', response.usage); > ``` > > 2. Update the Blueprints package: `npm install @dodopayments/ingestion-blueprints@latest` > [accordion] API key invalid error > > **Possible causes:** > > * The API key belongs to the other mode. > * The `.env` file has extra spaces or quotes. > > **Solutions:** > > * A key works only in the mode it was created in. Use a test mode key with `DODO_PAYMENTS_ENVIRONMENT=test_mode`, and a live mode key with `live_mode`. > * Remove any quotes around keys in the `.env` file. > * Generate a new key if needed. Need help? * [Discord Community](https://discord.gg/bYqAp4ayYh) * [support@dodopayments.com](mailto:support@dodopayments.com) *** ## Congratulations! You Built an AI Chat App You have a working AI chat application that tracks token usage and bills customers for it through Dodo Payments. ### Learn More > [card] [LLM Blueprint](/developer-resources/ingestion-blueprints/llm) > > Track LLM token usage with the LLM Ingestion Blueprint. > [card] [Ingestion Blueprints SDK](https://github.com/dodopayments/ingestion-blueprints) > > More examples in the GitHub repository. > [card] [Join Community](https://discord.gg/bYqAp4ayYh) > > Get help and share your projects on Discord. # Build an App Source: https://docs.dodopayments.com/developer-resources/build-an-app Build an app for the Dodo Payments App Marketplace. Create the app, run the OAuth authorization code flow with PKCE, call the API for each installed business, receive webhooks, and submit the app for review. ## Overview An app is a program that a merchant installs into their Dodo Payments business. After the merchant approves the scopes that the app requests, the app calls the Dodo Payments API for that business and receives webhooks about it. This guide shows how to: * Create an app and get its credentials. * Run the OAuth authorization code flow with PKCE. * Keep tokens fresh. * Receive and verify webhooks. * Submit the app for review and list it publicly. > [!NOTE] > > The App Marketplace is available only to businesses that have the `app_marketplace` feature enabled. Testers need the feature enabled too. ## Create an App **1. Open the Apps Page** In the dashboard, open **Apps**, then the **Created** tab, and select **Create app**. **2. Fill In the App Details** Set the app name, the redirect URIs, the scopes the app needs, and the events it subscribes to. Write a short reason for each scope. The merchant reads these reasons on the consent screen. **3. Copy the Credentials** Copy the client ID and the client secret (it starts with `dodo_cs_`). The dashboard shows the secret one time. Redirect URIs must use HTTPS, must match exactly, and are limited to 10 per app. A public app cannot use a loopback address or a private IP address. > [!WARNING] > > If you rotate the client secret, the old secret stops working immediately. Update your servers before you rotate. ## Live and Test Installs Live and test installs are separate. A merchant installs your app once in live mode and once in test mode. Each install has its own tokens, its own scopes, and its own webhooks. Set `resource` to `https://test.dodopayments.com` for a test install or `https://live.dodopayments.com` for a live install. The API host for the install is the same URL. The examples on this page use the test host. For a live install, use the live host. Every authorization request must include one `resource`. A request with no `resource` fails with `invalid_target`. ## Authorize a Business The app uses the OAuth 2.0 authorization code flow with PKCE (`S256`) and the client secret. The authorization server is `https://auth.dodopayments.com`. **1. Create a PKCE Pair** Create a random `code_verifier`. Compute `code_challenge` as the Base64URL-encoded SHA-256 hash of the verifier. **2. Send the Merchant to the Authorize Endpoint** ```text theme={null} https://auth.dodopayments.com/oauth2/authorize ?response_type=code &client_id=YOUR_CLIENT_ID &redirect_uri=https%3A%2F%2Fapp.example.com%2Fcallback &scope=payments%3Aread%20customers%3Aread &resource=https%3A%2F%2Ftest.dodopayments.com &code_challenge=CODE_CHALLENGE &code_challenge_method=S256 &state=RANDOM_STATE ``` The merchant signs in. An owner or an admin of the business approves all scopes or none. The merchant sees the reason that you wrote for each scope. **3. Receive the Code** Dodo Payments redirects to your `redirect_uri` with `code` and `state`. Check that `state` matches the value that you sent. **4. Exchange the Code for Tokens** Send the client ID and secret with HTTP Basic authentication. ```bash theme={null} curl https://auth.dodopayments.com/oauth2/token \ -u "$CLIENT_ID:$CLIENT_SECRET" \ -d grant_type=authorization_code \ -d code="$CODE" \ -d redirect_uri="https://app.example.com/callback" \ -d code_verifier="$CODE_VERIFIER" ``` The response holds `access_token`, `refresh_token`, `expires_in`, and `scope`. **5. Call the API** ```bash theme={null} curl https://test.dodopayments.com/payments \ -H "Authorization: Bearer $ACCESS_TOKEN" ``` A token works only for its own business and its own mode, and only for the granted scopes. A call outside the granted scopes returns `403`. > [!NOTE] > > Activation is asynchronous. Your app can receive the authorization code and call the API before the install is `active`, and before the `app.installed` webhook arrives. Do not wait for `app.installed` to start the token exchange. Use it to record the install. ### Token Lifetimes | Token | Lifetime | | - | - | | Access token | 1 hour | | Refresh token | 365 days, rolling. Each refresh gives a new refresh token. | Refresh with the same Basic authentication: ```bash theme={null} curl https://auth.dodopayments.com/oauth2/token \ -u "$CLIENT_ID:$CLIENT_SECRET" \ -d grant_type=refresh_token \ -d refresh_token="$REFRESH_TOKEN" \ -d resource="https://test.dodopayments.com" ``` Store the new refresh token and discard the old one. If you use an old refresh token a second time, Dodo Payments revokes the grant, and the install receives `app.uninstalled`. ### Uninstall and Revocation A merchant owner or admin can uninstall the app at any time. The install stays active if the person who installed it leaves the business. Revocation takes effect within 2 minutes. During that time, a token that was revoked can still work. After that time, the API returns `401`. You can also revoke a token yourself at `https://auth.dodopayments.com/oauth2/revoke`. ## Scopes A scope has the form `resource:read` or `resource:write`, for example `payments:read` or `refunds:write`. The dashboard lists the scopes that you can assign when you create the app. Scopes that give access to money movement or customer data get extra attention in review. Request only the scopes that the app uses. If you add a scope later, existing installs keep their old scopes and the merchant sees a banner to approve the new scopes. Calls that need the new scope fail until the merchant approves. ## Webhooks An app has one webhook endpoint for live installs (`webhook_url`) and one for test installs (`webhook_url_test`). Test events are sent only if you set `webhook_url_test`. Without it, the app page shows a warning. ### Which Events an App Receives An app receives an event only if both of these are true: 1. The app subscribed to the event type. 2. The install granted the read scope of the resource that the event describes. | Event family | Required scope | | - | - | | `payment.*` | `payments:read` | | `refund.*` | `refunds:read` | | `dispute.*` | `disputes:read` | | `subscription.*` | `subscriptions:read` | | `customer.*` | `customers:read` | | `license_key.*` | `license_keys:read` | The dashboard shows the full list for each scope when you choose events. The app always receives these events for its own installs, with no scope check: `app.installed`, `app.installation.updated`, and `app.uninstalled`. > [!WARNING] > > `payment.*` events need only `payments:read`, and they carry the full payload, including the customer name and email. The consent screen tells the merchant that payment access includes customer contact data. Handle this data under your privacy policy. ### Payload Every webhook has these fields at the top level: ```json theme={null} { "livemode": true, "business_id": "bus_123", "installation_id": "ains_123", "app_id": "app_123", "type": "payment.succeeded", "data": {} } ``` | Field | Meaning | | - | - | | `livemode` | `true` for a live install, `false` for a test install | | `business_id` | The business that installed the app | | `installation_id` | The install that the event belongs to | | `app_id` | Your app | | `type` | The event type | | `data` | The event data. It has the same shape as the merchant webhook for that event. | ### Verify the Signature Dodo Payments signs each message with Svix. Verify the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers against the raw request body, with the signing secret of your endpoint. The app webhook uses the same Svix headers and verification steps as a merchant webhook. See [Webhooks](/developer-resources/webhooks) for code examples in each language. To get the signing secret, open your app under **Apps → Created**. The **Webhook signing secret** card shows the secret for the current mode, so switch modes to get the live and the test secret. Set the webhook URL for a mode before you read its secret. Only the business that owns the app can see the secret. To replace the secret, click **Rotate secret**. The old secret stays valid for 24 hours, so update your server within that time. > [!TIP] > > The **Connect your app** card on the same page lists the authorization URL, the token URL, the API base URL of the current mode (also the `resource` value), and the requested scopes, with copyable examples of each request. Return a `2xx` response quickly. Use `webhook-id` to ignore a message that you already processed. ## Privacy Webhooks An app that has `customers` scopes must handle three privacy events before it can be listed publicly: * `customer.data_request` * `customer.redact` * `business.redact` Dodo Payments sends each event to your `webhook_url`, with the same payload fields as other app webhooks. When you receive one, delete or anonymize the data that the event names, then return a `2xx` response. Finish each request within 30 days. `business.redact` is sent 48 hours after the app is uninstalled. It is not sent if the business installs the app again in the same mode within those 48 hours. ## Review and Listing A private app can be installed by its own business only. To list an app publicly, select **Make public** and submit it for review. * The review target is 5 business days. * Reviewers check the test credentials, redirect URIs, scopes and their reasons, the privacy policy and support URLs, the name and icon, and that your webhook endpoint returns `2xx` for a test event. * If a reviewer rejects the app, you see the reason. Fix the issues and submit again. * A reviewer can suspend an app. A suspended app is hidden, its tokens are revoked, and its webhooks stop. ### Change a Live App When you edit a live app, the change goes to review. The live version, with its approved scopes, redirect URIs, and events, stays active until the change is approved. A rejected change does not affect the live version. > [!NOTE] > > You cannot test a pending redirect URI. The authorization server uses the approved redirect URIs only. To test a new redirect URI, use a separate private app. ### Test Before You List Use the test link on the app page to let up to 25 other businesses install a private app or an app in review. Testers need the `app_marketplace` feature enabled. The app shows a **Test app** badge to them. If you rotate the test link, new businesses cannot join with the old link, and businesses that already joined stay testers. The app page lists each tester business by name, and you can remove a tester there. ## Rate Limits Each pair of app and business is limited to 20 requests each second and 120 requests each minute. A call over the limit returns `429`. Retry with a back-off. ## Next Steps > [card] [Webhooks](/developer-resources/webhooks) > > Signature verification and retries. > [card] [API reference](/api-reference/introduction) > > All endpoints that an app can call. # Bun Adaptor Source: https://docs.dodopayments.com/developer-resources/bun-adaptor Add Dodo Payments checkout, Customer Portal, and webhook handlers to a Bun server built with Bun.serve() using the @dodopayments/bun package. The `@dodopayments/bun` package gives your Bun server three request handlers. `Checkout` returns checkout URLs, `CustomerPortal` sends a customer to the Customer Portal, and `Webhooks` verifies webhook events and routes them to your code. Each handler takes a standard `Request` and returns a `Response`, so you call it from the `fetch` handler of `Bun.serve()`. > [card] [Checkout Handler](#checkout-route-handler) > > Create checkout URLs with static and checkout session flows. > [card] [Customer Portal](#customer-portal-route-handler) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-route-handler) > > Receive and process Dodo Payments webhook events. ## Installation **1. Install the Package** Run this command in your project root: ```bash theme={null} bun add @dodopayments/bun ``` The package also needs `zod` 3.25 or later, which it lists as a peer dependency. **2. Set Up Environment Variables** Create a `.env` file in your project root. Create the API key under **Developer → API Keys**. Add your webhook endpoint under **Developer → Webhooks**, and copy its **Signing secret** into `DODO_PAYMENTS_WEBHOOK_KEY`: ```env expandable theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret # test_mode or live_mode DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_RETURN_URL=https://yourdomain.com/checkout/success ``` Bun reads `.env` files automatically, so the examples read these values from `process.env`. `DODO_PAYMENTS_RETURN_URL` is where customers land after checkout. If you don't pass an environment, the handlers use `live_mode`. A test mode API key works only with `test_mode`. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## Route Handler Examples > [!NOTE] > > All examples use Bun's native server, `Bun.serve()`, and route requests by path and method in its `fetch` handler. > [tab] Checkout Handler > > > [!NOTE] > > > > Use this handler to add Dodo Payments checkout to your Bun server. The static handler serves `GET` requests. The session handler serves `POST` requests. > > ```typescript Bun Server Handler expandable theme={null} > import { Checkout } from '@dodopayments/bun'; > > const staticCheckoutHandler = Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > type: "static" > }); > > const sessionCheckoutHandler = Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > type: "session" > }); > > Bun.serve({ > port: 3000, > fetch(request) { > const url = new URL(request.url); > > if (url.pathname === "/api/checkout") { > if (request.method === "GET") { > return staticCheckoutHandler(request); > } > if (request.method === "POST") { > return sessionCheckoutHandler(request); > } > } > > return new Response("Not Found", { status: 404 }); > }, > }); > ``` > > ```bash Static Checkout cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/checkout?productId=pdt_xxx' > ``` > > ```bash Checkout Session cURL Example expandable theme={null} > curl --request POST \ > --url https://example.com/api/checkout \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_xxx", > "quantity": 1 > } > ], > "customer": { > "email": "customer@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal Handler > > > [!NOTE] > > > > Use this handler to send customers to the Dodo Payments Customer Portal, where they manage their subscriptions and details. > > ```typescript Bun Server Handler expandable theme={null} > import { CustomerPortal } from "@dodopayments/bun"; > > const customerPortalHandler = CustomerPortal({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > }); > > Bun.serve({ > port: 3000, > fetch(request) { > const url = new URL(request.url); > > if (url.pathname === "/api/customer-portal" && request.method === "GET") { > return customerPortalHandler(request); > } > > return new Response("Not Found", { status: 404 }); > }, > }); > ``` > > ```bash Customer Portal cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/customer-portal?customer_id=cus_123&send_email=true' > ``` > [tab] Webhook Handler > > > [!NOTE] > > > > Use this handler to receive Dodo Payments webhook events in your Bun server and verify their signatures. > > ```typescript Bun Server Handler expandable theme={null} > import { Webhooks } from "@dodopayments/bun"; > > const webhookHandler = Webhooks({ > webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, > onPayload: async (payload) => { > // handle the payload > }, > // ... other event handlers for granular control > }); > > Bun.serve({ > port: 3000, > fetch(request) { > const url = new URL(request.url); > > if (url.pathname === "/api/webhook/dodo-payments" && request.method === "POST") { > return webhookHandler(request); > } > > return new Response("Not Found", { status: 404 }); > }, > }); > ``` ## Checkout Route Handler The checkout handler supports all three ways to take payments with Dodo Payments: * **Static Payment Links:** Shareable URLs that collect payments without code. * **Dynamic Payment Links (deprecated):** Payment links you generate with custom details. They use deprecated endpoints. * **Checkout Sessions:** Hosted checkout with a product cart, customer details, and customization options. This is the recommended flow. `Checkout` takes these options: | Option | Type | Description | | - | - | - | | `bearerToken` | `string` | Your Dodo Payments API key. | | `environment` | `string` | `test_mode` or `live_mode`. Defaults to `live_mode`. | | `returnUrl` | `string` | Optional. The URL that checkout redirects the customer to after payment. A `return_url` in a POST body takes precedence. | | `type` | `string` | The checkout flow: `static`, `dynamic`, or `session`. Defaults to `static`. | The handler serves static checkout for `GET` requests. For `POST` requests, it creates a dynamic payment link when `type` is `dynamic`, and a checkout session otherwise. > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_xxx`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's street address. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's ZIP or postal code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > Payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed to checkout as metadata, for example `metadata_orderId=123`. > > A disable flag takes effect only when the matching field has a value, for example `email` with `disableEmail=true`. The handler adds `returnUrl` from its config to the link as `redirect_url`. > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters, or a product that doesn't exist in your account, also return 400. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL. In test mode, the URL uses `test.checkout.dodopayments.com`: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_xxx?quantity=1&redirect_url=https%3A%2F%2Fyourdomain.com%2Fcheckout%2Fsuccess" > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send the parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. The handler retrieves the product, then creates a subscription if the product is recurring and a one-time payment otherwise. > * The body needs `billing` (with `street`, `city`, `state`, `country`, and `zipcode`) and `customer`, plus `product_id` or `product_cart`. Subscriptions need `product_id`. > * For every supported body field, see: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic checkout proxies the deprecated `POST /payments` and `POST /subscriptions` endpoints. It keeps working for existing integrations, but new integrations should use checkout sessions. > > ### Response Format > > Dynamic checkout returns a JSON response with the payment link as the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/cbq" > } > ``` > [accordion] Checkout Sessions (POST) > > Checkout sessions create a hosted checkout for one-time purchases and subscriptions, with full control over customization. `product_cart` is the only required field, and it needs at least one product. If the body has no `return_url`, the handler uses `returnUrl` from its config. > > Each `checkout_url` works once and expires after 24 hours, or after 15 minutes when you pass `confirm: true`. A session created with `payment_method_id` returns no `checkout_url`, so the handler responds with 400. > > For more details and every supported field, see the [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session). > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa" > } > ``` ## Customer Portal Route Handler The Customer Portal route handler creates a Customer Portal session for the customer you pass and redirects the browser to it. `CustomerPortal` takes the same `bearerToken` and `environment` options as `Checkout`. > [!WARNING] > > The handler doesn't check who is calling it. Anyone who requests it with a customer ID gets that customer's portal. Protect the route with your own authentication, and pass only the signed-in user's customer ID. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, Dodo Payments also emails the portal link to the customer. The handler returns 400 if `customer_id` is missing, and 500 if the portal session can't be created. ## Webhook Route Handler The webhook route handler verifies each request with your webhook secret, passed as `webhookKey`, before it runs your code: * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`, following the Standard Webhooks specification. Returns 401 if verification fails. * **Payload Validation:** Parses the body as JSON and validates it with Zod. Returns 400 for invalid JSON or an invalid payload. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Internal error during verification * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200. The adaptor doesn't catch errors thrown in your handlers. They propagate to `Bun.serve()`, and the request fails. ### Supported Webhook Event Handlers Every handler is optional and async, and receives the verified payload for its event type: ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` For what each event means, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). ## Prompt for LLM Copy this prompt into your AI coding assistant to have it add the adaptor to your project. To give your agent the Dodo Payments docs and skills as well, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ````text expandable theme={null} You are an expert Bun developer assistant. Your task is to guide a user through integrating the @dodopayments/bun adapter into their existing Bun project. The @dodopayments/bun adapter provides handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities. Each handler takes a Web Standard Request and returns a Response, so it works with Bun's native server, Bun.serve(). First, install the necessary package: bun add @dodopayments/bun Here's how you should structure your response: Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/bun adapter would you like to integrate into your project? You can choose one or more of the following: 1. Checkout (static or session-based) 2. Customer Portal 3. Webhooks" Based on the user's selection, provide step-by-step integration instructions. For each selected functionality, show: The environment variables required The exact code to add to their server file Where to place the code in their Bun.serve() configuration Provide complete, working examples that the user can copy and paste directly into their project. Environment Variables Setup Always include instructions for setting up the .env file. Bun reads .env files automatically: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_RETURN_URL=your-return-url DODO_PAYMENTS_ENVIRONMENT is test_mode or live_mode. The handlers default to live_mode. Remind the user to never commit their .env file to version control. For Checkout Integration If the user selects Checkout, ask which type they need: Static checkout (GET requests with query parameters) Checkout sessions (POST requests with product cart) Provide the appropriate handler code for their selection. Every checkout type returns JSON with a checkout_url. For Customer Portal Integration Provide a complete example showing how to integrate the customer portal handler into their Bun server. The handler does not authenticate the caller, so protect the route and pass only the signed-in user's customer ID. For Webhook Integration Provide a complete example showing how to integrate the webhook handler with available event handlers for granular control. Full Example If the user wants to integrate all three functionalities, provide a complete Bun server example that combines all handlers. ```typescript import { Checkout, CustomerPortal, Webhooks } from "@dodopayments/bun"; const staticCheckoutHandler = Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, type: "static", }); const sessionCheckoutHandler = Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, type: "session", }); const customerPortalHandler = CustomerPortal({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, }); const webhookHandler = Webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, onPaymentSucceeded: async (payload) => { console.log("Payment succeeded:", payload); // Your business logic here }, onSubscriptionActive: async (payload) => { console.log("Subscription activated:", payload); // Your business logic here }, }); Bun.serve({ port: 3000, fetch(request) { const url = new URL(request.url); // Checkout routes if (url.pathname === "/api/checkout") { if (request.method === "GET") { return staticCheckoutHandler(request); } if (request.method === "POST") { return sessionCheckoutHandler(request); } } // Customer portal route if (url.pathname === "/api/customer-portal" && request.method === "GET") { return customerPortalHandler(request); } // Webhook route if (url.pathname === "/api/webhook/dodo-payments" && request.method === "POST") { return webhookHandler(request); } return new Response("Not Found", { status: 404 }); }, }); console.log("Server running on http://localhost:3000"); Additional Guidance: • Explain that the handlers plug directly into the fetch handler of Bun.serve() • Highlight the use of Web Standard Request and Response objects • Mention that the handlers return HTTP status codes for errors: 400 for invalid input, 401 for an invalid webhook signature, 405 for a webhook request that is not POST, and 500 for internal errors • Provide links to the Dodo Payments documentation for more details ```` # Checkout Sessions Source: https://docs.dodopayments.com/developer-resources/checkout-session Create secure, hosted checkout experiences for one-time payments and subscriptions with full customization control. > [card] [Quick Start](#creating-your-first-checkout-session) > > Create your first checkout session in under 5 minutes > [card] [API Reference](/api-reference/checkout-sessions/create) > > Full API documentation and interactive testing > [card] [Preview Endpoint](/api-reference/checkout-sessions/preview) > > Calculate pricing and taxes before creating a session > [!NOTE] > > **Session Validity**: Checkout sessions expire after 24 hours by default, or 15 minutes when `confirm: true`. > [!WARNING] > > **Single-Use Links**: The `checkout_url` is not reusable. Generate a fresh session for each customer and payment attempt rather than sharing or reusing a link. ## Prerequisites You need: * An active Dodo Payments merchant account * API credentials from **Developer → API Keys** in the dashboard * At least one product created in **Products** ## Creating Your First Checkout Session > [tab] Node.js SDK > > ```javascript expandable theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', > }); > > async function createCheckoutSession() { > const session = await client.checkoutSessions.create({ > product_cart: [ > { > product_id: 'pdt_123', > quantity: 1 > } > ], > customer: { > email: 'customer@example.com', > name: 'John Doe', > phone_number: '+1234567890' > }, > billing_address: { > street: '123 Main St', > city: 'San Francisco', > state: 'CA', > country: 'US', > zipcode: '94102' > }, > return_url: 'https://yoursite.com/checkout/success' > }); > > console.log('Checkout URL:', session.checkout_url); > return session; > } > ``` > [tab] Python SDK > > ```python expandable theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), > environment="test_mode", > ) > > def create_checkout_session(): > session = client.checkout_sessions.create( > product_cart=[ > { > "product_id": "pdt_123", > "quantity": 1 > } > ], > customer={ > "email": "customer@example.com", > "name": "John Doe", > "phone_number": "+1234567890" > }, > billing_address={ > "street": "123 Main St", > "city": "San Francisco", > "state": "CA", > "country": "US", > "zipcode": "94102" > }, > return_url="https://yoursite.com/checkout/success" > ) > > print(f"Checkout URL: {session.checkout_url}") > return session > ``` > [tab] REST API > > ```bash theme={null} > curl -X POST https://test.dodopayments.com/checkouts \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_cart": [ > { > "product_id": "pdt_123", > "quantity": 1 > } > ], > "customer": { > "email": "customer@example.com", > "name": "John Doe", > "phone_number": "+1234567890" > }, > "billing_address": { > "street": "123 Main St", > "city": "San Francisco", > "state": "CA", > "country": "US", > "zipcode": "94102" > }, > "return_url": "https://yoursite.com/checkout/success" > }' > ``` ### API Response All methods return: ```json theme={null} { "session_id": "cks_Gi6KGJ2zFJo9rq9Ukifwa", "checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa" } ``` Only `session_id` is guaranteed to be present. When `payment_method_id` is provided, the charge processes immediately and `checkout_url` is `null`. Use the returned `payment_id` instead. When `confirm: true`, the payment is created at session-creation time, and the response also includes `payment_id`, `client_secret`, and `publishable_key` for use with the Dodo Payments checkout SDK. ### Redirect Your Customer **1. Extract the checkout URL** Get `checkout_url` from the API response. **2. Redirect to checkout** Send your customer to the URL: ```javascript theme={null} window.location.href = session.checkout_url; ``` Alternatively, open in a new window: ```javascript theme={null} window.open(session.checkout_url, '_blank'); ``` **3. Handle the return** After payment, customers are redirected to your `return_url` with query parameters: | Parameter | Type | Condition | | - | - | - | | `payment_id` | string | Always present for one-time payments | | `subscription_id` | string | Always present for subscriptions | | `status` | string | Always present | | `license_key` | string | Present if the product has license keys enabled. Comma-separated if multiple keys | | `email` | string | Present if the customer has an email on record | Example redirect: ``` https://yoursite.com/return?payment_id=pay_xxx&status=succeeded&license_key=LK-001&email=customer%40example.com ``` > [!TIP] > > Instead of redirecting, you can embed checkout directly in your page using [Overlay Checkout](/developer-resources/overlay-checkout) (modal), [Inline Checkout](/developer-resources/inline-checkout) (embedded), or [Mobile SDKs](/developer-resources/mobile-integration) (native apps). All consume the same session URL. ### Check Session Status To check a session's status, call [Get Checkout Session](/api-reference/checkout-sessions/get-checkouts) (`GET /checkouts/{id}`). The response has the session `id`, `created_at`, `customer_email`, and `customer_name`, plus `payment_id` and `payment_status`. Both payment fields are `null` while the customer is still entering details. After the customer submits payment, `payment_status` holds the payment's status, such as `succeeded`, `failed`, or `processing`. Use webhooks as the source of truth for fulfillment. ## Request Body ### Required Fields **product\_cart** `array` *required* Array of products to include in the checkout session. Each product must have a valid `product_id` from your dashboard. You can combine one-time payment products with one subscription product in the same session. A cart can also hold two or more subscription products, but then it can't hold one-time products. See [Multi-Subscription Cart](#multi-subscription-cart). A cart holds at most 20 products. **Product Cart Item Properties** **product\_id** `string` *required* The unique identifier of the product from your dashboard. **Example:** `"pdt_123abc456def"` **quantity** `integer` *required* Quantity of the product. **Example:** `1` for single item, `3` for multiple quantities **addons** `array` Array of addons to attach to the product. Only valid for subscription products. **Addon Item Properties** **addon\_id** `string` *required* The unique identifier of the addon. **quantity** `integer` *required* Quantity of the addon. **amount** `integer` Amount the customer pays if pay-what-you-want is enabled on the product. Represented in the lowest denomination of the currency (e.g., cents for USD). For example, `100` = \$1.00. Ignored if pay-what-you-want is disabled. Only applies to one-time payments. If you don't set it for a pay-what-you-want product, the customer chooses the amount. **credit\_entitlements** `array` Per-session overrides for credit entitlements already attached to this product. Use this to grant a different number of credits for this single session without creating a separate product. Each `credit_entitlement_id` must already be attached to the product. This field overrides only the `credits_amount` granted when this session is fulfilled; product-level credit entitlement settings (expiration, rollover, etc.) still apply. **Credit Entitlement Override Properties** **credit\_entitlement\_id** `string` *required* ID of the credit entitlement to override. Must already be attached to the product. **credits\_amount** `string` *required* Number of credits to grant for this checkout session, overriding the product-level `credits_amount`. Must be greater than zero. > [!TIP] > > **Find Your Product IDs**: You can find product IDs in your Dodo Payments dashboard under **Products → View Details**, or by using the [List Products API](/api-reference/products/get-products). ### Optional Fields > [accordion] Customer Information > > **customer** `object` > > Customer information. You can either attach an existing customer using their ID or create a new customer record during checkout. > > > [tab] Attach Existing Customer > > > > **Existing Customer Properties** > > > > **customer\_id** `string` *required* > > > > The unique identifier of an existing customer. > > > [tab] Create New Customer > > > > **New Customer Properties** > > > > **email** `string` *required* > > > > Customer's email address. > > > > **name** `string` > > > > Customer's full name as it should appear on receipts and invoices. > > > > **Example**: `"John Doe"` > > > > **phone\_number** `string` > > > > Customer's phone number in international format. Required for some payment methods and fraud prevention. > > > > **Format**: Include country code, e.g., `"+1234567890"` > > **billing\_address** `object` > > Billing address information for accurate tax calculation, fraud prevention, and regulatory compliance. > > When `confirm: true`, all billing address fields become required, unless `minimal_address` is `true`. > > **Billing Address Properties** > > **street** `string` > > Complete street address including house number, street name, and apartment/unit number if applicable. > > **Example**: `"123 Main St, Apt 4B"` > > **city** `string` > > City or municipality name. > > **Example**: `"San Francisco"` > > **state** `string` > > State, province, or region name. Use full names or standard abbreviations. > > **Example**: `"California"` or `"CA"` > > **country** `string` *required* > > Two-letter ISO country code (ISO 3166-1 alpha-2). Always required when billing\_address is provided. > > **Examples**: `"US"`, `"CA"`, `"GB"`, `"DE"` > > > [card] [Country Code Reference](/api-reference/misc/supported-countries) > > > > View complete list of supported countries and their ISO codes > > **zipcode** `string` > > Postal code, ZIP code, or equivalent based on country requirements. > > **Examples**: `"94102"` (US), `"M5V 3A8"` (Canada), `"SW1A 1AA"` (UK) > [accordion] Payment Configuration > > **allowed\_payment\_method\_types** `array` > > Control which payment methods are available to customers during checkout. This helps optimize for specific markets or business requirements. > > **Common options**: `credit`, `debit`, `upi_intent`, `apple_pay`, `google_pay`, `amazon_pay`, `klarna`, `affirm`, `afterpay_clearpay`, `cashapp`, `ach`, `multibanco`, `bancontact_card`, `eps`, `ideal`, `blik`, `gcash`, `ali_pay_hk`, `fps`, `touch_n_go`, `paypal` > > See the [Create Checkout Session API reference](/api-reference/checkout-sessions/create) for the complete list. > > > [!WARNING] > > > > Always include `credit` and `debit` as fallback options to prevent checkout failures when preferred payment methods are unavailable. > > **Example**: > > ```json theme={null} > ["apple_pay", "google_pay", "credit", "debit"] > ``` > > **billing\_currency** `string` > > Override the default currency selection with a fixed billing currency. Uses ISO 4217 currency codes. > > **Supported Currencies**: `USD`, `EUR`, `GBP`, `CAD`, `AUD`, `INR`, and more > > **Example**: `"USD"` for US Dollars, `"EUR"` for Euros > > This field is only effective when adaptive pricing is enabled. If adaptive pricing is disabled, the API discards this field, and the currency comes from the product price or the billing country. > > **show\_saved\_payment\_methods** `boolean` (default: false) > > Display previously saved payment methods for returning customers, improving checkout speed and user experience. > [accordion] Session Management > > **return\_url** `string` > > URL to redirect customers after payment completion. Dodo Payments appends query parameters to your URL on redirect (see the redirect table above). > > **Example redirect URLs**: > > ```text theme={null} > # One-time payment with license key > https://yoursite.com/return?payment_id=pay_xxx&status=succeeded&license_key=LK-001&email=customer%40example.com > > # Subscription payment with multiple license keys > https://yoursite.com/return?subscription_id=sub_xxx&status=active&license_key=LK-001,LK-002&email=customer%40example.com > > # Payment without license keys > https://yoursite.com/return?payment_id=pay_xxx&status=succeeded&email=customer%40example.com > ``` > > Use the `license_key` and `email` query parameters to display license keys or send a confirmation immediately on your return page, without needing an extra API call. > > **cancel\_url** `string` > > URL to redirect customers when they click the back button or cancel the checkout session. If not provided, the back button will not be displayed. > > Set a `cancel_url` to give customers a clear way to return to your site without completing the purchase. > > **confirm** `boolean` (default: false) > > If true, finalizes all session details immediately. The API throws an error if required data is missing. > > When `confirm: true`: > > * All billing address fields become required (only `country` and `zipcode` when `minimal_address` is `true`) > * `payment_method_id` can be provided to process the charge immediately > * Session expires after 15 minutes instead of 24 hours > * An existing `customer_id` is required if `payment_method_id` is provided > > **discount\_codes** `array` > > Apply one or more stacked discount codes to the checkout session. Codes are applied in array order (the first code reduces the starting price, the second reduces the already-discounted price, and so on), up to a maximum of 20 codes per session. > > When [Purchasing Power Parity](/features/purchasing-power-parity) is enabled, the starting price is the PPP-adjusted amount, not the base price. > > ```typescript theme={null} > discount_codes: ['WELCOME10', 'BLACKFRIDAY20'] > ``` > > The singular `discount_code` field below is deprecated but still fully supported. It cannot be combined with `discount_codes` in the same request. > > **discount\_code** `string` *deprecated* > > **Deprecated** — prefer `discount_codes` for new integrations. This field still works for backward compatibility, but cannot be combined with `discount_codes` in the same request. > > **metadata** `object` > > Custom key-value pairs to store additional information about the session. > > **force\_3ds** `boolean` > > Override merchant default 3DS behaviour for this session. > > **minimal\_address** `boolean` > > Enable minimal address collection mode. When enabled, the checkout only collects: > > * **Country**: Always required for tax determination > * **ZIP/Postal code**: Only in regions where it's necessary for sales tax, VAT, or GST calculation > > This significantly reduces checkout friction by eliminating unnecessary form fields. > > With `confirm: true`, only `zipcode` (plus `country`) is required; the other billing address fields remain optional. > > Defaults to `true` when `feature_flags.single_page` is `true`, and to `false` otherwise. > > **payment\_method\_id** `string` > > A saved payment method belonging to the attached customer. Requires `confirm: true` and an existing `customer.customer_id`. The payment method is validated for eligibility with the payment's currency. When set, the charge is processed immediately and `checkout_url` is returned as `null`. Use the returned `payment_id` instead. > > **short\_link** `boolean` (default: false) > > If true, returns a shortened checkout URL instead of the full session URL. > > **product\_collection\_id** `string` > > Product collection ID for the collection-based checkout flow. When you set it, pass an empty `product_cart` array. Discount codes can't be pre-applied at session creation. See [Product Collections](/features/checkout#product-collections). > > **tax\_id** `string` > > Tax ID for the customer (for example, a VAT number). Requires `billing_address` with a `country`. > > **customer\_business\_name** `string` > > Optional business or legal name associated with the tax ID, up to 250 characters. When provided together with a valid `tax_id`, it is rendered on the invoice instead of the customer's personal name. > > **mandate\_min\_amount\_inr\_paise** `integer` > > Override the merchant-level mandate floor (in INR paise) for INR e-mandates on Indian cards. > > The mandate amount sent to the processor is `max(this_floor, actual_billing_amount)`, so this is effectively the customer-facing authorization ceiling whenever billing is lower. When unset, the merchant setting applies; when that's also unset, the system default of ₹15,000 applies. > [accordion] UI Customization > > **customization** `object` > > Customize the appearance and behavior of the checkout interface. > > **Customization Properties** > > **theme** `string` > > Theme for the checkout interface. Options: `light`, `dark`, or `system`. If not provided, the checkout uses the theme configured for your business in the dashboard. > > **show\_order\_details** `boolean` (default: true) > > Display order details section in the checkout interface. > > **show\_on\_demand\_tag** `boolean` (default: true) > > Show the "on-demand" tag for applicable products. > > **force\_language** `string` > > Force the checkout interface to render in a specific language. By default, the checkout auto-detects the customer's browser language. > > **Supported language codes**: `ar`, `ca`, `de`, `en`, `es`, `fr`, `he`, `hr`, `id`, `it`, `ja`, `ka`, `ko`, `ms`, `nl`, `pl`, `pt`, `ro`, `ru`, `sr`, `sv`, `th`, `tr`, `zh` > > **Example**: `"es"` for Spanish, `"ja"` for Japanese > > **payment\_method\_layout** `string` (default: accordion) > > How [single page checkout](/features/single-page-checkout#payment-method-layout) shows the payment methods. Options: `accordion` (one row for each method) or `tabs` (one tab for each method). > > Only for single page checkout. If you set it while `feature_flags.single_page` is `false`, the request fails with a `422` error. > > **theme\_config** `object` > > Custom theme configuration with colors for light and dark modes, fonts, and button styling. This replaces the client-side `themeConfig` option, which Checkout SDK 2.0.1 removes. > > **Theme Config Properties** > > **light** `object` > > Light mode color configuration. > > **dark** `object` > > Dark mode color configuration. > > **font\_primary\_url** `string` > > URL for the primary font. Must be a valid `https://` URL. > > **font\_secondary\_url** `string` > > URL for the secondary font. Must be a valid `https://` URL. > > **font\_size** `string` > > Font size for the checkout UI. Options: `xs`, `sm`, `md`, `lg`, `xl`, `2xl`. > > **font\_weight** `string` > > Font weight for the checkout UI. Options: `normal`, `medium`, `bold`, `extraBold`. > > **pay\_button\_text** `string` > > Custom text for the pay button (for example, `"Complete Purchase"` or `"Subscribe Now"`). Max 100 characters. > > **radius** `string` > > Border radius for UI elements. A number followed by `px`, `rem`, or `em` (for example, `"4px"`, `"0.5rem"`, `"1em"`). > [accordion] Feature Flags > > **feature\_flags** `object` > > Configure specific features and behaviors for the checkout session. > > **Feature Flags Properties** > > **allow\_currency\_selection** `boolean` (default: true) > > Allow customers to select their preferred currency during checkout. > > **allow\_discount\_code** `boolean` (default: true) > > Show discount code input field in the checkout interface. When `false`, codes you pass in `discount_codes` still apply, and the customer can't change them. > > **allow\_editing\_addons** `boolean` (default: false) > > Allow customers to add or remove addons on a subscription product during checkout. Only applies to subscription products. > > **allow\_phone\_number\_collection** `boolean` (default: true) > > Collect customer phone numbers during checkout. > > **require\_phone\_number** `boolean` (default: false) > > Require the customer to provide a phone number to complete checkout. Requires `allow_phone_number_collection` to also be true. > > **require\_cardholder\_name** `boolean` (default: false) > > Require the customer to enter the name on the card to pay by card. With Apple Pay, the payment sheet also asks for the payer name. On inline and overlay checkout, this needs Checkout SDK 2.0.1 or later. > > **allow\_tax\_id** `boolean` (default: true) > > Allow customers to enter tax identification numbers. > > **require\_tax\_id** `boolean` (default: false) > > Require the customer to provide a Tax ID (GST number in India, VAT number in the EU) before they can complete checkout. > > When enabled, a customer who checks out as a business must provide a Tax ID. Checkout doesn't change for a customer who buys as an individual. See [B2B Payments](/features/b2b-payments#making-the-tax-id-mandatory) for the full checkout behavior. > > `allow_tax_id` must also be `true`. Otherwise, the request is rejected with a `400` and the message `feature_flags.require_tax_id: cannot be true when allow_tax_id is false`. With `confirm: true`, the request must include a non-blank `tax_id`, or it is rejected with a `422`. > > **always\_create\_new\_customer** `boolean` (default: false) > > Create a new customer record for this session. By default, the customer email is used to find an existing customer and attach the session to it. > > **allow\_customer\_editing\_email** `boolean` > > Allow customers to edit their email address during checkout. > > **allow\_customer\_editing\_name** `boolean` > > Allow customers to edit their name during checkout. > > **allow\_customer\_editing\_street** `boolean` > > Allow customers to edit the street address during checkout. > > **allow\_customer\_editing\_city** `boolean` > > Allow customers to edit the city during checkout. > > **allow\_customer\_editing\_state** `boolean` > > Allow customers to edit the state during checkout. > > **allow\_customer\_editing\_country** `boolean` > > Allow customers to edit the country during checkout. > > **allow\_customer\_editing\_zipcode** `boolean` > > Allow customers to edit the zipcode during checkout. > > **allow\_customer\_editing\_tax\_id** `boolean` > > Allow customers to enter or edit their tax ID during checkout. > > **allow\_customer\_editing\_business\_name** `boolean` (default: false) > > Allow the customer to supply or edit the business name associated with the tax ID. Works independently of `allow_customer_editing_tax_id`: either flag (or `allow_tax_id`) is sufficient to let the customer override the session's business name. Typically set together with `allow_customer_editing_tax_id`. > > **redirect\_immediately** `boolean` (default: false) > > Skip the default payment success page and redirect customers immediately to your `return_url` after payment completion. > > Use this when you have a custom success page that provides a better user experience, or for [mobile apps](/developer-resources/mobile-integration) and embedded checkout flows. > > **single\_page** `boolean` (default: false) > > If true, the session uses the single-page checkout flow: the page initializes the payment at load time and confirms it in place, with no separate payment page. See [Single Page Checkout](/features/single-page-checkout). > [accordion] Custom Fields > > **custom\_fields** `array` > > Collect additional information from customers during checkout with custom form fields. You can define up to 5 custom fields per checkout session. Customer responses are included in webhook payloads and available via the API. > > **Custom Field Properties** > > **key** `string` *required* > > Unique identifier for this field. Used as the key in webhook payloads and API responses. > > **Example**: `"company_name"`, `"referral_source"`, `"team_size"` > > **label** `string` *required* > > Display label shown to the customer on the checkout form. > > **Example**: `"Company Name"`, `"How did you hear about us?"`, `"Team Size"` > > **field\_type** `string` *required* > > Type of field determining input validation rules. > > **Available types**: `text`, `number`, `email`, `url`, `date`, `dropdown`, `boolean` > > **required** `boolean` (default: false) > > Whether this field must be filled before checkout can complete. > > **placeholder** `string` > > Placeholder text displayed in the input field. > > **options** `array` > > List of options for `dropdown` field type. Required when `field_type` is `dropdown`, ignored for other types. > > **Example**: `["Google", "Twitter", "Friend referral", "Other"]` > > Customer responses to custom fields are included in: > > * **Webhooks**: `payment.succeeded`, `subscription.active`, and other relevant event payloads contain the `custom_field_responses` array > * **API responses**: Payment and subscription objects include `custom_field_responses` > [accordion] Subscription Configuration > > **subscription\_data** `object` > > Additional configuration for checkout sessions containing subscription products. > > **Subscription Data Properties** > > **trial\_period\_days** `integer` > > Number of days for the trial period before the first charge. Must be between 0 and 10000 days. > > A paid trial amount cannot be set per session. Configure `trial_amount` on the product's recurring price instead. See [Paid Trials](/features/subscription#paid-trials). > > **on\_demand** `object` > > On-demand subscription configuration for usage-based or metered billing. > > **On-Demand Properties** > > **mandate\_only** `boolean` *required* > > If set to true, does not perform any charge and only authorizes payment method details for future use. > > **product\_price** `integer` > > Product price for the initial charge to customer. If not specified, the stored price of the product is used. > > **Format**: Represented in the lowest denomination of the currency (e.g., cents for USD). For example, `100` = \$1.00. > > **product\_currency** `string` > > Optional currency of the product price. If not specified, defaults to the currency of the product. > > **product\_description** `string` > > Optional product description override for billing and line items. If not specified, the stored description of the product is used. > > **adaptive\_currency\_fees\_inclusive** `boolean` > > Whether adaptive currency fees should be included in the product price (true) or added on top (false). Ignored if adaptive pricing is not enabled. ## Usage Examples ### Simple Single Product Checkout ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_ebook_guide', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, return_url: 'https://yoursite.com/success' }); ``` ### Multi-Product Cart ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_course_advanced', quantity: 1 }, { product_id: 'pdt_certificate', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'Jane Smith' }, return_url: 'https://yoursite.com/success' }); ``` ### Multi-Subscription Cart To sell several subscription products in one checkout, add two or more subscription products to `product_cart`. The customer pays once, and Dodo Payments creates one payment, one invoice, and one subscription for each product. Each subscription has its own billing cycle and renews on its own, so a monthly product and an annual product can share a cart. ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_monthly_plan', quantity: 1 }, { product_id: 'pdt_annual_addon_plan', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'Jane Smith' }, return_url: 'https://yoursite.com/success' }); ``` A multi-subscription cart has these limits: * It can't hold one-time products. The API rejects the request with a `422`. * It holds at most 20 subscription products. * It can't list the same product twice. To sell more than one unit of a product, set `quantity` instead. * It can't use on-demand billing (`subscription_data.on_demand`). * A discount code applied to the cart counts as one redemption. `subscription_data.trial_period_days` applies to every subscription in the cart. Without it, each subscription uses the trial set on its own product. When you don't set it and [Prevent Trial Misuse](/features/subscription#preventing-trial-misuse) is on, a product the customer already trialed starts without a trial. The resulting payment has `is_multi_subscription: true` and lists every subscription it starts in `subscription_ids`. Its `subscription_id` is `null`, because no single subscription owns the payment. The `payment.succeeded` webhook carries the same fields. Read `is_multi_subscription` to find the payment type, not the length of `subscription_ids`. After the payment succeeds, you receive one `payment.succeeded` event for the cart and one `subscription.active` event for each subscription. From then on, each subscription renews, changes plan, and cancels on its own, with its own invoice for each renewal. All subscriptions from one cart share the payment method the customer used at checkout. When you [update the payment method](/api-reference/subscriptions/update-payment-method) of one of them, Dodo Payments moves the new payment method to every subscription from the same cart that has the same settlement currency and billing currency and is `active`, `on_hold`, `past_due`, or `paused`. Every subscription from a cart starts with the same settlement currency and billing currency, even when its products have different price currencies. A later change, such as a plan change, can move a subscription to another settlement currency or billing currency. That subscription keeps its old payment method, so update it separately. For an `on_hold` subscription, the update retries only that subscription's unpaid invoice. ### Subscription with Trial Period ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_saas_pro', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, subscription_data: { trial_period_days: 14 }, return_url: 'https://yoursite.com/success' }); ``` ### Pre-Confirmed Checkout ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { customer_id: 'cus_existing_customer_id' }, billing_address: { street: '123 Main St', city: 'San Francisco', state: 'CA', country: 'US', zipcode: '94102' }, confirm: true, return_url: 'https://yoursite.com/success' }); ``` ### Checkout with Currency Override ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, billing_currency: 'EUR', return_url: 'https://yoursite.com/success' }); ``` ### Saved Payment Methods for Returning Customers ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { customer_id: 'cus_existing_customer_id' }, show_saved_payment_methods: true, return_url: 'https://yoursite.com/success' }); ``` ### B2B Checkout with Tax ID Collection ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_enterprise_plan', quantity: 1 } ], customer: { email: 'procurement@company.com', name: 'Jane Smith' }, billing_address: { street: '456 Business Ave', city: 'London', country: 'GB', zipcode: 'SW1A 1AA' }, feature_flags: { require_tax_id: true }, return_url: 'https://yoursite.com/success' }); ``` ### Dark Theme Checkout with Stacked Discount Codes ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, customization: { theme: 'dark' }, discount_codes: ['WELCOME10', 'BLACKFRIDAY20'], return_url: 'https://yoursite.com/success' }); ``` ### Regional Payment Methods (UPI for India) For detailed information about UPI configuration and testing, see the [India Payment Methods](/features/payment-methods/india) page. ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, billing_address: { street: '123 Main St', city: 'Bangalore', state: 'KA', country: 'IN', zipcode: '560001' }, billing_currency: 'INR', allowed_payment_method_types: ['upi_intent', 'credit', 'debit'], return_url: 'https://yoursite.com/success' }); ``` ### BNPL (Buy Now Pay Later) Checkout For detailed information about BNPL configuration and testing, see the [Buy Now Pay Later (BNPL)](/features/payment-methods/bnpl) page. ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, allowed_payment_method_types: ['klarna', 'affirm', 'afterpay_clearpay', 'credit', 'debit'], return_url: 'https://yoursite.com/success' }); ``` ### Instant Checkout with Existing Payment Method ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { customer_id: 'cus_existing_customer_id' }, payment_method_id: 'pm_existing_payment_method_id', confirm: true, return_url: 'https://yoursite.com/success' }); ``` ### Short Links for Cleaner Payment URLs ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, short_link: true, return_url: 'https://yoursite.com/success' }); ``` ### Skip Payment Success Page with Immediate Redirect ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, feature_flags: { redirect_immediately: true }, return_url: 'https://yoursite.com/success' }); ``` ### Forcing a Language ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, customization: { force_language: 'es' }, return_url: 'https://yoursite.com/success' }); ``` ### Collecting Custom Fields ```javascript expandable theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123', quantity: 1 } ], customer: { email: 'customer@example.com', name: 'John Doe' }, custom_fields: [ { key: 'company_name', label: 'Company Name', field_type: 'text', required: true }, { key: 'referral_source', label: 'How did you hear about us?', field_type: 'dropdown', options: ['Google', 'Twitter', 'Friend referral', 'Other'], required: true } ], return_url: 'https://yoursite.com/success' }); ``` ## Previewing Checkout Sessions Use the [Preview Checkout Session](/api-reference/checkout-sessions/preview) endpoint to calculate pricing, taxes, and totals before creating a session. This is useful for displaying accurate pricing information on your site. > [!NOTE] > > The previewed `current_breakup.subtotal` already reflects [Purchasing Power Parity](/features/purchasing-power-parity) and [Charm Pricing](/features/charm-pricing) where they apply to the product. > [!NOTE] > > When the cart contains a subscription product, the preview response also returns a `next_billing_date` — a preview of the upcoming billing date, so you can show it before the subscription is created. It is computed relative to now: `now + trial period` when a trial applies, otherwise `now + one payment frequency`. The field is `null` for one-time-only carts. This is an estimate anchored on the preview time; the authoritative `next_billing_date` is set when the subscription activates. > [!NOTE] > > The preview also returns `trial_period_days` (the effective trial length, free or paid) and `trial_amount` (the per-unit trial charge after discounts, in the price currency's minor units). `trial_amount` is only present for a [paid trial](/features/subscription#paid-trials) and is `null` for a free trial or no trial. Use `current_breakup` for the taxed total actually due today. > [!NOTE] > > For a [multi-subscription cart](#multi-subscription-cart), the response also returns a `subscriptions` array with one entry per subscription: `product_id`, `amount_due_now`, `tax_due_now`, `recurring_amount`, `recurring_tax`, `trial_period_days`, and `next_billing_date`. The top-level `next_billing_date` is the earliest date in the cart, and the top-level `trial_period_days` and `trial_amount` are `null`. Read amounts from `subscriptions` and `current_breakup`. `recurring_breakup` adds up the renewal amounts of every subscription, even when they renew on different dates, so read each renewal from `subscriptions`. > [tab] Node.js SDK > > ```javascript expandable theme={null} > const preview = await client.checkoutSessions.preview({ > product_cart: [ > { product_id: 'pdt_123', quantity: 1 } > ], > billing_address: { > country: 'US', > state: 'CA', > zipcode: '94102' > }, > discount_codes: ['SAVE20'] > }); > > console.log('Subtotal:', preview.current_breakup.subtotal); > console.log('Tax:', preview.current_breakup.tax); > console.log('Discount:', preview.current_breakup.discount); > console.log('Total:', preview.current_breakup.total_amount); > > // Present only when the cart contains a subscription product > console.log('Next billing date:', preview.next_billing_date); > ``` > [tab] Python SDK > > ```python expandable theme={null} > preview = client.checkout_sessions.preview( > product_cart=[ > {"product_id": "pdt_123", "quantity": 1} > ], > billing_address={ > "country": "US", > "state": "CA", > "zipcode": "94102" > }, > discount_codes=["SAVE20"] > ) > > print(f"Subtotal: {preview.current_breakup.subtotal}") > print(f"Tax: {preview.current_breakup.tax}") > print(f"Discount: {preview.current_breakup.discount}") > print(f"Total: {preview.current_breakup.total_amount}") > > # Present only when the cart contains a subscription product > print(f"Next billing date: {preview.next_billing_date}") > ``` > [tab] REST API > > ```bash theme={null} > curl -X POST https://test.dodopayments.com/checkouts/preview \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_cart": [ > { > "product_id": "pdt_123", > "quantity": 1 > } > ], > "billing_address": { > "country": "US", > "state": "CA", > "zipcode": "94102" > }, > "discount_codes": ["SAVE20"] > }' > ``` ## Migrating from Dynamic Links If you're using Dynamic Links, Checkout Sessions offer more flexibility. With Dynamic Links, you had to provide the customer's complete billing address. With Checkout Sessions, you can pass whatever information you have, and the checkout flow collects the rest. For example: * Provide only the customer's billing country, and checkout collects the remaining details. * Or provide all information and set `confirm: true` to skip directly to the payment page. Migrating is straightforward: update your integration to use the Checkout Sessions API or SDK method, adjust the request payload to match the Checkout Sessions format, and you're done. No additional handling is needed. ## Related Resources > [card] [Overlay Checkout](/developer-resources/overlay-checkout) > > Open checkout as a modal overlay on your page > [card] [Inline Checkout](/developer-resources/inline-checkout) > > Embed checkout directly in your page > [card] [Mobile Integration](/developer-resources/mobile-integration) > > Integrate checkout in native mobile apps > [card] [Webhooks](/developer-resources/webhooks) > > Listen for payment and subscription events > [card] [Payment Methods](/features/payment-methods) > > Supported payment methods by region > [card] [Subscriptions](/features/subscription) > > Recurring billing and subscription management # Convex Component Source: https://docs.dodopayments.com/developer-resources/convex-component Add Dodo Payments checkout, Customer Portal, and webhook handling to your Convex backend with the @dodopayments/convex component. The `@dodopayments/convex` component adds Dodo Payments to your Convex backend. It provides a `checkout` function that creates checkout sessions, a `customerPortal` function that opens the Customer Portal for the signed-in user, and `createDodoWebhookHandler`, which verifies webhooks in a Convex HTTP action. It requires Convex 1.26 or later. > [card] [Checkout Function](#checkout-function) > > Create checkout sessions from Convex actions. > [card] [Customer Portal](#customer-portal-function) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-handler) > > Receive and process Dodo Payments webhook events. ## Installation **1. Install the Package** Run this command in your project root: ```bash theme={null} npm install @dodopayments/convex ``` **2. Add Component to Convex Config** Add the Dodo Payments component to your Convex configuration: ```typescript theme={null} // convex/convex.config.ts import { defineApp } from "convex/server"; import dodopayments from "@dodopayments/convex/convex.config"; const app = defineApp(); app.use(dodopayments); export default app; ``` After you edit `convex.config.ts`, run `npx convex dev` once to generate the types. **3. Set Up Environment Variables** Set environment variables in your Convex dashboard under **Settings → Environment Variables**. To open the dashboard, run: ```bash theme={null} npx convex dashboard ``` Add these environment variables: * `DODO_PAYMENTS_API_KEY`: Your Dodo Payments API key, from **Developer → API Keys** in the Dodo Payments dashboard. * `DODO_PAYMENTS_ENVIRONMENT`: `test_mode` or `live_mode`. * `DODO_PAYMENTS_WEBHOOK_SECRET`: Your webhook secret, from **Developer → Webhooks**. Required for webhook handling. The webhook handler reads this exact variable name. > [!WARNING] > > Store secrets as Convex environment variables. Convex backend functions don't read `.env` files. Never commit secrets to version control. ## Component Setup Examples **1. Create Internal Query** Create an internal query that finds a customer in your database by auth ID. The `identify` function in the next step uses it to get the signed-in user's Dodo Payments customer ID for the customer portal. > [!WARNING] > > The component doesn't define a schema. Before you use this query, define a `customers` table with a `by_auth_id` index in `convex/schema.ts`, or change the query to match your existing schema. ```typescript theme={null} // convex/customers.ts import { internalQuery } from "./_generated/server"; import { v } from "convex/values"; // Internal query to fetch customer by auth ID export const getByAuthId = internalQuery({ args: { authId: v.string() }, handler: async (ctx, { authId }) => { return await ctx.db .query("customers") .withIndex("by_auth_id", (q) => q.eq("authId", authId)) .first(); }, }); ``` **2. Configure DodoPayments Component** Create the client. `identify` maps the signed-in Convex user to a Dodo Payments customer ID. It returns `null` if no user is signed in or no customer matches. ```typescript Convex Component Setup expandable theme={null} // convex/dodo.ts import { DodoPayments, type DodoPaymentsClientConfig } from "@dodopayments/convex"; import { components } from "./_generated/api"; import { internal } from "./_generated/api"; export const dodo = new DodoPayments(components.dodopayments, { // This function maps your Convex user to a Dodo Payments customer // Customize it based on your authentication provider and database identify: async (ctx) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) { return null; // User is not logged in } // Use ctx.runQuery() to lookup customer from your database const customer = await ctx.runQuery(internal.customers.getByAuthId, { authId: identity.subject, }); if (!customer) { return null; // Customer not found in database } return { dodoCustomerId: customer.dodoCustomerId, // Replace customer.dodoCustomerId with your field storing Dodo Payments customer ID }; }, apiKey: process.env.DODO_PAYMENTS_API_KEY!, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", } as DodoPaymentsClientConfig); // Export the API methods for use in your app export const { checkout, customerPortal } = dodo.api(); ``` Then add the functions you need: > [tab] Checkout Function Setup > > > [!NOTE] > > > > Use this function to add Dodo Payments checkout to your Convex app. It creates a checkout session from the fields accepted by the component's checkout payload validator. > > ```typescript Checkout Action expandable theme={null} > // convex/payments.ts > import { action } from "./_generated/server"; > import { v } from "convex/values"; > import { checkout } from "./dodo"; > > export const createCheckout = action({ > args: { > product_cart: v.array(v.object({ > product_id: v.string(), > quantity: v.number(), > })), > returnUrl: v.optional(v.string()), > }, > handler: async (ctx, args) => { > try { > const session = await checkout(ctx, { > payload: { > product_cart: args.product_cart, > return_url: args.returnUrl, > billing_currency: "USD", > feature_flags: { > allow_discount_code: true, > }, > }, > }); > if (!session?.checkout_url) { > throw new Error("Checkout session did not return a checkout_url"); > } > return session; > } catch (error) { > console.error("Failed to create checkout session", error); > throw new Error("Unable to create checkout session. Please try again."); > } > }, > }); > ``` > [tab] Customer Portal Setup > > > [!NOTE] > > > > Use this function to let customers manage their subscriptions and details in the Dodo Payments Customer Portal. The `identify` function finds the customer. > > ```typescript Customer Portal Action expandable theme={null} > // convex/payments.ts (add to existing file) > import { action } from "./_generated/server"; > import { v } from "convex/values"; > import { customerPortal } from "./dodo"; > > export const getCustomerPortal = action({ > args: { > send_email: v.optional(v.boolean()), > }, > handler: async (ctx, args) => { > try { > const portal = await customerPortal(ctx, args); > if (!portal?.portal_url) { > throw new Error("Customer portal did not return a portal_url"); > } > return portal; > } catch (error) { > console.error("Failed to generate customer portal link", error); > throw new Error("Unable to generate customer portal link. Please try again."); > } > }, > }); > ``` > [tab] Webhook Handler Setup > > > [!NOTE] > > > > Use this handler to receive Dodo Payments webhook events in your Convex app and verify their signatures. Every webhook handler receives the Convex `ActionCtx` as its first parameter, so you can call `ctx.runQuery()` and `ctx.runMutation()` to work with your database. > > ```typescript Convex HTTP Action expandable theme={null} > // convex/http.ts > import { createDodoWebhookHandler } from "@dodopayments/convex"; > import { httpRouter } from "convex/server"; > import { internal } from "./_generated/api"; > > const http = httpRouter(); > > http.route({ > path: "/dodopayments-webhook", > method: "POST", > handler: createDodoWebhookHandler({ > // Handle successful payments > onPaymentSucceeded: async (ctx, payload) => { > console.log("🎉 Payment Succeeded!"); > > // Use Convex context to persist payment data > await ctx.runMutation(internal.webhooks.createPayment, { > paymentId: payload.data.payment_id, > businessId: payload.business_id, > customerEmail: payload.data.customer.email, > amount: payload.data.total_amount, > currency: payload.data.currency, > status: payload.data.status, > webhookPayload: JSON.stringify(payload), > }); > }, > > // Handle subscription activation > onSubscriptionActive: async (ctx, payload) => { > console.log("🎉 Subscription Activated!"); > // Use Convex context to persist subscription data > await ctx.runMutation(internal.webhooks.createSubscription, { > subscriptionId: payload.data.subscription_id, > businessId: payload.business_id, > customerEmail: payload.data.customer.email, > status: payload.data.status, > webhookPayload: JSON.stringify(payload), > }); > }, > // Add other event handlers as needed > }), > }); > > export default http; > ``` > > > [!WARNING] > > > > Define the database mutation that each handler calls. For example, create a `createPayment` mutation to record successful payments, or a `createSubscription` mutation to track subscription state. This example expects them in `convex/webhooks.ts`. > > In the Dodo Payments dashboard, add the endpoint under **Developer → Webhooks**. Convex serves HTTP actions from your deployment's `.convex.site` domain, so the URL is `https://.convex.site/dodopayments-webhook`. ## Checkout Function The Convex component creates checkout sessions, the recommended checkout flow for all payments. A session holds the product cart, customer details, and checkout options. ### Usage Call `checkout` from a Convex action, with the checkout session fields in `payload`: ```typescript theme={null} const result = await checkout(ctx, { payload: { product_cart: [{ product_id: "pdt_123", quantity: 1 }], customer: { email: "user@example.com" }, return_url: "https://example.com/success" } }); ``` `checkout` doesn't call `identify`. To attach an existing customer, pass `customer: { customer_id }` in the payload. For more details and a complete list of supported fields, see [Checkout Sessions](/developer-resources/checkout-session). A session created with `payment_method_id` returns no checkout URL, so `checkout` throws an error for it. ### Response Format The checkout function returns an object with the checkout URL: ```json theme={null} { "checkout_url": "https://checkout.dodopayments.com/session/..." } ``` ## Customer Portal Function The customer portal function returns a Customer Portal URL for the signed-in user. ### Usage ```typescript theme={null} const result = await customerPortal(ctx, { send_email: false }); ``` It returns an object with a `portal_url` field. ### Parameters **send\_email** `boolean` (default: false) If set to `true`, Dodo Payments also emails the portal link to the customer. > [!NOTE] > > `customerPortal` gets the customer from the `identify` function in your DodoPayments setup, which must return the customer's `dodoCustomerId`. If `identify` returns `null`, `customerPortal` throws a `User is not authenticated.` error. ## Webhook Handler `createDodoWebhookHandler` verifies each request before it runs your code: * **Method:** Register the route with `method: "POST"`. Requests with other methods don't reach the handler. * **Signature Verification:** Verifies the Standard Webhooks signature with the `DODO_PAYMENTS_WEBHOOK_SECRET` environment variable. Returns 400 if verification fails. * **Payload Validation:** Validated with Zod. Returns 400 for invalid payloads. * **Error Handling:** * 400: Invalid signature, invalid payload, or an error thrown by one of your handlers * 200: All handlers finished * If `DODO_PAYMENTS_WEBHOOK_SECRET` isn't set, the handler throws an error and the request fails. * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type. ### Supported Webhook Event Handlers Each handler receives the Convex `ActionCtx` and the verified payload for its event type: ```typescript TypeScript expandable theme={null} onPayload?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onPaymentSucceeded?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onPaymentFailed?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onPaymentProcessing?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onPaymentCancelled?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onRefundSucceeded?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onRefundFailed?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onDisputeOpened?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onDisputeExpired?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onDisputeAccepted?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onDisputeCancelled?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onDisputeChallenged?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onDisputeWon?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onDisputeLost?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionActive?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionFailed?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionExpired?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionPaused?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onDunningStarted?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onDunningRecovered?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onCreditAdded?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onCreditDeducted?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onCreditExpired?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onCreditRolledOver?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onCreditOverageCharged?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onCreditOverageReset?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onCreditBalanceLow?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onPayoutCreated?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onPayoutOnHold?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onPayoutInProgress?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onPayoutFailed?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; onPayoutSuccess?: (ctx: GenericActionCtx, payload: WebhookPayload) => Promise; ``` ## Frontend Usage Call the checkout and portal actions from your React components with the `useAction` hook from `convex/react`. ```tsx React Checkout Component expandable theme={null} import { useAction } from "convex/react"; import { api } from "../convex/_generated/api"; export function CheckoutButton() { const createCheckout = useAction(api.payments.createCheckout); const handleCheckout = async () => { try { const { checkout_url } = await createCheckout({ product_cart: [{ product_id: "pdt_123", quantity: 1 }], returnUrl: "https://example.com/success" }); if (!checkout_url) { throw new Error("Missing checkout_url in response"); } window.location.href = checkout_url; } catch (error) { console.error("Failed to create checkout", error); throw new Error("Unable to create checkout. Please try again."); } }; return ; } ``` ```tsx Customer Portal Component expandable theme={null} import { useAction } from "convex/react"; import { api } from "../convex/_generated/api"; export function CustomerPortalButton() { const getPortal = useAction(api.payments.getCustomerPortal); const handlePortal = async () => { try { const { portal_url } = await getPortal({ send_email: false }); if (!portal_url) { throw new Error("Missing portal_url in response"); } window.location.href = portal_url; } catch (error) { console.error("Unable to open customer portal", error); alert("We couldn't open the customer portal. Please try again."); } }; return ; } ``` ## Prompt for LLM Copy this prompt into your AI coding assistant to have it add the component to your project. To give your agent the Dodo Payments docs and skills as well, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ```text expandable theme={null} You are an expert Convex developer assistant. Your task is to guide a user through integrating the @dodopayments/convex component into their existing Convex application. The @dodopayments/convex adapter provides a Convex component for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, built using the official Convex component architecture pattern. First, install the necessary package: npm install @dodopayments/convex Here's how you should structure your response: 1. Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/convex component would you like to integrate into your project? You can choose one or more of the following: - Checkout Function (for handling product checkouts) - Customer Portal Function (for managing customer subscriptions/details) - Webhook Handler (for receiving Dodo Payments webhook events) - All (integrate all three)" 2. Based on the user's selection, provide detailed integration steps for each chosen functionality. If Checkout Function is selected: Purpose: This function handles session-based checkout flows and returns checkout URLs for programmatic handling. Integration Steps: Step 1: Add the component to your Convex configuration. // convex/convex.config.ts import { defineApp } from "convex/server"; import dodopayments from "@dodopayments/convex/convex.config"; const app = defineApp(); app.use(dodopayments); export default app; Step 2: Guide the user to set up environment variables in the Convex dashboard. Instruct them to open the dashboard by running: npx convex dashboard Then add the required environment variables (e.g., DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_ENVIRONMENT, DODO_PAYMENTS_WEBHOOK_SECRET) in **Settings → Environment Variables**. Do not use .env files for backend functions. Step 3: Create an internal query to fetch customers from your database. Note: Ensure the user has appropriate schema defined in their convex/schema.ts file or modify the query to match their existing schema. // convex/customers.ts import { internalQuery } from "./_generated/server"; import { v } from "convex/values"; // Internal query to fetch customer by auth ID export const getByAuthId = internalQuery({ args: { authId: v.string() }, handler: async (ctx, { authId }) => { return await ctx.db .query("customers") .withIndex("by_auth_id", (q) => q.eq("authId", authId)) .first(); }, }); Step 4: Create your payment functions file. // convex/dodo.ts import { DodoPayments, type DodoPaymentsClientConfig } from "@dodopayments/convex"; import { components } from "./_generated/api"; import { internal } from "./_generated/api"; export const dodo = new DodoPayments(components.dodopayments, { // This function maps your Convex user to a Dodo Payments customer // Customize it based on your authentication provider and user database identify: async (ctx) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) { return null; // User is not logged in } // Use ctx.runQuery() to lookup customer from your database const customer = await ctx.runQuery(internal.customers.getByAuthId, { authId: identity.subject, }); if (!customer) { return null; // Customer not found in database } return { dodoCustomerId: customer.dodoCustomerId, // Replace customer.dodoCustomerId with your field storing Dodo Payments customer ID }; }, apiKey: process.env.DODO_PAYMENTS_API_KEY!, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", } as DodoPaymentsClientConfig); // Export the API methods for use in your app export const { checkout, customerPortal } = dodo.api(); Step 5: Create actions that use the checkout function. // convex/payments.ts import { action } from "./_generated/server"; import { v } from "convex/values"; import { checkout } from "./dodo"; // Checkout session with full feature support export const createCheckout = action({ args: { product_cart: v.array(v.object({ product_id: v.string(), quantity: v.number(), })), returnUrl: v.optional(v.string()), }, handler: async (ctx, args) => { return await checkout(ctx, { payload: { product_cart: args.product_cart, return_url: args.returnUrl, billing_currency: "USD", feature_flags: { allow_discount_code: true, }, }, }); }, }); Step 6: Use in your frontend. // Your frontend component import { useAction } from "convex/react"; import { api } from "../convex/_generated/api"; export function CheckoutButton() { const createCheckout = useAction(api.payments.createCheckout); const handleCheckout = async () => { const { checkout_url } = await createCheckout({ product_cart: [{ product_id: "pdt_123", quantity: 1 }], }); window.location.href = checkout_url; }; return ; } Configuration Details: - `checkout()`: Checkout session with full feature support using session checkout. - Returns: `{"checkout_url": "https://checkout.dodopayments.com/..."}` For complete API documentation, refer to: - Checkout Sessions: https://docs.dodopayments.com/developer-resources/checkout-session - Create Checkout Session API: https://docs.dodopayments.com/api-reference/checkout-sessions/create If Customer Portal Function is selected: Purpose: This function allows customers to manage their subscriptions and payment methods. The customer is automatically identified via the `identify` function. Integration Steps: Follow Steps 1-4 from the Checkout Function section, then: Step 5: Create a customer portal action. // convex/payments.ts (add to existing file) import { action } from "./_generated/server"; import { v } from "convex/values"; import { customerPortal } from "./dodo"; export const getCustomerPortal = action({ args: { send_email: v.optional(v.boolean()), }, handler: async (ctx, args) => { try { const portal = await customerPortal(ctx, args); if (!portal?.portal_url) { throw new Error("Customer portal did not return a portal_url"); } return portal; } catch (error) { console.error("Failed to generate customer portal link", error); throw new Error("Unable to generate customer portal link. Please retry."); } }, }); Step 6: Use in your frontend. // Your frontend component import { useAction } from "convex/react"; import { api } from "../convex/_generated/api"; export function CustomerPortalButton() { const getPortal = useAction(api.payments.getCustomerPortal); const handlePortal = async () => { const { portal_url } = await getPortal({ send_email: false }); window.location.href = portal_url; }; return ; } Configuration Details: - Requires authenticated user (via `identify` function). - Customer identification is handled automatically by the `identify` function. - `send_email`: Optional boolean to send portal link via email. If Webhook Handler is selected: Purpose: This handler processes incoming webhook events from Dodo Payments, allowing your application to react to events like successful payments or subscription changes. Integration Steps: Step 1: Add the webhook secret to your environment variables in the Convex dashboard. Guide the user to open the Convex dashboard by running: npx convex dashboard In the dashboard, go to **Settings → Environment Variables** and add: - `DODO_PAYMENTS_WEBHOOK_SECRET=whsec_...` Do not use .env files for backend functions; always set secrets in the Convex dashboard. The webhook handler reads this exact variable name. Step 2: Create a file `convex/http.ts`: // convex/http.ts import { createDodoWebhookHandler } from "@dodopayments/convex"; import { httpRouter } from "convex/server"; import { internal } from "./_generated/api"; const http = httpRouter(); http.route({ path: "/dodopayments-webhook", method: "POST", handler: createDodoWebhookHandler({ // Handle successful payments onPaymentSucceeded: async (ctx, payload) => { console.log("🎉 Payment Succeeded!"); // Use Convex context to persist payment data await ctx.runMutation(internal.webhooks.createPayment, { paymentId: payload.data.payment_id, businessId: payload.business_id, customerEmail: payload.data.customer.email, amount: payload.data.total_amount, currency: payload.data.currency, status: payload.data.status, webhookPayload: JSON.stringify(payload), }); }, // Handle subscription activation onSubscriptionActive: async (ctx, payload) => { console.log("🎉 Subscription Activated!"); // Use Convex context to persist subscription data await ctx.runMutation(internal.webhooks.createSubscription, { subscriptionId: payload.data.subscription_id, businessId: payload.business_id, customerEmail: payload.data.customer.email, status: payload.data.status, webhookPayload: JSON.stringify(payload), }); }, // Add other event handlers as needed }), }); export default http; Note: Make sure to define the corresponding database mutations in your Convex backend for each webhook event you want to handle. For example, create a `createPayment` mutation to record successful payments or a `createSubscription` mutation to manage subscription state. Now, you can set the webhook endpoint URL in your Dodo Payments dashboard to `https://.convex.site/dodopayments-webhook`. Convex serves HTTP actions from the deployment's .convex.site domain, not .convex.cloud. Environment Variable Setup: Set up the following environment variables in your Convex dashboard if you haven't already (Settings → Environment Variables): - `DODO_PAYMENTS_API_KEY` - Your Dodo Payments API key - `DODO_PAYMENTS_ENVIRONMENT` - Set to `test_mode` or `live_mode` - `DODO_PAYMENTS_WEBHOOK_SECRET` - Your webhook secret (required for webhook handling) Usage in your component configuration: apiKey: process.env.DODO_PAYMENTS_API_KEY environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode" Important: Never commit sensitive environment variables directly into your code. Always use Convex environment variables for all sensitive information. If the user needs assistance setting up environment variables or deployment, ask them about their specific setup and provide guidance accordingly. Run `npx convex dev` after setting up the component to generate the necessary types. ``` # Sync with Your Database Source: https://docs.dodopayments.com/developer-resources/dodo-sync Automatically sync your Dodo Payments data to your own database for analytics, reporting, and integrations. Sync your Dodo Payments data to your own database for analytics, reporting, and integrations. The sync engine automatically replicates **payments**, **customers**, **subscriptions**, and **licenses** to MongoDB, PostgreSQL, MySQL, or ClickHouse. > [!NOTE] > > **Package**: [dodo-sync on npm](https://www.npmjs.com/package/dodo-sync) | **Source**: [GitHub](https://github.com/dodopayments/dodo-sync) ## What Can You Sync? Choose any combination of these entities: > [card] Payments > > All payment transactions, including one-time payments, refunds, and status updates. > [card] Customers > > Customer profiles, contact information, and metadata. > [card] Subscriptions > > Subscription data, billing cycles, and status changes. > [card] Licenses > > License keys, activations, and status updates. Specify which entities to sync using the `scopes` parameter. Each run fetches every record in the selected scopes and writes it by ID, so existing rows are updated in place instead of duplicated. Each page of records is written to your database in a single batch. ## Database Support Dodo Sync supports **MongoDB**, **PostgreSQL**, **MySQL** 8.0.20 or later, and **ClickHouse**. Support for Snowflake and other databases, ETL pipelines, and realtime sync is in development. To contribute a new database integration, submit a pull request to the [GitHub repository](https://github.com/dodopayments/dodo-sync). ## Getting Started Use Dodo Sync via the **CLI** for quick setup or programmatically in your code for integration into your application. Both methods provide the same functionality. ### Using the CLI Install the CLI globally to run it from anywhere: ```bash npm theme={null} npm install -g dodo-sync ``` ```bash bun theme={null} bun add -g dodo-sync ``` #### Running the CLI The CLI supports two modes: **interactive** for guided setup, and **manual** for direct configuration. **Interactive mode**: Run without arguments to start the setup wizard. ```bash theme={null} dodo-sync ``` **Manual mode**: Pass arguments directly to skip the wizard. ```bash theme={null} dodo-sync -i [interval] -d [database] -u [database_uri] --scopes [scopes] --api-key [api_key] --env [environment] ``` Examples: ```bash theme={null} # MongoDB dodo-sync -i 600 -d mongodb -u mongodb://mymongodb.url --scopes "licences,payments,customers,subscriptions" --api-key dodo_test_... --env test_mode # PostgreSQL dodo-sync -i 600 -d postgres -u postgresql://user:password@localhost:5432/mydb --scopes "licences,payments,customers,subscriptions" --api-key dodo_test_... --env test_mode # MySQL dodo-sync -i 600 -d mysql -u mysql://user:password@localhost:3306/mydb --scopes "licences,payments,customers,subscriptions" --api-key dodo_test_... --env test_mode # ClickHouse dodo-sync -i 600 -d clickhouse -u http://localhost:8123 --scopes "licences,payments,customers,subscriptions" --api-key dodo_test_... --env test_mode ``` #### CLI Arguments **--interval** `number` *required* Sync interval in seconds. The CLI runs continuously at this interval. For a one-time sync, use [`.run()` in your code](#manual-sync). **--database** `string` *required* Database type: `"mongodb"`, `"postgres"`, `"mysql"`, or `"clickhouse"`. **--database-uri** `string` *required* Connection URI for your database: * **MongoDB**: `mongodb://localhost:27017` or `mongodb+srv://user:pass@cluster.mongodb.net/` * **PostgreSQL**: `postgresql://user:password@localhost:5432/mydb` * **MySQL**: `mysql://user:password@localhost:3306/mydb` * **ClickHouse**: `http://localhost:8123` **--scopes** `string` *required* Comma-separated list of entities to sync: `licences`, `payments`, `customers`, `subscriptions`. Example: `"payments,customers"`. **--api-key** `string` *required* Your Dodo Payments API key from **Developer → API Keys**. Use a key from the same mode as `--env`. **--env** `string` *required* Environment: `"live_mode"` or `"test_mode"`. **--rate-limit** `number` Rate limit in requests per second. Controls how fast the sync engine makes API requests. Defaults to `10`; values of `100` or more turn off throttling. ### Using in Your Code Integrate the sync feature directly into your application. Install it as a dependency: ```bash npm theme={null} npm install dodo-sync ``` ```bash bun theme={null} bun add dodo-sync ``` #### Automatic Sync (Interval-based) Run the sync continuously at regular intervals: ```typescript theme={null} import { DodoSync } from 'dodo-sync'; const syncDodoPayments = new DodoSync({ interval: 60, // Sync every 60 seconds database: 'mongodb', databaseURI: process.env.MONGODB_URI, // e.g., 'mongodb://localhost:27017' scopes: ['licences', 'payments', 'customers', 'subscriptions'], dodoPaymentsOptions: { bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode' // or 'live_mode' } }); // Initialize connection await syncDodoPayments.init(); // Start the sync loop syncDodoPayments.start(); ``` > [!TIP] > > The `interval` option is required when using `.start()`. The sync runs continuously at the specified interval until the process stops. #### Manual Sync Trigger sync operations on-demand, such as from a cron job, an API endpoint, or a serverless function: ```typescript expandable theme={null} import { DodoSync } from 'dodo-sync'; const syncDodoPayments = new DodoSync({ database: 'mongodb', databaseURI: process.env.MONGODB_URI, scopes: ['licences', 'payments', 'customers', 'subscriptions'], dodoPaymentsOptions: { bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode' } }); try { // Initialize connection await syncDodoPayments.init(); // Trigger a single sync operation await syncDodoPayments.run(); } finally { // Close the database connection await syncDodoPayments.disconnect(); } ``` > [!TIP] > > The `interval` option is not required for manual sync. Call `.run()` whenever you need to sync. `.run()` resolves only after every database write has finished. `.close()` is an alias for `.disconnect()`. #### Running on Serverless On Vercel, AWS Lambda, or similar platforms: * Call `.disconnect()` in a `finally` block, as in the example above, so connections don't stay open between invocations. * Use the Node.js runtime. Edge runtimes can't open database connections. * Raise the function timeout. A large sync can take longer than the default limit. On Vercel, set `export const maxDuration = 60;`. * Sync fewer scopes per invocation, such as `scopes: ['payments']`, to keep each run short. #### PostgreSQL Example ```typescript theme={null} import { DodoSync } from 'dodo-sync'; const syncDodoPayments = new DodoSync({ interval: 60, database: 'postgres', databaseURI: process.env.POSTGRES_URI, // e.g., 'postgresql://user:password@localhost:5432/mydb' scopes: ['licences', 'payments', 'customers', 'subscriptions'], dodoPaymentsOptions: { bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode' } }); await syncDodoPayments.init(); syncDodoPayments.start(); ``` #### MySQL Example ```typescript theme={null} import { DodoSync } from 'dodo-sync'; const syncDodoPayments = new DodoSync({ interval: 60, database: 'mysql', databaseURI: process.env.MYSQL_URI, // e.g., 'mysql://user:password@localhost:3306/mydb' scopes: ['licences', 'payments', 'customers', 'subscriptions'], dodoPaymentsOptions: { bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode' } }); await syncDodoPayments.init(); syncDodoPayments.start(); ``` #### ClickHouse Example ```typescript theme={null} import { DodoSync } from 'dodo-sync'; const syncDodoPayments = new DodoSync({ interval: 60, database: 'clickhouse', databaseURI: process.env.CLICKHOUSE_URI, // e.g., 'http://localhost:8123' scopes: ['licences', 'payments', 'customers', 'subscriptions'], dodoPaymentsOptions: { bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode' } }); await syncDodoPayments.init(); syncDodoPayments.start(); ``` #### Constructor Options **database** `string` *required* Database type: `"mongodb"`, `"postgres"`, `"mysql"`, or `"clickhouse"`. **databaseURI** `string` *required* Connection string for your database: * **MongoDB**: `mongodb://localhost:27017` or `mongodb+srv://...` * **PostgreSQL**: `postgresql://user:password@localhost:5432/mydb` * **MySQL**: `mysql://user:password@localhost:3306/mydb` * **ClickHouse**: `http://localhost:8123` **scopes** `string[]` *required* Array of entities to sync: `"licences"`, `"payments"`, `"customers"`, `"subscriptions"`. Include any combination. **dodoPaymentsOptions** `object` *required* Dodo Payments API configuration. See the [TypeScript SDK types](https://github.com/dodopayments/dodopayments-typescript/blob/main/src/client.ts) for complete options. **Required properties:** * `bearerToken`: Your Dodo Payments API key * `environment`: `"test_mode"` or `"live_mode"` **interval** `number` Time in seconds between automatic syncs. Required for `.start()`, optional for `.run()`. **rateLimit** `number` Rate limit in requests per second. Defaults to `10`; values of `100` or more turn off throttling. ## Important Information > [!WARNING] > > **MongoDB**: Collections (`subscriptions`, `payments`, `licences`, `customers`) are created in the database named in your connection URI, such as `mongodb://localhost:27017/my_database`. If the URI names no database, Dodo Sync uses `dodopayments_sync`. > > **PostgreSQL**: Tables (`Subscriptions`, `Payments`, `Licenses`, `Customers`) are created in the database specified in your connection URI. Data is stored as JSONB. > > **MySQL**: Requires MySQL 8.0.20 or later. Tables (`Subscriptions`, `Payments`, `Licenses`, `Customers`) are created in the database specified in your connection URI. Data is stored as JSON. > > **ClickHouse**: Tables (`Subscriptions`, `Payments`, `Licenses`, `Customers`) are created using the ReplacingMergeTree engine. When querying, use the `FINAL` keyword to ensure deduplicated results. ## Upgrading from 0.x Version 1.0 changes how MongoDB data is stored and raises the MySQL requirement. Before upgrading: * **MongoDB**: Drop your existing `licences` collection. License documents are now stored by license `id` instead of `subscription_id`, and the next sync repopulates the collection. * **MongoDB**: Check your connection URI. Data is now written to the database the URI names, not always `dodopayments_sync`. To keep using your existing data, put `dodopayments_sync` in the URI or leave the database out. * **MySQL**: Upgrade to MySQL 8.0.20 or later. ## Additional Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodo-sync) > > View source code, report issues, or contribute improvements > [card] [npm Package](https://www.npmjs.com/package/dodo-sync) > > View package details and installation instructions # Dynamic Pricing Checkout with Pay What You Want Source: https://docs.dodopayments.com/developer-resources/dynamic-pricing-checkout Create checkout sessions with variable pricing using Pay What You Want. Set a minimum price, pass dynamic amounts via API, or let customers choose their price. Pay What You Want (PWYW) lets you offer variable pricing for a single product without creating multiple product entries. You set a minimum price in the dashboard, then pass dynamic amounts when creating checkout sessions, or let customers choose their price. This approach works for: * Variable pricing without managing multiple products * Customer-driven pricing where buyers choose their amount * Programmatic price control where you set the amount via API * Flexible pricing models for digital products, donations, or experimental launches > [!WARNING] > > Pay What You Want is only available for one-time payment products. It cannot be used with subscriptions. The product's base currency must be USD, GBP, or EUR. ## Prerequisites * A one-time payment product with Pay What You Want enabled in the dashboard * The product ID (e.g., `pdt_123abc456def`) * An API key from **Developer → API Keys** ## Enable Pay What You Want on a Product In the Dodo Payments dashboard: **1. Go to Products** Navigate to **Products** and select the one-time payment product you want to configure. **2. Enable Pay What You Want** In the **Pricing** section, toggle **Pay What You Want** on. **3. Set the minimum price** Enter the **Minimum Price** customers must pay. This is required. **4. Set a suggested price (optional)** Optionally set a **Suggested Price** to guide customers. There is no maximum price setting. To cap the amount you charge, enforce the cap in your own code before you create the session. **5. Save** Click **Update Product** and note your product ID for use in checkout sessions. > [!TIP] > > You can find your product ID in the dashboard under **Products** → **View Details**, or by using the [List Products API](/api-reference/products/get-products). ## Create a Checkout Session with a Fixed Amount When you pass an `amount` in the product cart, the checkout uses that exact amount as the unit price, as long as it's at or above the product's minimum price. The `amount` field uses the smallest currency unit: cents for USD, pence for GBP, cents for EUR. For example, `1500` = \$15.00 or €15.00. ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, }); const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123abc456def', quantity: 1, amount: 1500, // $15.00 in cents } ], return_url: 'https://yoursite.com/success', metadata: { pricing_tier: 'custom' } }); console.log('Checkout URL:', session.checkout_url); ``` ```python Python theme={null} import os from dodopayments import DodoPayments client = DodoPayments( bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), ) session = client.checkout_sessions.create( product_cart=[ { "product_id": "pdt_123abc456def", "quantity": 1, "amount": 1500, # $15.00 in cents } ], return_url="https://yoursite.com/success", metadata={ "pricing_tier": "custom" } ) print(f"Checkout URL: {session.checkout_url}") ``` ```bash cURL theme={null} curl -X POST https://test.dodopayments.com/checkouts \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "product_cart": [ { "product_id": "pdt_123abc456def", "quantity": 1, "amount": 1500 } ], "return_url": "https://yoursite.com/success" }' ``` > [!NOTE] > > The `amount` field is ignored for products without Pay What You Want enabled. It only applies to one-time payments. ## Let Customers Choose Their Price Omit the `amount` field to show a price input on checkout. Customers can enter any amount at or above your product's minimum price. ```typescript TypeScript theme={null} const session = await client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123abc456def', quantity: 1, // No amount field — customer chooses } ], return_url: 'https://yoursite.com/success', }); ``` ```python Python theme={null} session = client.checkout_sessions.create( product_cart=[ { "product_id": "pdt_123abc456def", "quantity": 1, # No amount field — customer chooses } ], return_url="https://yoursite.com/success", ) ``` ```bash cURL theme={null} curl -X POST https://test.dodopayments.com/checkouts \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "product_cart": [ { "product_id": "pdt_123abc456def", "quantity": 1 } ], "return_url": "https://yoursite.com/success" }' ``` ## Use Payment Links with Dynamic Amounts Static payment links for Pay What You Want products accept a `paymentAmount` query parameter that fixes the amount charged. Unlike the Checkout Sessions API, this parameter uses major currency units (e.g., `12.5` for \$12.50). ```text theme={null} https://checkout.dodopayments.com/buy/pdt_123abc456def?paymentAmount=15.00 ``` > [!WARNING] > > `paymentAmount` uses major currency units (`15.00` is \$15.00). The Checkout Sessions API field `product_cart[].amount` uses the smallest currency unit (`1500` is \$15.00). See the [Integration Guide](/developer-resources/integration-guide#static-payment-links) for more details. ## Common Patterns ### Tiered Pricing by Customer Segment Charge different amounts to different customer types using the same product: ```typescript theme={null} async function createCheckoutForSegment(segment: string) { const amounts: Record = { student: 1000, // $10.00 regular: 2500, // $25.00 premium: 5000, // $50.00 }; return client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123abc456def', quantity: 1, amount: amounts[segment], } ], return_url: 'https://yoursite.com/success', metadata: { segment }, }); } ``` ### Quantity-Based Pricing Adjust the unit price based on quantity purchased. The `amount` is a per-unit price, and the total is `amount` × `quantity`: ```typescript theme={null} async function createCheckoutWithQuantity(quantity: number) { const basePrice = 2000; // $20.00 per unit let discount = 0; if (quantity >= 5) { discount = 0.20; // 20% off } else if (quantity >= 2) { discount = 0.10; // 10% off } const unitAmount = Math.round(basePrice * (1 - discount)); return client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123abc456def', quantity, amount: unitAmount, // Charged per unit } ], return_url: 'https://yoursite.com/success', }); } ``` ### Promotional Pricing Apply time-limited pricing: ```typescript theme={null} async function createCheckoutWithPromo() { const isPromoActive = checkIfPromotionActive(); // Your logic const regularPrice = 3000; // $30.00 const promoPrice = 2000; // $20.00 return client.checkoutSessions.create({ product_cart: [ { product_id: 'pdt_123abc456def', quantity: 1, amount: isPromoActive ? promoPrice : regularPrice, } ], return_url: 'https://yoursite.com/success', metadata: { pricing_type: isPromoActive ? 'promotional' : 'regular', }, }); } ``` Use metadata to track why specific amounts were chosen (e.g., `pricing_tier`, `discount_code`, `user_segment`). This helps you analyze pricing patterns and customer behavior. ## Validate Amounts Check that the amount is at or above your product's minimum price before you create a checkout session. `maxAmount` is your own business cap; Dodo Payments has no maximum price setting. ```typescript TypeScript theme={null} async function createValidatedCheckout( productId: string, amountInCents: number, minAmount: number, maxAmount: number | null ) { if (amountInCents < minAmount) { throw new Error( `Amount ${amountInCents} is below minimum ${minAmount}` ); } if (maxAmount !== null && amountInCents > maxAmount) { throw new Error( `Amount ${amountInCents} exceeds maximum ${maxAmount}` ); } return client.checkoutSessions.create({ product_cart: [ { product_id: productId, quantity: 1, amount: amountInCents, } ], return_url: 'https://yoursite.com/success', }); } ``` ```python Python theme={null} def create_validated_checkout( product_id: str, amount_in_cents: int, min_amount: int, max_amount: int | None ): if amount_in_cents < min_amount: raise ValueError( f"Amount {amount_in_cents} is below minimum {min_amount}" ) if max_amount is not None and amount_in_cents > max_amount: raise ValueError( f"Amount {amount_in_cents} exceeds maximum {max_amount}" ) return client.checkout_sessions.create( product_cart=[ { "product_id": product_id, "quantity": 1, "amount": amount_in_cents, } ], return_url="https://yoursite.com/success", ) ``` ## Troubleshooting > [accordion] Amount is being ignored > > Verify that: > > * The product has Pay What You Want enabled in the dashboard > * The product is a one-time payment product, not a subscription > * The amount is in the correct format (smallest currency unit: cents for USD, pence for GBP, cents for EUR) > [accordion] Amount is below the minimum price > > The API rejects checkout sessions where the amount is below your product's minimum price. Validate amounts before creating sessions, or omit the `amount` field to let customers choose. > [accordion] Customer can't enter their own price > > If the price input field doesn't appear, ensure you've omitted the `amount` field from the product cart. When `amount` is provided, the checkout uses that exact amount. > [card] [Checkout Sessions API](/api-reference/checkout-sessions/create) > > Complete API reference for checkout sessions. > [card] [Checkout Sessions Guide](/developer-resources/checkout-session) > > Explore advanced checkout session features and customization options. > [card] [Pay What You Want Feature](/features/pay-what-you-want) > > Learn more about the Pay What You Want pricing model. # Expo Boilerplate Source: https://docs.dodopayments.com/developer-resources/expo-boilerplate Start an Expo and React Native app that sells a subscription with Dodo Payments hosted checkout, a demo Express backend, and deep-link payment results. > [card] [GitHub Repository](https://github.com/dodopayments/expo-boilerplate) > > The Expo, React Native, and Dodo Payments boilerplate. ## Overview The Expo boilerplate is a working Expo app that sells a subscription plan through Dodo Payments hosted checkout. It has two parts: an Expo Router app in TypeScript, and a small Express server in `server/` that creates checkout sessions with your API key. The app asks the server for a checkout URL, opens it in the system browser with `expo-web-browser`, and receives the result through a deep link. > [!NOTE] > > The boilerplate uses Expo SDK 54, Expo Router, and TypeScript. The API key stays on the server. The app only knows the server's URL. [Expo Boilerplate Demo | Dodo Payments](https://www.youtube.com/embed/78N1qw14m0Y) ## Prerequisites * Node.js 18 or later. * Expo CLI or EAS CLI. * A Dodo Payments account with a product. Create the product under **Products** in the dashboard. * An iOS Simulator, an Android Emulator, or a physical device. ## Quick Start **1. Clone the Repository** Clone the boilerplate repository and go to the project directory: ```bash theme={null} git clone https://github.com/dodopayments/expo-boilerplate.git cd expo-boilerplate ``` **2. Get Your API Credentials** Get your API key from the Dodo Payments dashboard in test mode: * **API Key**: Go to **Developer → API Keys** in your [dashboard](https://app.dodopayments.com). > [!TIP] > > Build in test mode, which simulates payments without moving real money. **3. Configure Environment Variables** The app and the server each read their own `.env` file. Copy both example files: ```bash theme={null} cp .env.example .env cp server/.env.example server/.env ``` In `server/.env`, add your API key. `DODOPAYMENTS_RETURN_URL` must use the `scheme` from `app.json`, which is `dodoexpo` in the boilerplate: ```bash server/.env theme={null} DODOPAYMENTS_API_KEY=dodo_test_... DODOPAYMENTS_ENVIRONMENT=test_mode DODOPAYMENTS_RETURN_URL=dodoexpo://payment/result PORT=3000 ``` In the root `.env`, set `EXPO_PUBLIC_BACKEND_URL` to the server's URL, for example `http://localhost:3000`. The app sends checkout requests to `EXPO_PUBLIC_BACKEND_URL/checkout`. Then open `server/server.js` and replace `your-product-id` with the ID of your product. Product IDs start with `pdt_`. > [!WARNING] > > Never commit your `.env` files to version control. The root `.gitignore` already excludes `.env`. > > Never put a Dodo Payments API key in an `EXPO_PUBLIC_*` variable. Expo embeds these variables in the JavaScript bundle, so anyone who downloads your app can read them. Keep the key on your server, as the boilerplate does, and pass only the resulting `checkout_url` to the app. See [Mobile Integration](/developer-resources/mobile-integration). **4. Install Dependencies** Install the packages for the app and for the server: ```bash theme={null} npm install cd server && npm install && cd .. ``` **5. Start the Development Server** Start the backend in one terminal, then start Expo in a second terminal: ```bash theme={null} # Terminal 1: the checkout server cd server && npm run dev # Terminal 2: the Expo app npx expo start ``` Press `i` for the iOS Simulator or `a` for the Android Emulator, or scan the QR code on your device. The project includes `expo-dev-client`, and the `dodoexpo://` return link needs your app's own scheme, so run the app in a development build (`npx expo run:ios` or `npx expo run:android`) rather than Expo Go. A physical device can't reach `localhost` on your computer. To test on a device, set `EXPO_PUBLIC_BACKEND_URL` to your computer's local network address, for example `http://192.168.1.10:3000`. > [!TIP] > > The home screen shows a plan card with a checkout button. Tap it to open checkout, pay with the test card `4242 4242 4242 4242`, and the app opens its payment result screen. ## What's Included The boilerplate includes: > [card] Checkout Integration > > A demo server that creates checkout sessions, and an app service that requests and opens them. > [card] Payment Handling > > A result screen that reads the `status` from the `dodoexpo://payment/result` deep link and shows success or failure. > [card] TypeScript Support > > TypeScript configuration with types for the checkout request and response. > [card] Expo Router > > File-based navigation with Expo Router, including a tab layout and the payment result route. ## Project Structure These are the main files in the repository: ``` expo-boilerplate/ ├── app/ │ ├── (tabs)/ │ │ ├── index.tsx # Home screen with the plan card and checkout button │ │ └── profile.tsx │ ├── payment/ │ │ └── result.tsx # Payment result screen (deep-link target) │ └── _layout.tsx # Root layout and deep-link handling ├── components/ │ └── payments/ # PaymentButton, ProductCard, and related UI ├── config/ │ ├── env.ts # Reads EXPO_PUBLIC_BACKEND_URL │ └── product.ts # Plan name, price text, and features ├── services/ │ └── dodo-payments.ts # Requests a checkout URL and opens it ├── types/ │ └── dodo-payments.ts # Checkout types ├── server/ # Demo Express server that creates checkout sessions │ ├── server.js │ └── .env.example ├── .env.example # App environment variables template ├── app.json # App name, scheme, and bundle identifiers └── package.json ``` ## Next Steps After the boilerplate runs: **1. Create Your Products** Add products in your [Dodo Payments dashboard](https://app.dodopayments.com), and use their IDs in `server/server.js`. **2. Customize the Integration** Change the plan text in `config/product.ts`, and change the app name, `scheme`, and bundle identifiers in `app.json`. If you change the `scheme`, update `DODOPAYMENTS_RETURN_URL` to match. **3. Test on Real Devices** Test the payment flow and the deep-link return on physical iOS and Android devices. **4. Go Live** Replace the demo server with your own backend that authenticates users and grants access from webhooks. Then switch to a live mode API key and build your app for production. ## Building for Production Build store-ready binaries with EAS Build: **1. Install EAS CLI** ```bash theme={null} npm install -g eas-cli ``` **2. Configure EAS** The repository has no `eas.json`. This command creates one: ```bash theme={null} eas build:configure ``` **3. Build Your App** For iOS: ```bash theme={null} eas build --platform ios ``` For Android: ```bash theme={null} eas build --platform android ``` ## Additional Resources > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > The mobile checkout SDKs, deep-link setup, and mobile checkout settings. > [card] [Integration Guide](/developer-resources/integration-guide) > > Checkout sessions, payment links, and webhooks. > [card] [API Reference](/api-reference/introduction) > > Every Dodo Payments API endpoint. ## Support For help with the boilerplate: * Ask questions in the [Discord community](https://discord.gg/bYqAp4ayYh). * Report issues in the [GitHub repository](https://github.com/dodopayments/expo-boilerplate). * Email the [support team](mailto:support@dodopayments.com). # Express Adaptor Source: https://docs.dodopayments.com/developer-resources/express-adaptor Add Dodo Payments checkout, Customer Portal, and webhook route handlers to an Express app with the @dodopayments/express adaptor. The `@dodopayments/express` adaptor gives your Express app three route handlers: `checkoutHandler` returns checkout URLs, `CustomerPortal` sends a customer to the Customer Portal, and `Webhooks` verifies webhook requests and calls your event handlers. > [card] [Checkout Handler](#checkout-route-handler) > > Create payment links and checkout sessions from your Express app. > [card] [Customer Portal](#customer-portal-route-handler) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-route-handler) > > Verify and process Dodo Payments webhook events. ## Installation **1. Install the Package** Run the following command in your project root: ```bash theme={null} npm install @dodopayments/express ``` **2. Set Up Environment Variables** Create a `.env` file in your project root: ```env expandable theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret # test_mode or live_mode DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_RETURN_URL=https://yourapp.com/success ``` Create the API key under **Developer → API Keys**. Add your webhook endpoint under **Developer → Webhooks** and copy its signing secret into `DODO_PAYMENTS_WEBHOOK_KEY`. While you build, use a test mode API key with `DODO_PAYMENTS_ENVIRONMENT=test_mode`, because a test mode key works only against test mode. `DODO_PAYMENTS_RETURN_URL` is optional. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## Route Handler Examples > [!NOTE] > > The examples register routes on an Express app created with `express()`. The POST checkout handlers and the webhook handler read `req.body`, so each example registers `express.json()` before its routes. > [tab] Checkout Handler > > > [!NOTE] > > > > Use this handler to integrate Dodo Payments checkout into your Express app. Supports static (GET) and checkout session (POST) flows. > > ```typescript Express Route Handler expandable theme={null} > import express from 'express'; > import { checkoutHandler } from '@dodopayments/express'; > > const app = express(); > app.use(express.json()); > > app.get('/api/checkout', checkoutHandler({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > type: "static" > })) > > app.post('/api/checkout-session', checkoutHandler({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > type: "session" > })) > ``` > > ```bash Static Checkout cURL theme={null} > curl --request GET \ > --url 'https://example.com/api/checkout?productId=pdt_fqJhl7pxKWiLhwQR042rh' > ``` > > ```bash Checkout Session cURL expandable theme={null} > curl --request POST \ > --url https://example.com/api/checkout-session \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_QMDuvLkbVzCRWRQjLNcs", > "quantity": 1 > } > ], > "customer": { > "email": "test@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal Handler > > > [!NOTE] > > > > Use this handler to let customers manage their subscriptions and details in the Dodo Payments Customer Portal. > > ```typescript Express Route Handler expandable theme={null} > import express from 'express'; > import { CustomerPortal } from "@dodopayments/express"; > > const app = express(); > > app.get('/api/customer-portal', CustomerPortal({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > })) > ``` > > ```bash Customer Portal cURL theme={null} > curl --request GET \ > --url 'https://example.com/api/customer-portal?customer_id=cus_9VuW4K7O3GHwasENg31m&send_email=true' > ``` > [tab] Webhook Handler > > > [!NOTE] > > > > Use this handler to receive, verify, and process Dodo Payments webhook events in your Express app. > > ```typescript Express Route Handler expandable theme={null} > import express from 'express'; > import { Webhooks } from "@dodopayments/express"; > > const app = express(); > app.use(express.json()); > > app.post('/api/webhooks', Webhooks({ > webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, > onPayload: async (payload) => { > // handle the payload > }, > // ... other event handlers for granular control > })) > ``` ## Checkout Route Handler > [!NOTE] > > The adaptor supports all three Dodo Payments checkout flows. Set `type` in the handler config to choose the flow a route serves. Every flow responds with JSON that contains a `checkout_url` for the customer to open. * **Static Payment Links:** `type: "static"`, GET. Builds a payment link for one product from query parameters, after checking that the product exists. * **Dynamic Payment Links (deprecated):** `type: "dynamic"`, POST. Creates a one-time payment or a subscription with a payment link, depending on whether the product is recurring. * **Checkout Sessions:** `type: "session"`, POST. Creates a checkout session from a product cart and customer details. Use this flow for new integrations. `checkoutHandler` takes these options: | Option | Type | Description | | - | - | - | | `bearerToken` | `string` | Your Dodo Payments API key. | | `environment` | `string` | `test_mode` or `live_mode`. Defaults to `live_mode`. | | `returnUrl` | `string` | Optional. The URL that checkout redirects the customer to after payment. A `return_url` in a POST body takes precedence. | | `type` | `string` | The checkout flow: `static`, `dynamic`, or `session`. | Register the handler for GET when `type` is `static`, and for POST when `type` is `dynamic` or `session`. The handler returns 405 for other methods. > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_nZuwz45WAs64n3l07zpQR`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's street address. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's postal or ZIP code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > The payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed to checkout as metadata, for example `metadata_orderId=123`. > > A disable flag takes effect only when it's `true` and the matching field has a value, for example `email` with `disableEmail`. The handler passes these parameters to a [static payment link](/developer-resources/integration-guide#static-payment-links). > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters, or a product that doesn't exist in your account, also result in a 400 response. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_fqJhl7pxKWiLhwQR042rh?quantity=1&redirect_url=https%3A%2F%2Fyourapp.com%2Fsuccess" > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. The handler retrieves the product, then creates a subscription if the product is recurring and a one-time payment otherwise. > * The body needs `billing` (with `street`, `city`, `state`, `country`, and `zipcode`) and `customer`, plus `product_id` (with an optional `quantity`) or `product_cart`. Subscriptions need `product_id`. > * The handler also forwards `metadata`, `allowed_payment_method_types`, `billing_currency`, `discount_codes` (or the deprecated `discount_code`), `return_url`, `show_saved_payment_methods`, and `tax_id`. For subscriptions, it forwards `addons`, `on_demand`, and `trial_period_days` too. It ignores other fields. > * For field details, refer to: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic Checkout calls the deprecated `POST /payments` and `POST /subscriptions` endpoints. Use Checkout Sessions for new integrations. > > ### Response Format > > Dynamic checkout returns a JSON response with the payment link as the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/cbq" > } > ``` > [accordion] Checkout Sessions (POST) > > Send a checkout session payload as the JSON body. The handler creates a checkout session, which handles the complete payment flow for one-time purchases and subscriptions, and returns its `checkout_url`. `product_cart` is required and must contain at least one product. > > Each `checkout_url` works once and expires after 24 hours, or after 15 minutes when you pass `confirm: true`. A session created with `payment_method_id` returns no `checkout_url`, so the handler responds with 400. > > Refer to [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session) for more details and a complete list of supported fields. > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa" > } > ``` ## Customer Portal Route Handler The Customer Portal Route Handler creates a Customer Portal session for the customer in `customer_id` and redirects the request to the portal link. `CustomerPortal` takes the `bearerToken` and `environment` options, the same as `checkoutHandler`. If Dodo Payments can't create the session, the handler returns 500. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, sends an email to the customer with the portal link. > [!WARNING] > > Returns 400 if `customer_id` is missing. The handler doesn't authenticate the request and opens the portal for any `customer_id` it receives, so put the route behind your own authentication and pass only the signed-in user's customer ID. ## Webhook Route Handler The webhook handler verifies each request with your webhook secret, passed as `webhookKey`, then calls your event handlers. > [!WARNING] > > Register `express.json()` before the webhook route. The handler verifies the signature against `req.body`, so it rejects every request unless the body is parsed JSON. Don't use `express.raw()` for this route. * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`, following the [Standard Webhooks](https://standardwebhooks.com/) specification. Returns 401 if verification fails. * **Payload Validation:** Validated with Zod. Returns 400 for invalid payloads. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Internal error during verification * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200 when they finish. The handler doesn't catch errors that your event handlers throw. ### Supported Webhook Event Handlers Every handler is optional and async. For the payload of each event, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` *** ## Prompt for LLM ```text theme={null} You are an expert Express.js developer assistant. Your task is to guide a user through integrating the @dodopayments/express adapter into their existing Express.js project. The @dodopayments/express adapter provides route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed to plug directly into an Express app. First, install the necessary package. Use the package manager appropriate for the user's project (npm, yarn, or bun): npm install @dodopayments/express --- Here's how you should structure your response: 1. Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/express adapter would you like to integrate into your project? You can choose one or more of the following: - Checkout Route Handler (for handling product checkouts) - Customer Portal Route Handler (for managing customer subscriptions/details) - Webhook Route Handler (for receiving Dodo Payments webhook events) - All (integrate all three)" --- 2. Based on the user's selection, provide detailed integration steps for each chosen functionality. --- **If Checkout Route Handler is selected:** **Purpose**: This handler manages two checkout flows. Static checkout and checkout sessions both return JSON responses with checkout URLs for programmatic handling. **Integration**: Create routes in your Express app for static (GET) and checkout sessions (POST). Register express.json() first, because the POST handler reads req.body. import express from 'express'; import { checkoutHandler } from '@dodopayments/express'; const app = express(); app.use(express.json()); app.get('/api/checkout', checkoutHandler({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, type: "static" })); // For checkout sessions app.post('/api/checkout-session', checkoutHandler({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, type: "session" })); Config Options: bearerToken: Your Dodo Payments API key (recommended to be stored in DODO_PAYMENTS_API_KEY env variable). returnUrl (optional): URL to redirect the user after successful checkout. A return_url in the POST body takes precedence. environment: "test_mode" or "live_mode" (defaults to "live_mode") type: "static" (GET) or "session" (POST) GET (static checkout) expects query parameters: productId (required) quantity, customer fields (fullName, email, etc.), and metadata (metadata_*) are optional. Returns: {"checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_fqJhl7pxKWiLhwQR042rh?quantity=1"} POST (checkout sessions) - (Recommended) A more customizable checkout experience. Returns JSON with checkout_url: Parameters are sent as a JSON body, and product_cart is required. Supports both one-time and recurring payments. Returns: {"checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa"}. For a complete list of supported fields, refer to: Checkout Sessions Integration Guide: https://docs.dodopayments.com/developer-resources/checkout-session If Customer Portal Route Handler is selected: Purpose: This route allows customers to manage their subscriptions via the Dodo Payments portal. It redirects the request to the portal link. Integration: import express from 'express'; import { CustomerPortal } from "@dodopayments/express"; const app = express(); app.get('/api/customer-portal', CustomerPortal({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, })); Query Parameters: customer_id (required): e.g., ?customer_id=cus_123 send_email (optional): if true, customer is emailed the portal link Returns 400 if customer_id is missing. The handler does not authenticate the request, so protect the route with the app's own authentication and pass only the signed-in user's customer ID. If Webhook Route Handler is selected: Purpose: Processes incoming webhook events from Dodo Payments to trigger events in your app. Integration: import express from 'express'; import { Webhooks } from "@dodopayments/express"; const app = express(); app.use(express.json()); // required: the handler verifies the signature against the parsed req.body app.post('/api/webhooks', Webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, onPayload: async (payload) => { // Handle generic payload }, // You can also provide fine-grained handlers for each event type below })); Features: Only POST method is allowed — others return 405 Signature verification is performed using webhookKey. Returns 401 if invalid. Zod-based payload validation. Returns 400 if invalid schema. All handlers are async functions. onPayload runs for every event, before the event-specific handler. Supported Webhook Event Handlers: You may pass in any of the following handlers: onPayload onPaymentSucceeded onPaymentFailed onPaymentProcessing onPaymentCancelled onRefundSucceeded onRefundFailed onDisputeOpened, onDisputeExpired, onDisputeAccepted, onDisputeCancelled, onDisputeChallenged, onDisputeWon, onDisputeLost onSubscriptionActive, onSubscriptionOnHold, onSubscriptionRenewed, onSubscriptionPlanChanged, onSubscriptionCancelled, onSubscriptionFailed, onSubscriptionExpired, onSubscriptionUpdated, onSubscriptionPaused, onSubscriptionUnpaused, onSubscriptionUpdatePaymentMethod onLicenseKeyCreated onAbandonedCheckoutDetected, onAbandonedCheckoutRecovered onDunningStarted, onDunningRecovered onCreditAdded, onCreditDeducted, onCreditExpired, onCreditRolledOver, onCreditRolloverForfeited, onCreditOverageCharged, onCreditOverageReset, onCreditManualAdjustment, onCreditBalanceLow onEntitlementGrantCreated, onEntitlementGrantDelivered, onEntitlementGrantFailed, onEntitlementGrantRevoked onPayoutCreated, onPayoutOnHold, onPayoutInProgress, onPayoutFailed, onPayoutSuccess Environment Variable Setup: Make sure to define these environment variables in your project: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_ENVIRONMENT=test_mode (or live_mode) DODO_PAYMENTS_RETURN_URL=https://yourapp.com/success Use these inside your code as: process.env.DODO_PAYMENTS_API_KEY process.env.DODO_PAYMENTS_WEBHOOK_KEY Security Note: Do NOT commit secrets to version control. Use .env files locally and secrets managers in deployment environments (e.g., AWS, Vercel, Heroku, etc.). ``` # FastAPI Boilerplate Source: https://docs.dodopayments.com/developer-resources/fastapi-boilerplate Clone the FastAPI boilerplate to create checkout sessions, verify webhooks, and open the Customer Portal from a Python backend with the Dodo Payments SDK. > [card] [GitHub Repository](https://github.com/dodopayments/fastapi-boilerplate) > > Source code for the FastAPI and Dodo Payments boilerplate. ## Overview The FastAPI boilerplate is a Python backend with Dodo Payments already connected. It has endpoints that create checkout sessions and Customer Portal sessions, a webhook endpoint that verifies signatures, and a pricing page rendered from Jinja2 templates. > [!NOTE] > > This boilerplate uses FastAPI with `async` route handlers, Pydantic for validation and settings, and the `dodopayments` Python SDK. The handlers call the synchronous `DodoPayments` client. To avoid blocking the event loop, switch to `AsyncDodoPayments` and `await` its calls. ### Features The boilerplate includes: * **Quick Setup**: Go from clone to a running server in about five minutes. * **Async Handlers**: Route handlers are FastAPI `async def` functions. * **Checkout Sessions**: A pre-configured checkout endpoint that uses the Python SDK. * **Webhook Handling**: A webhook endpoint that verifies each signature with the SDK's `unwrap` method. * **Customer Portal**: An endpoint that creates Customer Portal sessions. * **Type Safety**: Pydantic models validate request bodies, and the code uses type hints. * **Environment Configuration**: `pydantic-settings` loads and validates the configuration from `.env`. ## Prerequisites Before you begin, you need: * **Python 3.9 or later**, which the `dodopayments` SDK requires. Python 3.11 or later is recommended. * **pip** or **uv** for package management. * **A Dodo Payments account**, to create an API key and a webhook signing secret in the dashboard. ## Quick Start **1. Clone the Repository** ```bash theme={null} git clone https://github.com/dodopayments/fastapi-boilerplate.git cd fastapi-boilerplate ``` **2. Create Virtual Environment** Set up an isolated Python environment: ```bash theme={null} python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate ``` Or use uv for faster dependency management: ```bash theme={null} uv venv source .venv/bin/activate ``` **3. Install Dependencies** ```bash theme={null} pip install -r requirements.txt ``` Or with uv: ```bash theme={null} uv pip install -r requirements.txt ``` **4. Get API Credentials** Sign up at [Dodo Payments](https://dodopayments.com/), then get your credentials from the dashboard: * **API Key:** Create a key under [Dashboard → Developer → API Keys](https://app.dodopayments.com/developer/api-keys). * **Webhook Key:** Add an endpoint under [Dashboard → Developer → Webhooks](https://app.dodopayments.com/developer/webhooks), then copy its signing secret. The endpoint URL must be public and use HTTPS. To receive events on your machine, see [Testing Webhooks Locally](#testing-webhooks-locally). > [!TIP] > > Create both while the **Live Mode** switch in the sidebar is off. A test mode key works only with `DODO_PAYMENTS_ENVIRONMENT=test_mode`, and test mode payments don't move real money. **5. Configure Environment Variables** Copy the example file to create a `.env` file in the root directory: ```bash theme={null} cp .env.example .env ``` Set the values to your Dodo Payments credentials: ```bash .env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_signing_key_here DODO_PAYMENTS_RETURN_URL=http://localhost:8000 DODO_PAYMENTS_ENVIRONMENT=test_mode ``` All four variables are required. `app/core/config.py` loads them with `pydantic-settings`, and the app fails to start if one is missing or empty. `DODO_PAYMENTS_RETURN_URL` is where checkout sends the customer after payment. > [!WARNING] > > Don't commit your `.env` file to version control. The repository's `.gitignore` already excludes it. **6. Add Your Products** Replace the sample products in `app/lib/products.py` with your own. Set each `product_id` to the ID of a product under **Products** in your dashboard. The pricing page displays these products. **7. Run the Development Server** ```bash theme={null} uvicorn app.main:app --reload --port 8000 ``` Open [http://localhost:8000/docs](http://localhost:8000/docs) to see the interactive API documentation. > [!TIP] > > Swagger UI lists the `/api/checkout/`, `/api/webhook/`, and `/api/customer-portal/` endpoints, ready to test. The root URL, `http://localhost:8000`, serves the pricing page. > [!WARNING] > > `app/main.py` calls `templates.TemplateResponse("index.html", {"request": request, ...})`, a signature that Starlette 1.x no longer accepts, so the pricing page returns a `500` error on a fresh install. To fix it, change the call to `templates.TemplateResponse(request, "index.html", {"products": products})`. ## Project Structure ```text theme={null} fastapi-boilerplate/ ├── app/ │ ├── main.py # FastAPI application entry point │ ├── api/ │ │ ├── checkout.py # Checkout session endpoint │ │ ├── portal.py # Customer portal endpoint │ │ └── webhook.py # Webhook handler endpoint │ ├── core/ │ │ └── config.py # Environment configuration │ ├── lib/ │ │ ├── customers.py # Customer payload helpers │ │ └── products.py # Products shown on the pricing page │ └── templates/ │ ├── base.html # Base template │ └── index.html # Pricing page ├── requirements.txt # Python dependencies ├── .env.example # Environment template └── README.md ``` ## API Endpoints `app/main.py` mounts each router under an `/api` prefix: | Endpoint | Method | Description | | - | - | - | | `/api/checkout/` | POST | Create a new checkout session | | `/api/webhook/` | POST | Handle Dodo Payments webhooks | | `/api/customer-portal/` | POST | Generate customer portal URL | Each path ends with a slash. FastAPI answers a request to the path without the slash with a `307` redirect, so use the exact path, especially in your webhook URL. ## Code Examples These examples are condensed from the files in `app/api/`. ### Creating a Checkout Session `app/api/checkout.py` creates a checkout session and returns its `checkout_url`. The request body takes a `product_id`, an optional `quantity`, and an optional `customer` object with `name` and `email`: ```python theme={null} from typing import Optional from fastapi import APIRouter, HTTPException from pydantic import BaseModel from dodopayments import DodoPayments from app.core.config import settings from app.lib.customers import CustomerData, to_dodo_customer_payload router = APIRouter() client = DodoPayments( bearer_token=settings.DODO_PAYMENTS_API_KEY, environment=settings.DODO_PAYMENTS_ENVIRONMENT, ) class CheckoutRequest(BaseModel): product_id: str quantity: int = 1 customer: Optional[CustomerData] = None @router.post("/") async def create_checkout(request: CheckoutRequest): try: checkout_session = client.checkout_sessions.create( product_cart=[{ "product_id": request.product_id, "quantity": request.quantity, }], customer=to_dodo_customer_payload(request.customer), show_saved_payment_methods=True, feature_flags={"allow_discount_code": True}, return_url=settings.DODO_PAYMENTS_RETURN_URL, ) return {"session_id": checkout_session.session_id, "checkout_url": checkout_session.checkout_url} except Exception as e: raise HTTPException(status_code=400, detail=str(e)) ``` ### Handling Webhooks `app/api/webhook.py` verifies the signature with the SDK's `unwrap` method, then branches on the event type: ```python theme={null} import json from fastapi import APIRouter, Request, HTTPException from dodopayments import DodoPayments from app.core.config import settings router = APIRouter() client = DodoPayments( bearer_token=settings.DODO_PAYMENTS_API_KEY, environment=settings.DODO_PAYMENTS_ENVIRONMENT, webhook_key=settings.DODO_PAYMENTS_WEBHOOK_KEY, ) @router.post("/") async def handle_webhook(request: Request): body = await request.body() # Dodo Payments follows the Standard Webhooks spec: the signature covers # `id.timestamp.body`, so all three webhook-* headers must be passed in. try: client.webhooks.unwrap( body, headers={ "webhook-id": request.headers.get("webhook-id", ""), "webhook-signature": request.headers.get("webhook-signature", ""), "webhook-timestamp": request.headers.get("webhook-timestamp", ""), }, ) except Exception as e: raise HTTPException(status_code=400, detail=f"Webhook verification failed: {e}") event_type = json.loads(body).get("type", "") if event_type == "subscription.active": print("Subscription is active") # Grant access, update DB, send email elif event_type == "payment.succeeded": print("Payment succeeded") # Fulfill order, update DB, send email elif event_type == "subscription.cancelled": print("Subscription cancelled") # Revoke access, update user status elif event_type == "payment.failed": print("Payment failed") # Notify user, update payment status else: print(f"Unhandled event type: {event_type}") return {"status": "success", "event": event_type} ``` ### Customer Portal Integration `app/api/portal.py` creates a Customer Portal session for a customer ID and returns the portal link as `url`: ```python theme={null} from fastapi import APIRouter, HTTPException from pydantic import BaseModel from dodopayments import DodoPayments from app.core.config import settings from app.lib.customers import sanitize_customer_id router = APIRouter() client = DodoPayments( bearer_token=settings.DODO_PAYMENTS_API_KEY, environment=settings.DODO_PAYMENTS_ENVIRONMENT, ) class PortalRequest(BaseModel): customer_id: str @router.post("/") async def create_customer_portal(request: PortalRequest): try: customer_id = sanitize_customer_id(request.customer_id) portal_session = client.customers.customer_portal.create( customer_id=customer_id, ) return {"url": portal_session.link} except Exception as e: raise HTTPException(status_code=400, detail=str(e)) ``` The pricing page in `app/templates/index.html` sends a hardcoded customer ID (`cus_001`) to this endpoint, and a hardcoded name and email to the checkout endpoint. Replace them with the signed-in user's values. ## Webhook Events The handler in `app/api/webhook.py` branches on these events: | Event | Description | | - | - | | `payment.succeeded` | Payment completed successfully | | `payment.failed` | Payment attempt failed | | `subscription.active` | Subscription is now active | | `subscription.cancelled` | Subscription was cancelled | To handle another event, add a branch for its type, such as `refund.succeeded` for a refund that processed successfully. For every event type, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). Add your business logic inside the webhook handler to: * Update user permissions in your database * Send confirmation emails * Provision access to digital products * Track analytics and metrics ## Testing Webhooks Locally Dodo Payments can't reach `localhost`. For local development, use a tool such as [ngrok](https://ngrok.com/) to expose your local server: ```bash theme={null} ngrok http 8000 ``` Add the ngrok HTTPS URL, followed by `/api/webhook/`, as an endpoint in your [Dodo Payments Dashboard](https://app.dodopayments.com/developer/webhooks): ```text theme={null} https://your-ngrok-url.ngrok.io/api/webhook/ ``` Copy the endpoint's signing secret into `DODO_PAYMENTS_WEBHOOK_KEY` in `.env`, then restart the server. The app reads `.env` only at startup. ## Deployment ### Docker The repository doesn't include a `Dockerfile`. To run the app in a container, add this `Dockerfile` to the repository root: ```dockerfile theme={null} FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] ``` `COPY . .` copies every file in the build context, including `.env`. To keep your keys out of the image, add a `.dockerignore` file that lists `.env`. Then build the image and run it with your environment file: ```bash theme={null} docker build -t fastapi-dodo . docker run -p 8000:8000 --env-file .env fastapi-dodo ``` ### Production Considerations > [!WARNING] > > Before deploying to production: > > * Switch `DODO_PAYMENTS_ENVIRONMENT` to `live_mode`. > * Use a live mode API key from the dashboard. > * Add a webhook endpoint for your production domain, and set `DODO_PAYMENTS_WEBHOOK_KEY` to its signing secret. > * Set `DODO_PAYMENTS_RETURN_URL` to your production URL. > * Enable HTTPS for all endpoints. ## Troubleshooting > [accordion] Import errors or missing modules > > Make sure your virtual environment is activated and dependencies are installed: > > ```bash theme={null} > source venv/bin/activate > pip install -r requirements.txt > ``` > [accordion] Server fails to start with Directory 'app/static' does not exist > > `app/main.py` serves static files from `app/static`, but the repository doesn't include that directory. Create it with `mkdir app/static`, then start the server again. > [accordion] Checkout session creation fails > > Check for these common causes: > > * The product ID doesn't exist in your Dodo Payments dashboard. > * The API key or `DODO_PAYMENTS_ENVIRONMENT` in `.env` is wrong. A test mode key works only with `test_mode`. > > The endpoint returns the SDK error in a `400` response. Check the FastAPI logs for detailed error messages. > [accordion] Webhooks not receiving events > > For local testing, use [ngrok](https://ngrok.com) to expose your server: > > ```bash theme={null} > ngrok http 8000 > ``` > > In your [Dodo dashboard](https://app.dodopayments.com/developer/webhooks), add an endpoint with the ngrok URL followed by `/api/webhook/`, including the trailing slash. Copy that endpoint's signing secret into `DODO_PAYMENTS_WEBHOOK_KEY` in your `.env` file. > [accordion] Webhook signature verification fails > > * Make sure `DODO_PAYMENTS_WEBHOOK_KEY` in `.env` matches the endpoint's signing secret. > * Verify the signature against the raw request body, before you parse it as JSON. > * Pass all three `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers to `client.webhooks.unwrap()`. The Standard Webhooks signature covers `id.timestamp.body`, not the body alone. ## Learn More > [card] [Python SDK](/developer-resources/sdks/python) > > Complete Python SDK documentation with async support > [card] [Webhooks Documentation](/developer-resources/webhooks) > > Learn about all webhook events and best practices > [card] [Checkout Sessions](/developer-resources/checkout-session) > > Deep dive into checkout session configuration > [card] [API Reference](/api-reference/introduction) > > Complete Dodo Payments API documentation ## Support For help with the boilerplate: * Ask questions in the [Discord community](https://discord.gg/bYqAp4ayYh). * Report issues and follow updates in the [GitHub repository](https://github.com/dodopayments/fastapi-boilerplate). * Email the [support team](mailto:support@dodopayments.com). # Fastify Adaptor Source: https://docs.dodopayments.com/developer-resources/fastify-adaptor Add Dodo Payments checkout, Customer Portal, and webhook route handlers to a Fastify app with the @dodopayments/fastify adaptor. The `@dodopayments/fastify` adaptor gives your Fastify app three route handlers: `Checkout` returns checkout URLs, `CustomerPortal` sends a customer to the Customer Portal, and `Webhooks` verifies webhook requests and calls your event handlers. > [card] [Checkout Handler](#checkout-route-handler) > > Create payment links and checkout sessions from your Fastify app. > [card] [Customer Portal](#customer-portal-route-handler) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-route-handler) > > Verify and process Dodo Payments webhook events. ## Installation **1. Install the Package** Run the following command in your project root: ```bash theme={null} npm install @dodopayments/fastify ``` The package requires Fastify 5.4.0 or later. **2. Set Up Environment Variables** Create a `.env` file in your project root: ```env expandable theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret # test_mode or live_mode DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_RETURN_URL=https://yourapp.com/success ``` Create the API key under **Developer → API Keys**. Add your webhook endpoint under **Developer → Webhooks** and copy its signing secret into `DODO_PAYMENTS_WEBHOOK_KEY`. While you build, use a test mode API key with `DODO_PAYMENTS_ENVIRONMENT=test_mode`, because a test mode key works only against test mode. `DODO_PAYMENTS_RETURN_URL` is optional. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## Route Handler Examples > [!NOTE] > > The examples register routes on a Fastify instance created with `Fastify()`. The webhook route needs the raw request body, so its example adds a string body parser inside a plugin that contains only the webhook route. > [tab] Checkout Handler > > > [!NOTE] > > > > Use this handler to integrate Dodo Payments checkout into your Fastify app. Supports static (GET) and checkout session (POST) flows. `Checkout()` returns a `getHandler` for the static flow and a `postHandler` for the session flow. > > ```typescript Fastify Route Handler expandable theme={null} > // route.ts > import { Checkout } from '@dodopayments/fastify'; > import Fastify from 'fastify' > > const fastify = Fastify({}) > const checkoutGet = Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > type: 'static' > }); > > const checkoutSession = Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > type: 'session' > }); > > fastify.get('/api/checkout', checkoutGet.getHandler); > fastify.post('/api/checkout-session', checkoutSession.postHandler); > ``` > > ```bash Static Checkout cURL theme={null} > curl --request GET \ > --url 'https://example.com/api/checkout?productId=pdt_fqJhl7pxKWiLhwQR042rh' > ``` > > ```bash Checkout Session cURL expandable theme={null} > curl --request POST \ > --url https://example.com/api/checkout-session \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_QMDuvLkbVzCRWRQjLNcs", > "quantity": 1 > } > ], > "customer": { > "email": "test@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal Handler > > > [!NOTE] > > > > Use this handler to let customers manage their subscriptions and details in the Dodo Payments Customer Portal. > > ```typescript Fastify Route Handler expandable theme={null} > // route.ts > import { CustomerPortal } from "@dodopayments/fastify"; > import Fastify from 'fastify' > > const fastify = Fastify({}) > const customerPortalHandler = CustomerPortal({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT > }); > fastify.get('/api/customer-portal', customerPortalHandler); > ``` > > ```bash Customer Portal cURL theme={null} > curl --request GET \ > --url 'https://example.com/api/customer-portal?customer_id=cus_9VuW4K7O3GHwasENg31m&send_email=true' > ``` > [tab] Webhook Handler > > > [!NOTE] > > > > Use this handler to receive, verify, and process Dodo Payments webhook events in your Fastify app. > > ```typescript Fastify Route Handler expandable theme={null} > // route.ts > import Fastify from 'fastify' > import { Webhooks } from '@dodopayments/fastify' > > const fastify = Fastify({}) > > // Keep the raw-body parser inside this plugin, so other routes still receive parsed JSON > fastify.register(async (webhookRoutes) => { > webhookRoutes.addContentTypeParser('application/json', { parseAs: 'string' }, function (req, body, done) { > done(null, body) > }) > > webhookRoutes.post('/api/webhooks', Webhooks({ > webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, > onPayload: async (payload) => { > // Handle Payload Here > console.log(payload) > } > })) > }) > ``` ## Checkout Route Handler > [!NOTE] > > The adaptor supports all three Dodo Payments checkout flows. Set `type` in the handler config to choose the flow a route serves. Every flow responds with JSON that contains a `checkout_url` for the customer to open. * **Static Payment Links:** `type: "static"`, GET. Builds a payment link for one product from query parameters, after checking that the product exists. * **Dynamic Payment Links (deprecated):** `type: "dynamic"`, POST. Creates a one-time payment or a subscription with a payment link, depending on whether the product is recurring. * **Checkout Sessions:** `type: "session"`, POST. Creates a checkout session from a product cart and customer details. Use this flow for new integrations. `Checkout` takes these options: | Option | Type | Description | | - | - | - | | `bearerToken` | `string` | Your Dodo Payments API key. | | `environment` | `string` | `test_mode` or `live_mode`. Defaults to `live_mode`. | | `returnUrl` | `string` | Optional. The URL that checkout redirects the customer to after payment. A `return_url` in a POST body takes precedence. | | `type` | `string` | The checkout flow: `static`, `dynamic`, or `session`. | `Checkout` returns an object with two handlers. Register `getHandler` for GET when `type` is `static`, and `postHandler` for POST when `type` is `dynamic` or `session`. > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_nZuwz45WAs64n3l07zpQR`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's street address. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's postal or ZIP code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > The payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed to checkout as metadata, for example `metadata_orderId=123`. > > A disable flag takes effect only when it's `true` and the matching field has a value, for example `email` with `disableEmail`. The handler passes these parameters to a [static payment link](/developer-resources/integration-guide#static-payment-links). > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters, or a product that doesn't exist in your account, also result in a 400 response. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_fqJhl7pxKWiLhwQR042rh?quantity=1&redirect_url=https%3A%2F%2Fyourapp.com%2Fsuccess" > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. The handler retrieves the product, then creates a subscription if the product is recurring and a one-time payment otherwise. > * The body needs `billing` (with `street`, `city`, `state`, `country`, and `zipcode`) and `customer`, plus `product_id` (with an optional `quantity`) or `product_cart`. Subscriptions need `product_id`. > * The handler also forwards `metadata`, `allowed_payment_method_types`, `billing_currency`, `discount_codes` (or the deprecated `discount_code`), `return_url`, `show_saved_payment_methods`, and `tax_id`. For subscriptions, it forwards `addons`, `on_demand`, and `trial_period_days` too. It ignores other fields. > * For field details, refer to: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic Checkout calls the deprecated `POST /payments` and `POST /subscriptions` endpoints. Use Checkout Sessions for new integrations. > > ### Response Format > > Dynamic checkout returns a JSON response with the payment link as the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/cbq" > } > ``` > [accordion] Checkout Sessions (POST) > > Send a checkout session payload as the JSON body. The handler creates a checkout session, which handles the complete payment flow for one-time purchases and subscriptions, and returns its `checkout_url`. `product_cart` is required and must contain at least one product. > > Each `checkout_url` works once and expires after 24 hours, or after 15 minutes when you pass `confirm: true`. A session created with `payment_method_id` returns no `checkout_url`, so the handler responds with 400. > > Refer to [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session) for more details and a complete list of supported fields. > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa" > } > ``` ## Customer Portal Route Handler The Customer Portal Route Handler creates a Customer Portal session for the customer in `customer_id` and redirects the request to the portal link. `CustomerPortal` takes the `bearerToken` and `environment` options, the same as `Checkout`. If Dodo Payments can't create the session, the handler returns 500. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, sends an email to the customer with the portal link. > [!WARNING] > > Returns 400 if `customer_id` is missing. The handler doesn't authenticate the request and opens the portal for any `customer_id` it receives, so put the route behind your own authentication and pass only the signed-in user's customer ID. ## Webhook Route Handler The webhook handler verifies each request with your webhook secret, passed as `webhookKey`, then calls your event handlers. > [!WARNING] > > The webhook handler needs the raw request body as a string, so add a content type parser for `application/json` with `parseAs: 'string'`. Fastify applies a parser to every route in the scope where you add it. Add it inside a plugin that registers only the webhook route, as the example does. On the root instance, it would also pass a string to the POST checkout handlers, which then return 400. * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`, following the [Standard Webhooks](https://standardwebhooks.com/) specification. Returns 401 if verification fails. * **Payload Validation:** Validated with Zod. Returns 400 for invalid payloads. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Internal error during verification * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200 when they finish. The handler doesn't catch errors that your event handlers throw. ### Supported Webhook Event Handlers Every handler is optional and async. For the payload of each event, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` *** ## Prompt for LLM ```text theme={null} You are an expert Fastify developer assistant. Your task is to guide a user through integrating the @dodopayments/fastify adapter into their existing Fastify project. The @dodopayments/fastify adapter provides route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed to plug directly into a Fastify app. First, install the necessary package. Use the package manager appropriate for the user's project (npm, yarn, or bun): npm install @dodopayments/fastify The package requires Fastify 5.4.0 or later. --- Here's how you should structure your response: 1. Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/fastify adapter would you like to integrate into your project? You can choose one or more of the following: - Checkout Route Handler (for handling product checkouts) - Customer Portal Route Handler (for managing customer subscriptions/details) - Webhook Route Handler (for receiving Dodo Payments webhook events) - All (integrate all three)" --- 2. Based on the user's selection, provide detailed integration steps for each chosen functionality. --- **If Checkout Route Handler is selected:** **Purpose**: This handler manages two checkout flows. Static checkout and checkout sessions both return JSON responses with checkout URLs for programmatic handling. **Integration**: Create routes in your Fastify app for static (GET) and checkout sessions (POST). Checkout() returns getHandler for the static flow and postHandler for the session flow. import { Checkout } from '@dodopayments/fastify'; import Fastify from 'fastify' const fastify = Fastify({}) const checkoutGet = Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, type: 'static' }); const checkoutSession = Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, type: 'session' }); fastify.get('/api/checkout', checkoutGet.getHandler); fastify.post('/api/checkout-session', checkoutSession.postHandler); Config Options: bearerToken: Your Dodo Payments API key (recommended to be stored in DODO_PAYMENTS_API_KEY env variable). returnUrl (optional): URL to redirect the user after successful checkout. A return_url in the POST body takes precedence. environment: "test_mode" or "live_mode" (defaults to "live_mode") type: "static" (GET) or "session" (POST) GET (static checkout) expects query parameters: productId (required) quantity, customer fields (fullName, email, etc.), and metadata (metadata_*) are optional. Returns: {"checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_fqJhl7pxKWiLhwQR042rh?quantity=1"} POST (checkout sessions) - (Recommended) A more customizable checkout experience. Returns JSON with checkout_url: Parameters are sent as a JSON body, and product_cart is required. Supports both one-time and recurring payments. Returns: {"checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa"}. For a complete list of supported fields, refer to: Checkout Sessions Integration Guide: https://docs.dodopayments.com/developer-resources/checkout-session If Customer Portal Route Handler is selected: Purpose: This route allows customers to manage their subscriptions via the Dodo Payments portal. It redirects the request to the portal link. Integration: import { CustomerPortal } from "@dodopayments/fastify"; import Fastify from 'fastify' const fastify = Fastify({}) const customerPortalHandler = CustomerPortal({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT }); fastify.get('/api/customer-portal', customerPortalHandler); Query Parameters: customer_id (required): e.g., ?customer_id=cus_123 send_email (optional): if true, customer is emailed the portal link Returns 400 if customer_id is missing. The handler does not authenticate the request, so protect the route with the app's own authentication and pass only the signed-in user's customer ID. If Webhook Route Handler is selected: Purpose: Processes incoming webhook events from Dodo Payments to trigger events in your app. Integration: The handler needs the raw request body as a string. Add the string content type parser inside a plugin that contains only the webhook route, so the POST checkout handlers still receive parsed JSON. import Fastify from 'fastify' import { Webhooks } from '@dodopayments/fastify' const fastify = Fastify({}) fastify.register(async (webhookRoutes) => { webhookRoutes.addContentTypeParser('application/json', { parseAs: 'string' }, function (req, body, done) { done(null, body) }) webhookRoutes.post('/api/webhooks', Webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, onPayload: async (payload) => { // Handle Payload Here console.log(payload) } })) }) Features: Only POST method is allowed — others return 405 Signature verification is performed using webhookKey. Returns 401 if invalid. Zod-based payload validation. Returns 400 if invalid schema. All handlers are async functions. onPayload runs for every event, before the event-specific handler. Supported Webhook Event Handlers: You may pass in any of the following handlers: onPayload onPaymentSucceeded onPaymentFailed onPaymentProcessing onPaymentCancelled onRefundSucceeded onRefundFailed onDisputeOpened, onDisputeExpired, onDisputeAccepted, onDisputeCancelled, onDisputeChallenged, onDisputeWon, onDisputeLost onSubscriptionActive, onSubscriptionOnHold, onSubscriptionRenewed, onSubscriptionPlanChanged, onSubscriptionCancelled, onSubscriptionFailed, onSubscriptionExpired, onSubscriptionUpdated, onSubscriptionPaused, onSubscriptionUnpaused, onSubscriptionUpdatePaymentMethod onLicenseKeyCreated onAbandonedCheckoutDetected, onAbandonedCheckoutRecovered onDunningStarted, onDunningRecovered onCreditAdded, onCreditDeducted, onCreditExpired, onCreditRolledOver, onCreditRolloverForfeited, onCreditOverageCharged, onCreditOverageReset, onCreditManualAdjustment, onCreditBalanceLow onEntitlementGrantCreated, onEntitlementGrantDelivered, onEntitlementGrantFailed, onEntitlementGrantRevoked onPayoutCreated, onPayoutOnHold, onPayoutInProgress, onPayoutFailed, onPayoutSuccess Environment Variable Setup: Make sure to define these environment variables in your project: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_ENVIRONMENT=test_mode (or live_mode) DODO_PAYMENTS_RETURN_URL=https://yourapp.com/success Use these inside your code as: process.env.DODO_PAYMENTS_API_KEY process.env.DODO_PAYMENTS_WEBHOOK_KEY Security Note: Do NOT commit secrets to version control. Use .env files locally and secrets managers in deployment environments (e.g., AWS, Vercel, Heroku, etc.). ``` # Framework Adaptors Overview Source: https://docs.dodopayments.com/developer-resources/framework-adaptors Add Dodo Payments checkout, customer portal, and webhook handlers to Next.js, Nuxt, Express, Hono, SvelteKit, Convex, Better Auth, and other frameworks. Framework adaptors add Dodo Payments checkout, Customer Portal, and webhook handlers to your app using your framework's request and response types. Each adaptor is an npm package in the `@dodopayments` scope. The packages use `@dodopayments/core` for checkout validation, Dodo Payments API requests, webhook payload validation, and typed event callbacks. > [!TIP] > > Each adaptor accepts your API key and environment in its handler configuration. Keep those values in environment variables and pass them when you create the handler. To have a coding agent add an adaptor for you, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ## Available Framework Adaptors Choose the adaptor that matches your framework: > [card] [Next.js](/developer-resources/nextjs-adaptor) > > Route handlers for checkout, the customer portal, and webhooks in the App Router. > [card] [Nuxt](/developer-resources/nuxt-adaptor) > > Server route handlers for Nuxt 3, a full-stack Vue framework. > [card] [Express](/developer-resources/express-adaptor) > > Request handlers for Express 5 routes in Node.js apps. > [card] [Fastify](/developer-resources/fastify-adaptor) > > Route handlers for Fastify 5, a Node.js framework with a plugin architecture. > [card] [Hono](/developer-resources/hono-adaptor) > > Route handlers for Hono 4, a web framework for Cloudflare Workers, other edge runtimes, and Node.js. > [card] [Astro](/developer-resources/astro-adaptor) > > Server endpoint handlers for Astro 7, a content-focused web framework. > [card] [SvelteKit](/developer-resources/sveltekit-adaptor) > > Server route handlers for SvelteKit 2, a full-stack Svelte framework. > [card] [Remix](/developer-resources/remix-adaptor) > > Loader and action handlers for Remix 2, a full-stack React framework. > [card] [TanStack Start](/developer-resources/tanstack-adaptor) > > Server route handlers for TanStack Start, a type-safe full-stack React framework. > [card] [Better Auth](/developer-resources/better-auth-adaptor) > > A plugin for the Better Auth authentication framework that adds checkout, portal, usage, and webhook endpoints, and can create a customer at sign-up. > [card] [Convex](/developer-resources/convex-component) > > A component for the Convex backend with checkout and customer portal actions and a webhook HTTP action. > [card] [Bun](/developer-resources/bun-adaptor) > > Native `Bun.serve()` handlers for checkout, the customer portal, and webhooks. ## Core Features The route handler adaptors share these capabilities: | Feature | Description | | - | - | | **Checkout Handler** | Static and checkout session flows | | **Customer Portal** | A handler that opens the Customer Portal, where customers manage subscriptions and billing details | | **Webhook Handler** | Signature verification and typed callbacks for individual event types | | **Environment Config** | API credentials and environment passed through typed handler options | | **Type Safety** | TypeScript types for handler options and webhook payloads | The Better Auth plugin and the Convex component provide the same capabilities through their own APIs. See their pages for the differences. ## Quick Start Set up a route handler adaptor in three steps. **1. Install the Adaptor** Install the package for your framework: > [tab] Next.js > > ```bash theme={null} > npm install @dodopayments/nextjs > ``` > [tab] Nuxt > > ```bash theme={null} > npm install @dodopayments/nuxt > ``` > [tab] Express > > ```bash theme={null} > npm install @dodopayments/express > ``` > [tab] Hono > > ```bash theme={null} > npm install @dodopayments/hono > ``` > [tab] Astro > > ```bash theme={null} > npm install @dodopayments/astro > ``` > [tab] SvelteKit > > ```bash theme={null} > npm install @dodopayments/sveltekit > ``` **2. Configure Environment Variables** Add your Dodo Payments credentials to your environment. Create the API key under **Developer → API Keys** and the webhook secret under **Developer → Webhooks** in the dashboard. A test mode API key works only with `test_mode`. ```env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_RETURN_URL=https://yourdomain.com/checkout/success DODO_PAYMENTS_ENVIRONMENT="test_mode" # or "live_mode" ``` If you don't pass an environment, the adaptor uses `live_mode`. > [!WARNING] > > Never commit your `.env` file or secrets to version control. **3. Create Route Handlers** Create a checkout route. The customer portal and webhook routes follow the same pattern: > [tab] Next.js > > ```typescript expandable theme={null} > // app/checkout/route.ts > import { Checkout } from "@dodopayments/nextjs"; > > export const GET = Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > }); > ``` > [tab] Express > > ```typescript expandable theme={null} > import express from 'express'; > import { checkoutHandler } from '@dodopayments/express'; > > const app = express(); > > app.get('/api/checkout', checkoutHandler({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > })); > ``` > [tab] Hono > > ```typescript expandable theme={null} > import { Hono } from "hono"; > import { Checkout } from "@dodopayments/hono"; > > const app = new Hono(); > > app.get('/checkout', Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > })); > ``` > [!TIP] > > Your checkout route now returns a checkout URL. Each adaptor's page covers the customer portal and webhook handlers and lists every option. ## Checkout Flow Types The route handler adaptors support three checkout flow types. The Better Auth plugin supports checkout sessions and a deprecated dynamic checkout. The Convex component supports checkout sessions only. > [accordion] Static Checkout (GET) > > Static checkout returns a payment link for one product, so you can share it or redirect to it. Pass the product ID as a query parameter: > > ```text theme={null} > /api/checkout?productId=pdt_xxx&quantity=1 > ``` > > The handler checks that the product exists and returns the link as `checkout_url`. Optional query parameters pre-fill customer details and control the checkout form. > [accordion] Dynamic Checkout (POST, Deprecated) > > Dynamic checkout (`type: "dynamic"`) creates a payment link through the deprecated `POST /payments` or `POST /subscriptions` endpoint, depending on the product type. Existing dynamic routes keep working. For new integrations, use checkout sessions: switch the handler to `type: "session"`, send `product_cart` instead of `product_id`, and pass the address as the optional `billing_address` instead of the required `billing`. > [accordion] Checkout Sessions (POST) > > Checkout sessions are the recommended flow. They offer the most options and accept a cart with several products: > > ```json theme={null} > { > "product_cart": [ > { "product_id": "pdt_xxx", "quantity": 1 }, > { "product_id": "pdt_yyy", "quantity": 2 } > ], > "customer": { > "email": "customer@example.com" > } > } > ``` > > For every supported field, see the [Checkout Sessions Guide](/developer-resources/checkout-session). ## Webhook Event Handling Every route handler adaptor exports a `Webhooks` handler. It takes your webhook secret and optional typed callbacks for individual event types. `onPayload` runs for every event: ```typescript expandable theme={null} Webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, onPayload: async (payload) => { // Handle any webhook event }, onPaymentSucceeded: async (payload) => { // Handle successful payments }, onSubscriptionActive: async (payload) => { // Handle new subscriptions }, // ...more than 40 optional event callbacks in total }); ``` The callbacks cover payment, refund, dispute, subscription, license key, abandoned checkout, dunning, credit, entitlement grant, and payout events. The Better Auth plugin accepts the same callbacks in `webhooks()`, and the Convex component accepts them in `createDodoWebhookHandler`. > [!NOTE] > > Each webhook handler verifies the `webhook-id`, `webhook-signature`, and `webhook-timestamp` headers with the Standard Webhooks library, then validates the payload with Zod schemas. Invalid requests are rejected with an error status before your callbacks run. ## Choosing the Right Adaptor | Framework | Best For | Runtime | | - | - | - | | **Next.js** | Full-stack React apps with App Router | Node.js, Edge | | **Nuxt** | Full-stack Vue.js applications | Node.js | | **Express** | REST APIs and traditional Node.js apps | Node.js | | **Fastify** | High-performance APIs | Node.js | | **Hono** | Edge deployments, Cloudflare Workers | Edge, Node.js | | **Astro** | Content sites with server endpoints | Node.js, Edge | | **SvelteKit** | Full-stack Svelte applications | Node.js | | **Remix** | Full-stack React with nested routing | Node.js | | **TanStack Start** | Type-safe full-stack React | Node.js | | **Better Auth** | Apps already using Better Auth | Various | | **Convex** | Apps using Convex for backend | Convex Runtime | | **Bun** | Native Bun server applications | Bun | ## Getting Help For help with a framework adaptor: * **Discord**: Ask in the [community server](https://discord.gg/bYqAp4ayYh). * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue in the [dodo-adapters repository](https://github.com/dodopayments/dodo-adapters), which holds every adaptor. * **Documentation**: See the [API reference](/api-reference/introduction). # Go Boilerplate Source: https://docs.dodopayments.com/developer-resources/go-boilerplate Clone a minimal Go server that creates Dodo Payments checkout sessions, verifies webhooks, and opens the Customer Portal with the dodopayments-go SDK. > [card] [GitHub Repository](https://github.com/dodopayments/go-boilerplate) > > Minimal Go + Dodo Payments boilerplate ## Overview The Go boilerplate is a minimal Go server that sells your Dodo Payments products from a pricing page. It creates checkout sessions, verifies and handles webhooks, and opens the Customer Portal. Clone it as the starting point for your own Go backend. > [!NOTE] > > The boilerplate needs Go 1.24.4 or later, the version set in its `go.mod`. It uses a `cmd`, `internal`, and `templates` layout, renders the pricing page with Go HTML templates, and calls the Dodo Payments API through the [`dodopayments-go`](/developer-resources/sdks/go) SDK. ### Features * **Quick Setup**: Clone the repository, add your API keys to `.env`, and start the server with `make run`. * **Payment Integration**: A checkout flow that creates checkout sessions with the `dodopayments-go` SDK. * **Modern UI**: A dark-themed pricing page built with Go HTML templates and Tailwind CSS. * **Webhook Handling**: Verifies the signature of each webhook before it processes the event. * **Customer Portal**: Self-serve subscription management through the Customer Portal. * **Go Best Practices**: A clean project layout with `cmd`, `internal`, and `templates`. * **Pre-filled Checkout**: Passes the customer's name and email to checkout, so the customer doesn't type them again. ## Prerequisites Before you begin, you need: * **Go 1.24.4 or later**. Check your version with `go version`. * **A Dodo Payments account**, to create an API key and a webhook signing key in the dashboard. * **At least one product**, created under **Products** in the dashboard. ## Quick Start **1. Clone the Repository** ```bash theme={null} git clone https://github.com/dodopayments/go-boilerplate.git cd go-boilerplate ``` **2. Install Dependencies** ```bash theme={null} make install ``` `make install` runs `go mod download` and then `go mod tidy`. To download the modules without `make`, run: ```bash theme={null} go mod download ``` **3. Get API Credentials** Sign up at [Dodo Payments](https://dodopayments.com/), then copy both keys from the dashboard: * **API Key:** [Developer → API Keys](https://app.dodopayments.com/developer/api-keys) * **Webhook Key:** [Developer → Webhooks](https://app.dodopayments.com/developer/webhooks). Each webhook endpoint has its own signing key. To create an endpoint that reaches your local server, see [Testing Webhooks Locally](#testing-webhooks-locally). > [!TIP] > > Create both keys in test mode while you develop. To switch to test mode, turn off the **Live Mode** switch in the dashboard sidebar. **4. Configure Environment Variables** Create a `.env` file in the project root from the template: ```bash theme={null} cp .env.example .env ``` Set these values in `.env`: ```bash .env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_signing_key_here DODO_PAYMENTS_RETURN_URL=http://localhost:8000 DODO_PAYMENTS_ENVIRONMENT=test_mode PORT=8000 ``` The server reads these variables at startup: | Variable | Required | Default | Purpose | | - | - | - | - | | `DODO_PAYMENTS_API_KEY` | Yes | None | Authenticates requests to the Dodo Payments API. | | `DODO_PAYMENTS_WEBHOOK_KEY` | Yes | None | Verifies the signature of incoming webhooks. | | `DODO_PAYMENTS_RETURN_URL` | No | `http://localhost:8080` | The URL that checkout sends the customer to after payment. | | `DODO_PAYMENTS_ENVIRONMENT` | No | `test_mode` | `test_mode` or `live_mode`. | | `PORT` | No | `8000` | The port the server listens on. | The server exits at startup if either required key is missing. `.env.example` sets `PORT` and `DODO_PAYMENTS_RETURN_URL` to port `8080`. This page uses port `8000`, so set both to `8000` as shown, or replace `8000` with `8080` in the commands on this page. > [!WARNING] > > Never commit your `.env` file to version control. The repository's `.gitignore` already excludes it. **5. Add Your Products** Replace the sample product in `internal/lib/products.go` with your products. Copy each product ID from **Products** in the dashboard: ```go theme={null} var Products = []Product{ { ProductID: "pdt_001", // Replace with your product ID Name: "Basic Plan", Description: "Get access to basic features and support", Price: 9999, // in cents Features: []string{ "Access to basic features", "Email support", "1 Team member", "Basic analytics", }, }, // ... add more products } ``` `Price` sets only the price that the pricing page displays, in the smallest currency unit: `9999` displays as \$99.99. Checkout charges the price of the product in Dodo Payments. **6. Run the Development Server** ```bash theme={null} make run ``` `make run` builds the server into `bin/server` and starts it. To run the server without building a binary first, run: ```bash theme={null} go run cmd/server/main.go ``` Open [http://localhost:8000](http://localhost:8000) to see your pricing page. > [!TIP] > > You see a dark-themed pricing page that lists your products, ready to purchase. ## Project Structure The repository has this layout: ```text theme={null} go-boilerplate/ ├── cmd/ │ └── server/ # Application entry point (main.go) ├── internal/ │ ├── api/ # API handlers: checkout.go, portal.go, webhook.go │ ├── core/ # Configuration loading (config.go) │ └── lib/ # Shared logic: products.go, customers.go ├── templates/ # HTML templates: base.html, index.html ├── Makefile # Build and run commands ├── go.mod # Go module definition ├── go.sum # Dependency checksums ├── .env.example # Environment template └── README.md ``` ## API Endpoints The boilerplate includes the following pre-configured endpoints: | Endpoint | Method | Description | | - | - | - | | `/` | GET | Pricing page that lists the products in `internal/lib/products.go`. | | `/api/checkout` | POST | Creates a checkout session. Send `product_id`, plus optional `quantity` (default `1`) and `customer` (`email`, `name`, `phone`). Returns `session_id` and `checkout_url`. | | `/api/webhook` | POST | Verifies and handles Dodo Payments webhooks. Returns `401` when the signature check fails. | | `/api/customer-portal` | POST | Returns a Customer Portal link in `portal_url`. Send `customer_id`, or `email` with an optional `name`. With only an email, the handler looks up the customer and creates one if none exists. | | `/health` | GET | Health check. Returns `OK`. | ## Customization ### Update Product Information Edit `internal/lib/products.go` to change: * Product IDs (from **Products** in your Dodo Payments dashboard) * Names * Pricing shown on the pricing page * Features * Descriptions ```go theme={null} var Products = []Product{ { ProductID: "pdt_001", // Replace with your product ID Name: "Basic Plan", Description: "Get access to basic features and support", Price: 9999, Features: []string{ "Access to basic features", "Email support", "1 Team member", "Basic analytics", }, }, } ``` The pricing page template adds a `/mo` suffix to every price and shows **Custom** instead of a price when `Price` is `100000` or more. To change this, edit `templates/index.html`. ### Pre-fill Customer Data In `templates/index.html`, the `handleCheckout` function sends hardcoded customer data to `/api/checkout`. Replace it with your signed-in user's data: ```javascript theme={null} const customerData = { name: "John Doe", // Replace with actual logged-in user's name email: "john@example.com" // Replace with actual logged-in user's email }; ``` The `handlePortal` function reuses this customer data, and falls back to the same sample name and email. In a production app, inject these values from your authentication system in both functions. ## Webhook Events `internal/api/webhook.go` verifies each request with `client.Webhooks.Unwrap` and the key in `DODO_PAYMENTS_WEBHOOK_KEY`, then routes the event by its `type`. These events have a handler, and each handler logs the event data: | Event | Description | | - | - | | `payment.succeeded` | Triggered when a payment is successful | | `payment.failed` | Triggered when a payment attempt fails | | `subscription.active` | Triggered when a subscription becomes active | | `subscription.renewed` | Triggered when a subscription renews for the next billing period | | `subscription.updated` | Triggered when any subscription field changes | | `subscription.cancelled` | Triggered when a subscription is cancelled | The handler also accepts `subscription.on_hold`, `subscription.failed`, `subscription.expired`, and `subscription.plan_changed` without any action, and logs every other event type as unhandled. It responds with `200` to every verified event. For all event types, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). Add your business logic to the handler functions to: * Update user permissions in your database * Send confirmation emails * Provision access to digital products * Track analytics and metrics ## Testing Webhooks Locally Dodo Payments can't reach `localhost`. To receive webhooks during development, expose your local server with a tunnel such as [ngrok](https://ngrok.com/): ```bash theme={null} ngrok http 8000 ``` In the [Dodo Payments Dashboard](https://app.dodopayments.com/developer/webhooks), add an endpoint with the forwarding URL that ngrok prints, followed by `/api/webhook`: ```text theme={null} https://your-ngrok-url.ngrok.io/api/webhook ``` Copy the endpoint's signing key into `DODO_PAYMENTS_WEBHOOK_KEY`, then restart the server. ## Deployment ### Build for Production `make build` compiles the server into `bin/server`: ```bash theme={null} make build ``` To build and start the binary without `make`, run: ```bash theme={null} go build -o bin/server cmd/server/main.go ./bin/server ``` ### Deploy to Vercel [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/dodopayments/go-boilerplate) After you deploy, add the variables from your `.env` file to the Vercel project settings, because `.env` isn't in the repository. Then set your webhook endpoint in the dashboard to `https://yourdomain.com/api/webhook`. ### Docker Create a `Dockerfile` in the project root. The build stage must use Go 1.24.4 or later to match `go.mod`: ```dockerfile theme={null} FROM golang:1.24-alpine AS builder WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY . . RUN go build -o bin/server cmd/server/main.go FROM alpine:latest WORKDIR /app COPY --from=builder /app/bin/server . COPY --from=builder /app/templates ./templates EXPOSE 8000 CMD ["./server"] ``` The final image copies `templates/` next to the binary, because the server loads the templates from the working directory. Build and run the image: ```bash theme={null} docker build -t go-dodo . docker run -p 8000:8000 --env-file .env go-dodo ``` The container listens on the `PORT` value from `.env`, so keep `PORT=8000` to match the port mapping. ### Production Considerations > [!WARNING] > > Before you deploy to production: > > * Set `DODO_PAYMENTS_ENVIRONMENT` to `live_mode`. > * Use a live mode API key from the dashboard. > * Point the webhook endpoint at your production domain, and use that endpoint's signing key. > * Set `DODO_PAYMENTS_RETURN_URL` to a page on your production domain. > * Serve every endpoint over HTTPS. ## Troubleshooting > [accordion] Build errors or missing dependencies > > Check that `go version` reports Go 1.24.4 or later, then download the modules again: > > ```bash theme={null} > go mod tidy > go mod download > ``` > [accordion] Checkout session creation fails > > **Common causes:** > > * The product ID is invalid. Check that it exists under **Products** in the same mode as your API key. > * The API key or `DODO_PAYMENTS_ENVIRONMENT` in `.env` is wrong. A test mode key needs `test_mode`. > * For the exact error, check the server logs. The handler logs every failed request before it returns `500`. > [accordion] Webhooks not receiving events > > For local testing, expose your server with [ngrok](https://ngrok.com): > > ```bash theme={null} > ngrok http 8000 > ``` > > Set the webhook URL in your [Dodo Payments dashboard](https://app.dodopayments.com/developer/webhooks) to the ngrok URL. Then set `DODO_PAYMENTS_WEBHOOK_KEY` in `.env` to that endpoint's signing key. If the server logs `webhook verification failed`, the key doesn't match the endpoint. > [accordion] Templates not loading > > The server loads `templates/base.html` and `templates/index.html` from the working directory. Start the server from the project root, or change the template paths in `cmd/server/main.go`. ## Learn More > [card] [Go SDK](/developer-resources/sdks/go) > > Complete Go SDK documentation > [card] [Webhooks Documentation](/developer-resources/webhooks) > > Learn about all webhook events and best practices > [card] [Checkout Sessions](/developer-resources/checkout-session) > > Deep dive into checkout session configuration > [card] [API Reference](/api-reference/introduction) > > Complete Dodo Payments API documentation ## Support For help with the boilerplate: * Ask questions in the [Discord community](https://discord.gg/bYqAp4ayYh). * Check the [GitHub repository](https://github.com/dodopayments/go-boilerplate) for issues and updates. * Contact the [support team](mailto:support@dodopayments.com). # Handle Payment Failures Source: https://docs.dodopayments.com/developer-resources/handle-payment-failures Read failure reasons from the payment object, decide whether to retry, and recover payments safely without exposing sensitive information to customers. When a payment fails, Dodo Payments provides a standardized `error_code` and human-readable `error_message`. This guide shows how to read those fields, decide whether to retry, and recover the payment safely. ## How Dodo Payments Reports a Failure Every failed payment carries these fields on the payment object: | Field | Type | Description | | - | - | - | | `status` | string | `failed` for a failed payment. Other non-success states: `cancelled`, `requires_customer_action`, `requires_payment_method`. | | `error_code` | string \| null | Standardized failure reason, e.g., `INSUFFICIENT_FUNDS` or `PROCESSING_ERROR`. See [Transaction Failures](/api-reference/transaction-failures) for the full list. | | `error_message` | string \| null | Merchant-facing explanation with recommended action. Not for customers. | | `retry_attempt` | integer | `0` for the original charge. `1` or higher for scheduled subscription renewal retries. | > [!NOTE] > > `error_code` and `error_message` are `null` until a payment fails. Always check `status` first. > [!WARNING] > > `error_message` is merchant-facing and can reveal fraud-related reasons. Never show it to customers. Map `error_code` to customer-safe wording instead (see [Surface Errors to Customers Safely](#surface-errors-to-customers-safely)). ## The `payment.failed` Webhook The `payment.failed` webhook is the most reliable way to detect a failure. The event wraps the full payment object in `data`: ```json payment.failed payload expandable theme={null} { "business_id": "bus_P3SXLcppjXgagmHS", "type": "payment.failed", "timestamp": "2025-08-04T05:36:41.609359Z", "data": { "payload_type": "Payment", "payment_id": "pay_2IjeQm4hqU6RA4Z4kwDee", "status": "failed", "error_code": "PROCESSING_ERROR", "error_message": "An error occurred while processing your card. Try again in a little bit.", "retry_attempt": 0, "subscription_id": null, "subscription_ids": [], "currency": "USD", "total_amount": 400, "payment_method": "card", "card_last_four": "0119", "card_network": "visa", "payment_link": "https://test.checkout.dodopayments.com/cbq", "customer": { "customer_id": "cus_8VbC6JDZzPEqfB", "email": "test@acme.com", "name": "Test user" } } } ``` A minimal handler reads `error_code` and routes based on it: ```javascript Node.js expandable theme={null} import { Webhook } from "standardwebhooks"; import express from "express"; const app = express(); // Mount the raw body parser so the exact payload is available for verification app.use(express.raw({ type: "application/json" })); const webhook = new Webhook(process.env.DODO_PAYMENTS_WEBHOOK_KEY); app.post("/webhooks/dodo", async (req, res) => { // Verify the signature against the raw body before trusting the payload const payload = req.body.toString(); await webhook.verify(payload, req.headers); const event = JSON.parse(payload); if (event.type === "payment.failed") { const payment = event.data; console.log( `Payment ${payment.payment_id} failed: ${payment.error_code} (${payment.error_message})` ); // subscription_id is null for multi-subscription payments, so check subscription_ids if (payment.subscription_ids.length > 0) { // Subscription payment. If Payment Retries is on, Dodo retries failed renewals. // On-demand charges are never retried automatically: handle those yourself. await flagSubscriptionPaymentIssue(payment.subscription_ids, payment.error_code); } else { // One-time payment — prompt the customer to try again await notifyCustomerOfFailedPayment(payment.customer.customer_id, payment.error_code); } } res.json({ received: true }); }); ``` ```python Python expandable theme={null} import os from fastapi import FastAPI, Request from standardwebhooks import Webhook app = FastAPI() webhook = Webhook(os.environ["DODO_PAYMENTS_WEBHOOK_KEY"]) @app.post("/webhooks/dodo") async def handle_webhook(request: Request): # Verify the signature before trusting the payload payload = await request.body() webhook.verify(payload, dict(request.headers)) event = await request.json() if event["type"] == "payment.failed": payment = event["data"] print( f"Payment {payment['payment_id']} failed: " f"{payment['error_code']} ({payment['error_message']})" ) # subscription_id is null for multi-subscription payments, so check subscription_ids if payment["subscription_ids"]: # Subscription payment. If Payment Retries is on, Dodo retries failed renewals. # On-demand charges are never retried automatically: handle those yourself. flag_subscription_payment_issue(payment["subscription_ids"], payment["error_code"]) else: # One-time payment — prompt the customer to try again notify_customer_of_failed_payment(payment["customer"]["customer_id"], payment["error_code"]) return {"received": True} ``` > [!TIP] > > Always verify the webhook signature before processing. See the [Webhooks guide](/developer-resources/webhooks) for the full setup, including signature verification and idempotency. ## Decide Whether to Retry: Soft vs. Hard Declines The `error_code` tells you whether retrying the same payment method is worthwhile. | Decline type | Examples | Action | | - | - | - | | **Soft decline** | `INSUFFICIENT_FUNDS`, `DO_NOT_HONOR`, `TRANSACTION_NOT_ALLOWED`, `PROCESSING_ERROR`, `NETWORK_ERROR`, `TRY_AGAIN_LATER` | Retry after a delay or once the customer fixes their input. | | **Hard decline** | `STOLEN_CARD`, `LOST_CARD`, `PICKUP_CARD`, `FRAUDULENT`, `TRANSACTION_NOT_APPROVED`, `INVALID_ACCOUNT` | Do not retry the same card. Ask the customer for a different payment method. | See [Transaction Failures](/api-reference/transaction-failures) for the full list of decline types and recommended actions. ## Handling Failures at Checkout vs. on Renewal How you recover depends on whether the customer is present. > [tab] At checkout (customer present) > > The customer is actively checking out. Surface a clear message and let them retry or use another card. > > * `requires_payment_method` — the customer never provided a payment method. This is usually a checkout drop-off, not a decline. Re-engage the customer to complete payment (see [Abandoned Cart Recovery](/features/recovery/abandoned-cart-recovery)). > * `requires_customer_action` — additional authentication (such as 3DS) is needed. Have the customer complete it. See [3D Secure](/features/payment-methods/cards#3d-secure-authentication). > [tab] On subscription renewal (customer not present) > > The customer is not present. When a renewal fails, the subscription moves to `on_hold` and `subscription.on_hold` fires. If your business has a grace period, it moves to `past_due` first (`subscription.past_due`) and keeps access until the grace period ends. > > * **Soft declines** are retried automatically if you turn on [Subscription Payment Retries](/features/recovery/payment-retries) (off by default). Retries cover scheduled renewals only, not on-demand charges. > * **Hard declines** (and exhausted retries) on scheduled renewals are recovered with [Subscription Dunning](/features/recovery/subscription-dunning), which emails the customer to update their payment method. For on-demand charge failures, see [On-Demand Subscriptions](/developer-resources/ondemand-subscriptions#handling-failed-charges). > > See [Subscription Integration Guide](/developer-resources/subscription-integration-guide#handling-subscription-on-hold) for the full on-hold → reactivate flow. ## Retrying a Failed Payment **Subscriptions:** Enable [Subscription Payment Retries](/features/recovery/payment-retries) to recover soft declines automatically. To retry immediately instead of waiting for the schedule, use [Manual Payment Retry](/features/recovery/manual-retry) from the dashboard or API. You can also trigger recovery by having the customer update their payment method via the [Update Payment Method API](/api-reference/subscriptions/update-payment-method), which charges any outstanding dues. **One-time payments:** Resend the checkout or `payment_link` so the customer can try again with a different method. There is no automatic retry for one-time payments. > [!WARNING] > > Do not retry hard declines against the same card. Card networks flag repeated declines as abusive, which hurts your authorization rate. ## Surface Errors to Customers Safely Show customers a friendly message, never the raw `error_code` or merchant-facing `error_message`. > [!NOTE] > > On Dodo Payments-controlled surfaces (checkout, [Customer Portal](/features/customer-portal), dunning emails), this mapping is already done for you, including fallback to a generic message for fraud-related declines. You only need the mapping below where you render failures in your own product. ```javascript Customer-facing messaging expandable theme={null} const CUSTOMER_MESSAGES = { INSUFFICIENT_FUNDS: "Your card has insufficient funds. Please use another card.", EXPIRED_CARD: "Your card has expired. Please use a card with a valid expiry date.", INCORRECT_CVC: "The security code (CVC) is incorrect. Please re-enter it.", }; function customerMessage(errorCode) { // Sensitive declines must never reveal the real reason const SENSITIVE = ["STOLEN_CARD", "LOST_CARD", "PICKUP_CARD", "FRAUDULENT"]; if (SENSITIVE.includes(errorCode)) { return "Your card was declined. Please contact your bank or use another card."; } return CUSTOMER_MESSAGES[errorCode] ?? "Your payment could not be processed. Please try another card."; } ``` > [!WARNING] > > Never reveal the real reason for `STOLEN_CARD`, `LOST_CARD`, `PICKUP_CARD`, or `FRAUDULENT`. Surfacing these can tip off a fraudulent actor. Show a generic decline message and log the specific `error_code` internally only. ## Related > [card] [Transaction Failures](/api-reference/transaction-failures) > > Every decline code, its type, and the recommended action. > [card] [Error Codes](/api-reference/error-codes) > > API and business-logic errors that are not card declines. > [card] [Subscription Payment Retries](/features/recovery/payment-retries) > > Automatic recovery of soft declines on subscription renewals. > [card] [Subscription Dunning](/features/recovery/subscription-dunning) > > Email sequences that recover hard declines. > [card] [Payment Webhooks](/developer-resources/webhooks/intents/payment) > > Full payload schema for payment events. > [card] [Testing Failures](/miscellaneous/testing-process) > > Test cards that simulate declines and renewal failures. # Hono Adaptor Source: https://docs.dodopayments.com/developer-resources/hono-adaptor Add Dodo Payments checkout, Customer Portal, and webhook route handlers to a Hono app with the @dodopayments/hono adaptor. The `@dodopayments/hono` adaptor gives your Hono app three route handlers: `Checkout` returns checkout URLs, `CustomerPortal` sends a customer to the Customer Portal, and `Webhooks` verifies webhook requests and calls your event handlers. > [card] [Checkout Handler](#checkout-route-handler) > > Create payment links and checkout sessions from your Hono app. > [card] [Customer Portal](#customer-portal-route-handler) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-route-handler) > > Verify and process Dodo Payments webhook events. ## Installation **1. Install the Package** Run the following command in your project root: ```bash theme={null} npm install @dodopayments/hono ``` The package requires Hono 4.8.9 or later. **2. Set Up Environment Variables** Create a `.env` file in your project root: ```env expandable theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret # test_mode or live_mode DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_RETURN_URL=https://yourapp.com/success ``` Create the API key under **Developer → API Keys**. Add your webhook endpoint under **Developer → Webhooks** and copy its signing secret into `DODO_PAYMENTS_WEBHOOK_KEY`. While you build, use a test mode API key with `DODO_PAYMENTS_ENVIRONMENT=test_mode`, because a test mode key works only against test mode. `DODO_PAYMENTS_RETURN_URL` is optional. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## Route Handler Examples > [!NOTE] > > The examples register routes on a Hono app created with `new Hono()`. The handlers read the request body themselves, so they need no body-parsing middleware. > [tab] Checkout Handler > > > [!NOTE] > > > > Use this handler to integrate Dodo Payments checkout into your Hono app. Supports static (GET) and checkout session (POST) flows. > > ```typescript Hono Route Handler expandable theme={null} > // route.ts > import { Hono } from 'hono' > import { Checkout } from '@dodopayments/hono' > > const app = new Hono() > > app.get( > "/api/checkout", > Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > type: 'static' > }) > ); > > app.post( > "/api/checkout-session", > Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > type: 'session' > }) > ); > ``` > > ```bash Static Checkout cURL theme={null} > curl --request GET \ > --url 'https://example.com/api/checkout?productId=pdt_fqJhl7pxKWiLhwQR042rh' > ``` > > ```bash Checkout Session cURL expandable theme={null} > curl --request POST \ > --url https://example.com/api/checkout-session \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_QMDuvLkbVzCRWRQjLNcs", > "quantity": 1 > } > ], > "customer": { > "email": "test@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal Handler > > > [!NOTE] > > > > Use this handler to let customers manage their subscriptions and details in the Dodo Payments Customer Portal. > > ```typescript Hono Route Handler expandable theme={null} > // route.ts > import { Hono } from 'hono' > import { CustomerPortal } from '@dodopayments/hono' > > const app = new Hono() > app.get( > "/api/customer-portal", > CustomerPortal({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT > }) > ); > ``` > > ```bash Customer Portal cURL theme={null} > curl --request GET \ > --url 'https://example.com/api/customer-portal?customer_id=cus_9VuW4K7O3GHwasENg31m&send_email=true' > ``` > [tab] Webhook Handler > > > [!NOTE] > > > > Use this handler to receive, verify, and process Dodo Payments webhook events in your Hono app. > > ```typescript Hono Route Handler expandable theme={null} > // route.ts > import { Hono } from 'hono' > import { Webhooks } from '@dodopayments/hono' > > const app = new Hono() > app.post( > "/api/webhooks", > Webhooks({ > webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, > onPayload: async (payload) => { > // Handle Payload Here > console.log(payload) > } > }) > ); > ``` ## Checkout Route Handler > [!NOTE] > > The adaptor supports all three Dodo Payments checkout flows. Set `type` in the handler config to choose the flow a route serves. Every flow responds with JSON that contains a `checkout_url` for the customer to open. * **Static Payment Links:** `type: "static"`, GET. Builds a payment link for one product from query parameters, after checking that the product exists. * **Dynamic Payment Links (deprecated):** `type: "dynamic"`, POST. Creates a one-time payment or a subscription with a payment link, depending on whether the product is recurring. * **Checkout Sessions:** `type: "session"`, POST. Creates a checkout session from a product cart and customer details. Use this flow for new integrations. `Checkout` takes these options: | Option | Type | Description | | - | - | - | | `bearerToken` | `string` | Your Dodo Payments API key. | | `environment` | `string` | `test_mode` or `live_mode`. Defaults to `live_mode`. | | `returnUrl` | `string` | Optional. The URL that checkout redirects the customer to after payment. A `return_url` in a POST body takes precedence. | | `type` | `string` | The checkout flow: `static`, `dynamic`, or `session`. | Register the handler for GET when `type` is `static`, and for POST when `type` is `dynamic` or `session`. The handler treats every request that isn't a POST as a static checkout request. > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_nZuwz45WAs64n3l07zpQR`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's street address. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's postal or ZIP code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > The payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed to checkout as metadata, for example `metadata_orderId=123`. > > A disable flag takes effect only when it's `true` and the matching field has a value, for example `email` with `disableEmail`. The handler passes these parameters to a [static payment link](/developer-resources/integration-guide#static-payment-links). > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters, or a product that doesn't exist in your account, also result in a 400 response. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_fqJhl7pxKWiLhwQR042rh?quantity=1&redirect_url=https%3A%2F%2Fyourapp.com%2Fsuccess" > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. The handler retrieves the product, then creates a subscription if the product is recurring and a one-time payment otherwise. > * The body needs `billing` (with `street`, `city`, `state`, `country`, and `zipcode`) and `customer`, plus `product_id` (with an optional `quantity`) or `product_cart`. Subscriptions need `product_id`. > * The handler also forwards `metadata`, `allowed_payment_method_types`, `billing_currency`, `discount_codes` (or the deprecated `discount_code`), `return_url`, `show_saved_payment_methods`, and `tax_id`. For subscriptions, it forwards `addons`, `on_demand`, and `trial_period_days` too. It ignores other fields. > * For field details, refer to: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic Checkout calls the deprecated `POST /payments` and `POST /subscriptions` endpoints. Use Checkout Sessions for new integrations. > > ### Response Format > > Dynamic checkout returns a JSON response with the payment link as the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/cbq" > } > ``` > [accordion] Checkout Sessions (POST) > > Send a checkout session payload as the JSON body. The handler creates a checkout session, which handles the complete payment flow for one-time purchases and subscriptions, and returns its `checkout_url`. `product_cart` is required and must contain at least one product. > > Each `checkout_url` works once and expires after 24 hours, or after 15 minutes when you pass `confirm: true`. A session created with `payment_method_id` returns no `checkout_url`, so the handler responds with 400. > > Refer to [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session) for more details and a complete list of supported fields. > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa" > } > ``` ## Customer Portal Route Handler The Customer Portal Route Handler creates a Customer Portal session for the customer in `customer_id` and redirects the request to the portal link. `CustomerPortal` takes the `bearerToken` and `environment` options, the same as `Checkout`. If Dodo Payments can't create the session, the handler returns 500. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, sends an email to the customer with the portal link. > [!WARNING] > > Returns 400 if `customer_id` is missing. The handler doesn't authenticate the request and opens the portal for any `customer_id` it receives, so put the route behind your own authentication and pass only the signed-in user's customer ID. ## Webhook Route Handler The webhook handler verifies each request with your webhook secret, passed as `webhookKey`, then calls your event handlers. It reads the raw request body itself, so the route needs no body-parsing middleware. * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`, following the [Standard Webhooks](https://standardwebhooks.com/) specification. Returns 401 if verification fails. * **Payload Validation:** Validated with Zod. Returns 400 for invalid payloads. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Internal error during verification * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200 when they finish. The handler doesn't catch errors that your event handlers throw. ### Supported Webhook Event Handlers Every handler is optional and async. For the payload of each event, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` *** ## Prompt for LLM ```text theme={null} You are an expert Hono developer assistant. Your task is to guide a user through integrating the @dodopayments/hono adapter into their existing Hono project. The @dodopayments/hono adapter provides route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed to plug directly into a Hono app. First, install the necessary package. Use the package manager appropriate for the user's project (npm, yarn, or bun): npm install @dodopayments/hono The package requires Hono 4.8.9 or later. --- Here's how you should structure your response: 1. Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/hono adapter would you like to integrate into your project? You can choose one or more of the following: - Checkout Route Handler (for handling product checkouts) - Customer Portal Route Handler (for managing customer subscriptions/details) - Webhook Route Handler (for receiving Dodo Payments webhook events) - All (integrate all three)" --- 2. Based on the user's selection, provide detailed integration steps for each chosen functionality. --- **If Checkout Route Handler is selected:** **Purpose**: This handler manages two checkout flows. Static checkout and checkout sessions both return JSON responses with checkout URLs for programmatic handling. **Integration**: Create routes in your Hono app for static (GET) and checkout sessions (POST). import { Hono } from 'hono' import { Checkout } from '@dodopayments/hono' const app = new Hono() app.get( "/api/checkout", Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, type: 'static' }) ); // For checkout sessions app.post( "/api/checkout-session", Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, type: 'session' }) ); Config Options: bearerToken: Your Dodo Payments API key (recommended to be stored in DODO_PAYMENTS_API_KEY env variable). returnUrl (optional): URL to redirect the user after successful checkout. A return_url in the POST body takes precedence. environment: "test_mode" or "live_mode" (defaults to "live_mode") type: "static" (GET) or "session" (POST) GET (static checkout) expects query parameters: productId (required) quantity, customer fields (fullName, email, etc.), and metadata (metadata_*) are optional. Returns: {"checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_fqJhl7pxKWiLhwQR042rh?quantity=1"} POST (checkout sessions) - (Recommended) A more customizable checkout experience. Returns JSON with checkout_url: Parameters are sent as a JSON body, and product_cart is required. Supports both one-time and recurring payments. Returns: {"checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa"}. For a complete list of supported fields, refer to: Checkout Sessions Integration Guide: https://docs.dodopayments.com/developer-resources/checkout-session If Customer Portal Route Handler is selected: Purpose: This route allows customers to manage their subscriptions via the Dodo Payments portal. It redirects the request to the portal link. Integration: import { Hono } from 'hono' import { CustomerPortal } from '@dodopayments/hono' const app = new Hono() app.get( "/api/customer-portal", CustomerPortal({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT }) ); Query Parameters: customer_id (required): e.g., ?customer_id=cus_123 send_email (optional): if true, customer is emailed the portal link Returns 400 if customer_id is missing. The handler does not authenticate the request, so protect the route with the app's own authentication and pass only the signed-in user's customer ID. If Webhook Route Handler is selected: Purpose: Processes incoming webhook events from Dodo Payments to trigger events in your app. Integration: import { Hono } from 'hono' import { Webhooks } from '@dodopayments/hono' const app = new Hono() app.post( "/api/webhooks", Webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, onPayload: async (payload) => { // Handle Payload Here console.log(payload) } }) ); Features: Only POST method is allowed — others return 405 Signature verification is performed using webhookKey. Returns 401 if invalid. Zod-based payload validation. Returns 400 if invalid schema. All handlers are async functions. onPayload runs for every event, before the event-specific handler. Supported Webhook Event Handlers: You may pass in any of the following handlers: onPayload onPaymentSucceeded onPaymentFailed onPaymentProcessing onPaymentCancelled onRefundSucceeded onRefundFailed onDisputeOpened, onDisputeExpired, onDisputeAccepted, onDisputeCancelled, onDisputeChallenged, onDisputeWon, onDisputeLost onSubscriptionActive, onSubscriptionOnHold, onSubscriptionRenewed, onSubscriptionPlanChanged, onSubscriptionCancelled, onSubscriptionFailed, onSubscriptionExpired, onSubscriptionUpdated, onSubscriptionPaused, onSubscriptionUnpaused, onSubscriptionUpdatePaymentMethod onLicenseKeyCreated onAbandonedCheckoutDetected, onAbandonedCheckoutRecovered onDunningStarted, onDunningRecovered onCreditAdded, onCreditDeducted, onCreditExpired, onCreditRolledOver, onCreditRolloverForfeited, onCreditOverageCharged, onCreditOverageReset, onCreditManualAdjustment, onCreditBalanceLow onEntitlementGrantCreated, onEntitlementGrantDelivered, onEntitlementGrantFailed, onEntitlementGrantRevoked onPayoutCreated, onPayoutOnHold, onPayoutInProgress, onPayoutFailed, onPayoutSuccess Environment Variable Setup: Make sure to define these environment variables in your project: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_ENVIRONMENT=test_mode (or live_mode) DODO_PAYMENTS_RETURN_URL=https://yourapp.com/success Use these inside your code as: process.env.DODO_PAYMENTS_API_KEY process.env.DODO_PAYMENTS_WEBHOOK_KEY Security Note: Do NOT commit secrets to version control. Use .env files locally and secrets managers in deployment environments (e.g., AWS, Vercel, Heroku, etc.). ``` # Inline Checkout Source: https://docs.dodopayments.com/developer-resources/inline-checkout Embed Dodo Payments checkout directly into your page layout. The inline checkout SDK renders a secure payment form that matches your page design. Inline checkout embeds a secure payment form directly into your page layout. Unlike [overlay checkout](/developer-resources/overlay-checkout), which opens as a modal, inline checkout becomes part of your page. You control the layout and can display your own order summary alongside the checkout form. ![Inline checkout form embedded in a product page with order summary](https://mintcdn.com/dodopayments/HpxJAc8zNlxzewa_/images/inline-checkout/cover.png?fit=max\&auto=format\&n=HpxJAc8zNlxzewa_\&q=85\&s=99c1a92ef01680248a421d3f057b02cd) ## How It Works Inline checkout renders a secure Dodo Payments frame into a container on your page. The frame handles collecting customer information and payment details. Your page displays items, totals, and other information. The SDK lets your page and the checkout frame communicate with each other. When checkout completes, Dodo Payments creates the payment, or the subscription for a subscription product, and sends a webhook so you can provision access. > [!NOTE] > > The inline checkout frame securely handles all sensitive payment information, ensuring PCI compliance without additional certification on your end. ## What Makes a Good Inline Checkout Customers need to know who they're buying from, what they're buying, and how much they're paying. Your implementation must include: ![Inline checkout example with required elements labeled](https://mintcdn.com/dodopayments/HpxJAc8zNlxzewa_/images/inline-checkout/example.png?fit=max\&auto=format\&n=HpxJAc8zNlxzewa_\&q=85\&s=c7c00fb01b76f7fb3d9831fc922b9fe9) Example inline checkout layout showing required elements 1. **Recurring information**: If recurring, show how often it recurs and the total to pay on renewal. If a trial, show the trial duration. 2. **Item descriptions**: A description of what's being purchased. 3. **Transaction totals**: Subtotal, total tax, and grand total, including currency. 4. **Dodo Payments footer**: The complete inline checkout frame, including the footer with Dodo Payments information, terms of sale, and privacy policy. 5. **Refund policy**: A link to your refund policy, if it differs from the Dodo Payments standard refund policy. > [!WARNING] > > Always display the complete inline checkout frame, including the footer. Removing or hiding legal information violates compliance requirements. ## Customer Journey The checkout flow depends on your checkout session configuration. Depending on how you configure the session, customers may see all information on [a single page](/features/single-page-checkout) or across multiple steps. **1. Customer opens checkout** You open inline checkout by passing a checkout URL. Use SDK events, such as `checkout.breakdown`, to show and update on-page information. ![Initial checkout page with items list and payment form](https://mintcdn.com/dodopayments/HpxJAc8zNlxzewa_/images/inline-checkout/1.png?fit=max\&auto=format\&n=HpxJAc8zNlxzewa_\&q=85\&s=b3def4e750c3c487196d22519503ae2a) **2. Customer enters their details** Inline checkout first asks customers to enter their email address, select their country, and (where required) enter their ZIP or postal code. This step gathers all necessary information to determine taxes and available payment options. You can prefill customer details and present saved addresses to streamline the experience. **3. Customer selects payment method** After entering their details, customers are presented with available payment methods and the payment form. Options may include credit or debit card, PayPal, Apple Pay, Google Pay, and other local payment methods based on their location. Display saved payment methods if available to speed up checkout. ![Available payment methods and card details form](https://mintcdn.com/dodopayments/HpxJAc8zNlxzewa_/images/inline-checkout/2.png?fit=max\&auto=format\&n=HpxJAc8zNlxzewa_\&q=85\&s=cbfa4958d0892feaa3aa474c4fe42c48) **4. Checkout completed** Dodo Payments routes every payment to the best acquirer for that sale to get the best possible chance of success. Customers enter a success workflow that you can build. ![Success screen with confirmation checkmark](https://mintcdn.com/dodopayments/HpxJAc8zNlxzewa_/images/inline-checkout/3.png?fit=max\&auto=format\&n=HpxJAc8zNlxzewa_\&q=85\&s=b75ac3d25abf7dc18a226904af72641b) **5. Dodo Payments creates the payment or subscription** Dodo Payments creates the payment, or the subscription for a subscription product, and sends a webhook so you can provision access. The payment method the customer used is held on file for renewals or subscription changes. ![Subscription created with webhook notification](https://mintcdn.com/dodopayments/HpxJAc8zNlxzewa_/images/inline-checkout/4.png?fit=max\&auto=format\&n=HpxJAc8zNlxzewa_\&q=85\&s=645d66da0aa02ac842384f85814c5922) ## Quick Start Install the SDK, initialize it for inline mode, and open checkout in a container element: ```typescript theme={null} import { DodoPayments } from "dodopayments-checkout"; DodoPayments.Initialize({ mode: "test", displayType: "inline", onEvent: (event) => { console.log("Checkout event:", event); }, }); DodoPayments.Checkout.open({ checkoutUrl: "https://test.checkout.dodopayments.com/session/cks_123", elementId: "dodo-inline-checkout" }); ``` > [!TIP] > > Ensure you have a container element with the corresponding `id` on your page: `
`. ## Step-by-Step Integration **1. Install the SDK** Install via npm, yarn, or pnpm: ```bash npm theme={null} npm install dodopayments-checkout ``` ```bash yarn theme={null} yarn add dodopayments-checkout ``` ```bash pnpm theme={null} pnpm add dodopayments-checkout ``` **2. Initialize the SDK for Inline Display** Initialize the SDK and specify `displayType: 'inline'`. Listen for the `checkout.breakdown` event to update your UI with real-time tax and total calculations: ```typescript theme={null} import { DodoPayments } from "dodopayments-checkout"; DodoPayments.Initialize({ mode: "test", displayType: "inline", onEvent: (event) => { if (event.event_type === "checkout.breakdown") { const breakdown = event.data?.message; // Update your UI with breakdown.subTotal, breakdown.tax, breakdown.total, etc. } }, }); ``` **3. Create a Container Element** Add an element to your HTML where the checkout frame will be injected: ```html theme={null}
``` **4. Open the Checkout** Call `DodoPayments.Checkout.open()` with the `checkoutUrl` and the `elementId` of your container: ```typescript theme={null} DodoPayments.Checkout.open({ checkoutUrl: "https://test.checkout.dodopayments.com/session/cks_123", elementId: "dodo-inline-checkout" }); ``` **5. Test Your Integration** 1. Start your development server: ```bash theme={null} npm run dev ``` 2. Test the checkout flow: * Enter your email and address details in the inline frame * Verify that your custom order summary updates in real-time * Test the payment flow using test credentials * Confirm redirects work correctly > [!TIP] > > You should see `checkout.breakdown` events logged in your browser console if you added a console log in the `onEvent` callback. **6. Go Live** When ready for production: 1. Change the mode to `'live'`: ```typescript theme={null} DodoPayments.Initialize({ mode: "live", displayType: "inline", onEvent: (event) => { // Handle events } }); ``` 2. Update your checkout URLs to use live checkout sessions from your backend 3. Test the complete flow in production ## Complete React Example This example demonstrates how to implement a custom order summary alongside the inline checkout, keeping them in sync using the `checkout.breakdown` event: ```tsx theme={null} "use client"; import { useEffect, useState } from 'react'; import { DodoPayments, CheckoutBreakdownData } from 'dodopayments-checkout'; export default function CheckoutPage() { const [breakdown, setBreakdown] = useState>({}); useEffect(() => { // 1. Initialize the SDK DodoPayments.Initialize({ mode: 'test', displayType: 'inline', onEvent: (event) => { // 2. Listen for the 'checkout.breakdown' event if (event.event_type === "checkout.breakdown") { const message = event.data?.message as CheckoutBreakdownData; if (message) setBreakdown(message); } } }); // 3. Open the checkout in the specified container DodoPayments.Checkout.open({ checkoutUrl: 'https://test.checkout.dodopayments.com/session/cks_123', elementId: 'dodo-inline-checkout' }); return () => DodoPayments.Checkout.close(); }, []); const format = (amt: number | null | undefined, curr: string | null | undefined) => amt != null && curr ? `${curr} ${(amt/100).toFixed(2)}` : '0.00'; const currency = breakdown.currency ?? breakdown.finalTotalCurrency ?? ''; return (
{/* Left Side - Checkout Form */}
{/* Right Side - Custom Order Summary */}

Order Summary

{breakdown.subTotal != null && (
Subtotal {format(breakdown.subTotal, currency)}
)} {breakdown.discount != null && breakdown.discount > 0 && (
Discount {format(breakdown.discount, currency)}
)} {breakdown.tax != null && (
Tax {format(breakdown.tax, currency)}
)}
{(breakdown.finalTotal ?? breakdown.total) != null && (
Total {format(breakdown.finalTotal ?? breakdown.total, breakdown.finalTotalCurrency ?? currency)}
)}
); } ``` ## API Reference ### Initialize Call `Initialize` once to set up the SDK: ```typescript theme={null} interface InitializeOptions { mode: "test" | "live"; displayType?: "overlay" | "inline"; onEvent: (event: CheckoutEvent) => void; } DodoPayments.Initialize(options); ``` | Option | Type | Required | Description | | - | - | - | - | | `mode` | `"test" \| "live"` | Yes | Environment mode. | | `displayType` | `"inline" \| "overlay"` | Yes | Must be set to `"inline"` to embed the checkout. | | `onEvent` | `function` | Yes | Callback function for handling checkout events. | ### Open Checkout Open the checkout frame in a container: ```typescript theme={null} export type FontSize = "xs" | "sm" | "md" | "lg" | "xl" | "2xl"; export type FontWeight = "normal" | "medium" | "bold" | "extraBold"; interface CheckoutOptions { checkoutUrl: string; elementId: string; options?: { showTimer?: boolean; showSecurityBadge?: boolean; manualRedirect?: boolean; payButtonText?: string; fontSize?: FontSize; fontWeight?: FontWeight; }; } DodoPayments.Checkout.open(options); ``` | Option | Type | Required | Description | | - | - | - | - | | `checkoutUrl` | `string` | Yes | Checkout session URL from the [create checkout session API](/api-reference/checkout-sessions/create) | | `elementId` | `string` | Yes | The `id` of the DOM element where the checkout should be rendered | | `options.showTimer` | `boolean` | No | Show or hide the session timer. Defaults to `true`. When set to `false`, you receive the `checkout.link_expired` event when the session expires. | | `options.showSecurityBadge` | `boolean` | No | Show or hide the security badge. Defaults to `true` | | `options.manualRedirect` | `boolean` | No | When `true`, prevent automatic redirects. Checkout emits `checkout.status` with the payment outcome and `checkout.redirect_requested` with the URL to open, and you handle navigation | | `options.payButtonText` | `string` | No | Custom text for the pay button | | `options.fontSize` | `"xs" \| "sm" \| "md" \| "lg" \| "xl" \| "2xl"` | No | Global font size for the checkout | | `options.fontWeight` | `"normal" \| "medium" \| "bold" \| "extraBold"` | No | Global font weight for the checkout | ### Close Checkout Programmatically remove the checkout frame and clean up event listeners: ```typescript theme={null} DodoPayments.Checkout.close(); ``` ### Check Status Check if the checkout frame is currently injected: ```typescript theme={null} const isOpen = DodoPayments.Checkout.isOpen(); // Returns: boolean ``` ### Events The SDK provides real-time events through the `onEvent` callback. For inline checkout, `checkout.breakdown` is particularly useful for syncing your UI: ```typescript theme={null} DodoPayments.Initialize({ mode: "test", displayType: "inline", onEvent: (event: CheckoutEvent) => { switch (event.event_type) { case "checkout.opened": // Frame has loaded break; case "checkout.form_ready": // Form is ready for user input break; case "checkout.breakdown": // Prices, taxes, or discounts updated break; case "checkout.customer_details_submitted": // Customer details submitted break; case "checkout.pay_button_clicked": // Customer clicked pay button break; case "checkout.redirect": // Checkout will redirect break; case "checkout.error": console.error("Error:", event.data?.message); break; case "checkout.link_expired": // Session expired (only when showTimer is false) break; } } }); ``` | Event | Description | | - | - | | `checkout.opened` | Checkout frame has been loaded | | `checkout.form_ready` | Form is ready for user input. Use this to hide loading states | | `checkout.breakdown` | Prices, taxes, or discounts updated | | `checkout.customer_details_submitted` | Customer details submitted | | `checkout.pay_button_clicked` | Customer clicked the pay button. Useful for analytics and tracking conversion funnels | | `checkout.redirect` | Checkout will redirect (e.g., to a bank page) | | `checkout.error` | An error occurred during checkout | | `checkout.link_expired` | The checkout session expired. Only received when `showTimer` is set to `false` | | `checkout.payment_method_selected` | Customer picked or changed a payment method in [single page checkout](/features/single-page-checkout#embedded-checkout-events). `data.message.payment_method_type` holds the method, for example `card` or `upi_collect`. Requires SDK `2.1.1` or later | ### Checkout Breakdown Data The `checkout.breakdown` event provides pricing and tax information: ```typescript theme={null} interface CheckoutBreakdownData { subTotal?: number; // Amount in cents discount?: number; // Amount in cents tax?: number; // Amount in cents total?: number; // Amount in cents currency?: string; // e.g., "USD" finalTotal?: number; // Final amount including adjustments finalTotalCurrency?: string; // Currency for the final total } ``` The event fires when the checkout frame loads, and again whenever the price is recalculated, for example when the customer selects a country or enters a postal code that changes the tax. **Field Details:** | Field | Description | | - | - | | `subTotal` | Sum of all line items before discounts or taxes | | `discount` | Total value of all applied discounts | | `tax` | Calculated tax amount. Updates dynamically as the user interacts with address fields | | `total` | Result of `subTotal - discount + tax` in the session's base currency | | `currency` | The ISO currency code (e.g., `"USD"`) for the standard subtotal, discount, and tax values. | | `finalTotal` | The actual amount the customer is charged. This may include additional foreign exchange adjustments or local payment method fees that aren't part of the basic price breakdown. | | `finalTotalCurrency` | The currency in which the customer is actually paying. This can differ from `currency` if [purchasing power parity](/features/purchasing-power-parity) or local currency conversion is active. | **Integration Tips:** 1. **Currency Formatting**: Prices are integers in the smallest currency unit, for example cents for USD. For two-decimal currencies, divide by 100 before formatting with `Intl.NumberFormat`. Zero-decimal currencies such as JPY have no smaller unit, so don't divide them. 2. **Handling Initial States**: When the checkout first loads, `tax` and `discount` may be `0` or `null` until the user provides their billing information or applies a code. Handle these states gracefully (e.g., showing a dash `—` or hiding the row). 3. **The "Final Total" vs "Total"**: While `total` gives you the standard price calculation, `finalTotal` is the source of truth for the transaction. If `finalTotal` is present, it reflects exactly what will be charged to the customer's card. 4. **Real-time Feedback**: Use the `tax` field to show users that taxes are being calculated in real-time. This provides a "live" feel to your checkout page and reduces friction during the address entry step. ## CDN Implementation For quick integration without a build step, load the SDK from CDN: ```html theme={null} Dodo Payments Inline Checkout
``` ## Update Payment Method Inline checkout supports payment method updates for subscriptions. When a customer needs to update their payment method for an active subscription or to reactivate an on-hold subscription, you can render the update flow directly within your page layout. ### How It Works 1. Call the [Update Payment Method API](/features/subscription#update-payment-method-for-active-subscription) to get a `payment_link`: ```typescript theme={null} // On your server. `client` is the Dodo Payments server SDK (`new DodoPayments()` from the `dodopayments` package). const response = await client.subscriptions.updatePaymentMethod('sub_123', { payment_method: { type: 'new', return_url: 'https://example.com/return' } }); ``` 2. Pass the returned `payment_link` as the `checkoutUrl` to open inline checkout: ```typescript theme={null} DodoPayments.Checkout.open({ checkoutUrl: response.payment_link, elementId: "dodo-inline-checkout" }); ``` The inline frame renders only the payment method collection form. Customers can enter new card details or select a saved payment method without leaving your page. ### For On-Hold Subscriptions When updating the payment method for a subscription in `on_hold` status, Dodo Payments automatically creates a charge for any remaining dues. Monitor the `payment.succeeded` and `subscription.active` webhooks to confirm reactivation. ```typescript theme={null} const response = await client.subscriptions.updatePaymentMethod('sub_123', { payment_method: { type: 'new', return_url: 'https://example.com/return' } }); if (response.payment_id) { // Charge created for remaining dues DodoPayments.Checkout.open({ checkoutUrl: response.payment_link, elementId: "dodo-inline-checkout" }); } ``` > [!TIP] > > You can also use an existing saved payment method instead of collecting new details by passing `type: 'existing'` with a `payment_method_id` to the Update Payment Method API. ## Error Handling Always implement error handling in your `onEvent` callback: ```typescript theme={null} DodoPayments.Initialize({ mode: "test", displayType: "inline", onEvent: (event: CheckoutEvent) => { if (event.event_type === "checkout.error") { console.error("Checkout error:", event.data?.message); // Show user-friendly error message } } }); ``` > [!WARNING] > > Always handle the `checkout.error` event to provide a good user experience when errors occur. ## Best Practices 1. **Responsive Design**: Ensure your container element has enough width and height. The iframe will typically expand to fill its container. 2. **Synchronization**: Use the `checkout.breakdown` event to keep your custom order summary or pricing tables in sync with what the user sees in the checkout frame. 3. **Skeleton States**: Show a loading indicator in your container until the `checkout.opened` event fires. 4. **Cleanup**: Call `DodoPayments.Checkout.close()` when your component unmounts to clean up the iframe and event listeners. > [!NOTE] > > For dark mode implementations, use `#0d0d0d` as the background color for optimal visual integration with the inline checkout frame. ## Payment Status Validation > [!WARNING] > > Do not rely solely on inline checkout events to determine payment success or failure. Always implement server-side validation using webhooks and/or polling. ### Why Server-Side Validation is Essential While inline checkout events provide real-time feedback, they should not be your only source of truth for payment status. Network issues, browser crashes, or users closing the page can cause events to be missed. To ensure reliable payment validation: 1. **Listen to webhook events** - Dodo Payments sends webhooks for payment status changes 2. **Implement a polling mechanism** - Your frontend should poll your server for status updates 3. **Combine both approaches** - Use webhooks as the primary source and polling as a fallback ### Recommended Architecture ```mermaid theme={null} flowchart TB subgraph Frontend["Your Frontend"] IC[Inline Checkout
Dodo iframe] CP[Your Checkout Page] IC -->|events| CP end subgraph Server["Your Server"] WH[Webhook Handler] DB[(Database)] API[Status API] WH --> DB API --> DB end subgraph Dodo["Dodo Payments"] PP[Payment Processor] end CP -->|Poll for status| API PP -->|Webhooks| WH IC -.->|Payment request| PP ``` ### Implementation Steps **1. Listen for checkout events** - When the user clicks pay, start preparing to verify the status: ```typescript theme={null} onEvent: (event) => { if (event.event_type === 'checkout.pay_button_clicked') { // Start polling your server for confirmed status startPolling(); } } ``` **2. Poll your server** - Create an endpoint that checks your database for the payment status (updated by webhooks): ```typescript theme={null} // Poll every 2 seconds until status is confirmed const interval = setInterval(async () => { const { status } = await fetch(`/api/payments/${paymentId}/status`).then(r => r.json()); if (status === 'succeeded' || status === 'failed') { clearInterval(interval); handlePaymentResult(status); } }, 2000); ``` **3. Handle webhooks server-side** - Update your database when Dodo sends `payment.succeeded` or `payment.failed` webhooks. See our [Webhooks documentation](/developer-resources/webhooks) for details. ## Troubleshooting > [accordion] Checkout frame is not appearing > > * Verify that `elementId` matches the `id` of a `div` that actually exists in the DOM > * Ensure `displayType: 'inline'` was passed to `Initialize` > * Check that the `checkoutUrl` is valid > [accordion] Taxes are not updating in my UI > > * Ensure you are listening for the `checkout.breakdown` event > * Taxes are only calculated after the user enters a valid country and postal code in the checkout frame ## Digital Wallets For detailed information about setting up Apple Pay, Google Pay, and other digital wallets, see the [Digital Wallets](/features/payment-methods/digital-wallets) page. ### Quick Setup for Apple Pay > [!NOTE] > > Domain verification is only required for inline (embedded) checkout. It is not required for hosted checkout. > [!WARNING] > > Apple Pay is not available for overlay checkout. Apple Pay is verified per-domain from the dashboard. **1. Open Wallet domains** Go to **Settings → Payment Methods** and, on the **Apple Pay** row, click **Manage domains**. ![Manage domains button on the Apple Pay row in Payment Methods settings](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/manage-domains.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=a96c60ee0eef744336df955f5148c573) Open Wallet domains from the Apple Pay row **2. Download the domain association file** From the Wallet domains panel, download the association file. ![Wallet domains panel with the Download file button](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/wallet-domains-panel.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=fb37db780807c0e92ffaa57d2140b91d) Download the Apple Pay domain association file **3. Register your domain** Click **Register domain** and enter the domain where you embed inline checkout (e.g. `shop.example.com`), then **Continue**. ![Register a domain form with a domain entered](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/register-domain.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=9c2bf22e51c8ff188a4e11b36b24c136) Register the domain where you embed inline checkout **4. Host the file on your domain** Host it at: ``` https://shop.example.com/.well-known/apple-developer-merchantid-domain-association ``` It must be served over HTTPS, reachable without redirects, and served with `Content-Type: application/octet-stream` or `text/plain`. **5. Verify the domain** Click **Verify domain**. Dodo Payments confirms the file is live and submits your domain to Apple. ![Verify your domain screen with the association file host path and Verify domain button](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/verify-domain.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=e9fcfe5b68320a0a22c644fb935c840b) Verify the hosted association file **6. Confirm it's active** When the status shows **Active**, Apple Pay is enabled for that domain. Use the **Enabled** toggle to turn it on or off per domain. ![Wallet domains list showing domains with an Active Apple Pay status and Enabled toggles](https://mintcdn.com/dodopayments/TklciB6vqCMDIBgH/images/apple-pay-domains/domains-active.png?fit=max\&auto=format\&n=TklciB6vqCMDIBgH\&q=85\&s=51a2bf473b1faf3db5776bbfa7140854) Verified domains show an Active status **7. Test the integration** 1. Open checkout on an Apple device 2. Verify Apple Pay button appears 3. Complete a test transaction ## Browser Support The Dodo Payments Checkout SDK supports: * Chrome (latest) * Firefox (latest) * Safari (latest) * Edge (latest) * IE11+ ## Inline vs Overlay Checkout Choose the right checkout type for your use case: | Feature | Inline | Overlay | | - | - | - | | Integration depth | Fully embedded in page | Modal on top of page | | Layout control | Full control | Limited | | Branding | Matches your page | Separate from page | | Implementation effort | Higher | Lower | | Best for | Custom checkout pages, high-conversion flows | Quick integration, existing pages | > [!TIP] > > Use inline checkout when you want maximum control over the checkout experience and consistent branding. Use overlay checkout for faster integration with minimal changes to your existing pages. ## Related Resources > [card] [Overlay Checkout](/developer-resources/overlay-checkout) > > Use the overlay checkout for quick modal-based integration. > [card] [Checkout Sessions API](/api-reference/checkout-sessions/create) > > Create checkout sessions to power your checkout experiences. > [card] [Webhooks](/developer-resources/webhooks) > > Handle payment events server-side with webhooks. > [card] [Integration Guide](/developer-resources/integration-guide) > > Complete guide to integrating Dodo Payments. For more help, visit our [Discord community](https://discord.gg/bYqAp4ayYh) or contact our developer support team. # Integration Guide Source: https://docs.dodopayments.com/developer-resources/integration-guide Create checkout sessions, payment links, and webhooks to accept payments with Dodo Payments. Start with an SDK or REST API. > [card] [Checkout Sessions](#checkout-sessions) > > Create a secure, hosted checkout for one-time payments and subscriptions. > [card] [Payment Links](#payment-links) > > Share a URL to collect payments without code. > [card] [Webhooks](#webhooks) > > Listen for payment events and fulfill orders. > [card] [API Reference](/api-reference/checkout-sessions/create) > > Full endpoint documentation and live testing. ## Prerequisites Before you start, you need: * A Dodo Payments account. * At least one product. Create it under **Products** in the dashboard. A subscription product with a non-zero price must meet the [subscription minimum](/features/adaptive-currency#minimum-amounts) for the currency the customer pays in: \$1.00 for USD. Currencies other than USD, EUR, and GBP must also be worth at least \$1.00. A \$0 subscription is also supported. * An API key. Create it under **Developer → API Keys** and store it in the `DODO_PAYMENTS_API_KEY` environment variable. Create the key in test mode while you build: the examples on this page use test mode, and a test mode key works only against test mode. See [Authentication](/api-reference/introduction#authentication). * The SDK for your language. The Node.js SDK requires Node.js 20 or later, the Python SDK requires Python 3.9 or later, and the Go SDK requires Go 1.22 or later. The cURL examples need no SDK. ```bash Node.js theme={null} npm install dodopayments ``` ```bash Python theme={null} pip install dodopayments ``` ```bash Go theme={null} go get github.com/dodopayments/dodopayments-go ``` The [webhook example](#webhooks) also uses the `standardwebhooks` package. Install it with `npm install standardwebhooks`. ## Choose an Integration Path | Path | Use it when | Guide | | - | - | - | | Checkout sessions | You want a hosted checkout created from your server. This is the recommended path for most integrations. | [Checkout Sessions](#checkout-sessions) | | Overlay checkout | You want checkout to open as a modal on your web page. | [Overlay Checkout](/developer-resources/overlay-checkout) | | Inline checkout | You want checkout embedded in your page layout, next to your own order summary. | [Inline Checkout](/developer-resources/inline-checkout) | | Static payment links | You want a shareable URL with no code. | [Payment Links](#payment-links) | | Mobile checkout SDKs | You're building a native Android, iOS, React Native, or Flutter app. | [Mobile Integration](/developer-resources/mobile-integration) | Overlay and inline checkout run in a web page only. In a native mobile app, create the checkout session on your server and open its `checkout_url` with a mobile checkout SDK. To have a coding agent build this integration for you, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ## Checkout Sessions Create a secure, hosted checkout experience. You create a session on your server, then redirect the customer to the returned `checkout_url`. > [!WARNING] > > Each `checkout_url` works once and expires after 24 hours, or after 15 minutes when you pass `confirm: true`. With `confirm: true`, you must also provide every required field. Create a new session for each customer and each payment attempt. ### Create a Checkout Session > [tab] Node.js SDK > > ```javascript expandable theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', // defaults to 'live_mode' > }); > > const session = await client.checkoutSessions.create({ > product_cart: [{ product_id: 'pdt_123', quantity: 1 }], > customer: { email: 'customer@example.com', name: 'John Doe' }, > return_url: 'https://yourapp.com/checkout/success', > }); > > console.log(session.checkout_url); > ``` > [tab] Python SDK > > ```python expandable theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), > environment="test_mode", # defaults to "live_mode" > ) > > session = client.checkout_sessions.create( > product_cart=[{"product_id": "pdt_123", "quantity": 1}], > customer={"email": "customer@example.com", "name": "John Doe"}, > return_url="https://yourapp.com/checkout/success", > ) > > print(session.checkout_url) > ``` > [tab] cURL > > ```bash theme={null} > curl -X POST https://test.dodopayments.com/checkouts \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_cart": [{"product_id": "pdt_123", "quantity": 1}], > "customer": {"email": "customer@example.com", "name": "John Doe"}, > "return_url": "https://yourapp.com/checkout/success" > }' > ``` ### Redirect to Checkout After creating a session, redirect the customer to the `checkout_url`: ```javascript theme={null} window.location.href = session.checkout_url; ``` > [!TIP] > > For advanced customization, see the full [Checkout Sessions](/developer-resources/checkout-session) guide and the [API Reference](/api-reference/checkout-sessions/create). ### Handle Errors When a request fails, the API returns an HTTP status code and a JSON body with a `code` and a `message`. Branch your error handling on `code`, not on `message`. For every code, its cause, and how to resolve it, see [Error Codes](/api-reference/error-codes). A failed payment is reported separately: the payment's `status` is `failed`, its `error_code` gives the reason, and you receive a `payment.failed` [webhook](#webhooks). To decide whether to retry, see [Handle Payment Failures](/developer-resources/handle-payment-failures). ## Payment Links A payment link is a URL that opens checkout for a product, so you can collect payments without writing code. Query parameters pre-fill customer details and control the checkout form. When a customer opens the link, checkout stores the parameters in a session and shortens the URL to a `session` parameter, so a page refresh keeps them. ### Static Payment Links A static payment link is a URL you create once and share multiple times. The base URL is: ```text theme={null} https://checkout.dodopayments.com/buy/{product_id} ``` Add query parameters to customize the checkout: **quantity** `integer` (default: 1) Number of items to purchase. **redirect\_url** `string` *required* Payment links use `redirect_url`. The Checkout Sessions API uses `return_url` for the same purpose. URL to redirect to after payment. Dodo Payments appends the payment details as query parameters, for example `https://example.com/?payment_id=pay_ts2ySpzg07phGeBZqePbH&status=succeeded&email=customer%40example.com`. If the product issues license keys, a `license_key` parameter is also appended, with multiple keys separated by commas. **paymentCurrency** `string` Specifies the payment currency. Defaults to the billing country's currency. **showCurrencySelector** `boolean` (default: true) Show or hide the currency selector. **showDiscounts** `boolean` (default: true) Show or hide the discounts section. Set to `false` to prevent customers from entering coupon codes. **paymentAmount** `number` Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > [!WARNING] > > `paymentAmount` uses major currency units (`12.5` is \$12.50). The Checkout Sessions API field `product_cart[].amount` uses the smallest currency unit (`1250` is \$12.50). See [Dynamic Pricing](/developer-resources/dynamic-pricing-checkout). **metadata\_**\* `string` Custom metadata fields, for example `metadata_orderId=123`. **singlePage** `boolean` (default: false) Set to `true` to open the [single-page checkout](/features/single-page-checkout), where the customer enters their details and pays on one page. Only the exact value `true` turns it on; any other value keeps the two-page checkout. Works for product links (`/buy/pdt_...`) and product collection links (`/buy/pdc_...`). The Checkout Sessions API uses [`feature_flags.single_page`](/developer-resources/checkout-session) for the same purpose. ### Pre-fill Customer Information Add customer fields as query parameters to streamline checkout: **fullName** `string` Customer's full name (ignored if firstName or lastName is provided). **firstName** `string` Customer's first name. **lastName** `string` Customer's last name. **email** `string` Customer's email address. **country** `string` Customer's country (ISO 3166-1 alpha-2 code). **addressLine** `string` Street address. **city** `string` City. **state** `string` State or province. **zipCode** `string` Postal or ZIP code. ### Disable Form Fields To prevent customers from changing pre-filled information, disable a field by providing its value and setting the corresponding `disable...` flag to `true`: ```text theme={null} ?email=alice@example.com&disableEmail=true ``` | Field | Disable Flag | Required Parameter | | - | - | - | | Full Name | `disableFullName` | `fullName` | | First Name | `disableFirstName` | `firstName` | | Last Name | `disableLastName` | `lastName` | | Email | `disableEmail` | `email` | | Country | `disableCountry` | `country` | | Address Line | `disableAddressLine` | `addressLine` | | City | `disableCity` | `city` | | State | `disableState` | `state` | | ZIP Code | `disableZipCode` | `zipCode` | ### Example Static Payment Link ```text theme={null} https://checkout.dodopayments.com/buy/pdt_123?quantity=1&email=alice@example.com&disableEmail=true&redirect_url=https://example.com/success ``` > [!TIP] > > Disabling fields prevents accidental changes and ensures data consistency. ### Shareable Links for a Specific Cart To send a customer a link for a specific cart, price, or prefilled customer, create a [checkout session](#create-a-checkout-session) on your server and share its `checkout_url`. Each `checkout_url` works once and expires after 24 hours. To make a link shorter, set `short_link: true`. ## Webhooks Webhooks tell your server when a payment succeeds or fails, so you can fulfill the order. ### Create a Webhook Endpoint Go to **Developer → Webhooks** in the dashboard and add your endpoint URL. Copy the endpoint's signing secret into the `DODO_PAYMENTS_WEBHOOK_KEY` environment variable. Here's an example using Next.js: ```typescript app/api/webhooks/dodo/route.ts expandable theme={null} import { Webhook } from "standardwebhooks"; const webhook = new Webhook(process.env.DODO_PAYMENTS_WEBHOOK_KEY!); export async function POST(request: Request) { const rawBody = await request.text(); const webhookHeaders = { "webhook-id": request.headers.get("webhook-id") ?? "", "webhook-signature": request.headers.get("webhook-signature") ?? "", "webhook-timestamp": request.headers.get("webhook-timestamp") ?? "", }; try { await webhook.verify(rawBody, webhookHeaders); } catch { return new Response("Invalid signature", { status: 400 }); } const payload = JSON.parse(rawBody); switch (payload.type) { case "payment.succeeded": // Fulfill the order break; case "payment.failed": // Notify the customer break; } return new Response(null, { status: 200 }); } ``` Our webhook implementation follows the [Standard Webhooks](https://standardwebhooks.com/) specification. ### Events to Listen For At minimum, listen for these events in a one-time payment flow: | Event | When it fires | What to do | | - | - | - | | `payment.succeeded` | Payment is successfully processed. | Fulfill the order — grant access, provision the product, send the receipt. | | `payment.failed` | Payment attempt fails (declined card, error, etc.). | Notify the customer and prompt a retry. | | `payment.processing` | Payment is accepted but still being processed (async methods). | Wait for `payment.succeeded` or `payment.failed` before fulfilling. | | `payment.cancelled` | Payment is cancelled before completion. | Release any held state and mark the order abandoned. | > [!TIP] > > Always fulfill on `payment.succeeded` from the webhook, not on the browser redirect. The redirect can be missed if the customer closes the tab, whereas the webhook is retried until acknowledged. If you sell products with license keys, also handle `license_key.created`. For the complete list of events, including subscription, entitlement, credit, recovery, and dunning events, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). For a complete Next.js and TypeScript example, see the [demo repository](https://github.com/dodopayments/dodo-checkout-demo) and its [live deployment](https://atlas.dodopayments.com/). ## Currency and Billing Address To charge in a specific currency, pass `billing_currency` and `billing_address.country` when you create the checkout session. If you omit them, [Adaptive Currency](/features/adaptive-currency) picks the currency and country from the customer's IP address, which may not be the currency you intend to charge. Pay What You Want amounts are in the product's base currency, which must be USD, GBP, or EUR. To collect a fixed amount in another currency, use [Adaptive Currency](/features/adaptive-currency), which converts your base price at live exchange rates, or [Localized Pricing](/features/localized-pricing), which sets a fixed price per currency. Localized Pricing doesn't work with Pay What You Want. ## One-Click Repeat Purchase To charge a returning customer with a saved payment method, pass its `payment_method_id` with `confirm: true`. `payment_method_id` is accepted only when `confirm` is `true`, and you must also pass the existing customer's `customer_id`. Because `confirm` is `true`, you must also pass a complete `billing_address`, or only `country` and `zipcode` when `minimal_address` is `true`. The session charges the saved payment method directly, so it returns no `checkout_url`. Use [webhooks](#webhooks) to learn whether the payment succeeded. ```typescript theme={null} const session = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], customer: { customer_id: 'cus_123' }, payment_method_id: 'pm_123', billing_address: { country: 'US', state: 'CA', city: 'San Francisco', street: '123 Main St', zipcode: '94102', }, confirm: true, }); ``` ## Related Pages > [card] [Checkout Sessions](/developer-resources/checkout-session) > > Full guide with advanced customization options. > [card] [Overlay Checkout](/developer-resources/overlay-checkout) > > Embed checkout as a modal overlay on your page. > [card] [Inline Checkout](/developer-resources/inline-checkout) > > Embed checkout directly in your page layout. > [card] [Subscription Integration](/developer-resources/subscription-integration-guide) > > Set up recurring billing. > [card] [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide) > > Complete list of all webhook events. > [card] [API Reference](/api-reference/checkout-sessions/create) > > Checkout Sessions API documentation. # Manual License Key Fulfillment Integration Guide Source: https://docs.dodopayments.com/developer-resources/manual-license-key-fulfillment Sell a product whose license keys you supply yourself: create a manual-mode License Key entitlement, detect pending grants, and deliver each key to the customer. With **manual license key fulfillment**, each purchase creates a `Pending` grant that waits for *you* to supply the key value, instead of Dodo Payments generating a key on payment. The key can come from your own system, a third-party vendor, or a finite pool of codes. When you finish this guide, you have: * A product with a License Key entitlement set to `manual` fulfillment. * A webhook listener that detects when a customer is waiting for a key. * A fulfillment call that delivers the key and notifies the customer automatically. > [card] [License Keys Overview](/features/license-keys) > > The full license key lifecycle and the `fulfillment_mode` setting. > [card] [Fulfill License Key Grant API](/api-reference/entitlements/fulfill-license-key) > > API reference for the endpoint you call to deliver a key. ## How It Works The sequence below shows one purchase, from checkout to key delivery: ```mermaid theme={null} sequenceDiagram participant C as Customer participant D as Dodo Payments participant M as Your Backend C->>D: Purchase (manual-mode License Key product) D->>D: Create grant (status: Pending, no key) D->>M: entitlement_grant.created (integration_type: license_key, status: Pending) M->>M: Obtain key from own system / vendor M->>D: POST /grants/{grant_id}/license-key { key } D->>C: Deliver license key to customer D->>M: entitlement_grant.delivered ``` Manual fulfillment changes only the **issuance** step. Once delivered, the key behaves like an auto-generated key for activation, validation, deactivation, expiry, and revocation. A purchase of several units creates one `Pending` grant per unit, and each grant needs its own key. ## Prerequisites To follow this guide, you need: * A Dodo Payments merchant account. * An API key, created under **Developer → API Keys** and stored in `DODO_PAYMENTS_API_KEY`, and the webhook signing secret from **Developer → Webhooks**, stored in `DODO_PAYMENTS_WEBHOOK_KEY`. See the [API key generation guide](/api-reference/introduction#authentication). * A backend endpoint that can receive webhooks. > [!NOTE] > > Use `https://test.dodopayments.com` and test mode credentials while you build. When you go to production, switch to `https://live.dodopayments.com` and live mode keys. ## Step 1 — Create a License Key Entitlement in Manual Mode An **entitlement** is a reusable definition of what you deliver. Create a License Key entitlement and set its `fulfillment_mode` to `manual`. > [tab] Dashboard > > **1. Open Entitlements** > > Go to **Entitlements** in the dashboard and click **+** to create an entitlement. > > **2. Choose License Key** > > Select **License Keys** and enter a **Name**. The form has these fields: > > * **Fulfillment Mode**: **Automatic** by default. This is the setting that enables manual fulfillment, and you change it in the next step. > * **License Length**: how long each issued key stays valid, or **No expiration**. > * **Activations Limit**: the maximum number of activations per key, or **Unlimited**. > * **Activation Message**: an optional customer-facing message shown when the customer activates the key, and included in the license key email. > > ![New License Key entitlement form with name, fulfillment mode, license length, activations limit, and activation message](https://mintcdn.com/dodopayments/sZYZEc6Biy3IrQNZ/images/entitlements/license-keys/create.png?fit=max\&auto=format\&n=sZYZEc6Biy3IrQNZ\&q=85\&s=65f24596e834387d0c35278ef92d14ea) > > **3. Set Fulfillment Mode to Manual** > > Open the **Fulfillment Mode** dropdown and change it from **Automatic** to **Manual**. The rest of this guide depends on this setting: without it, Dodo Payments generates and emails keys automatically and creates no pending grant. With **Manual** selected, each purchase creates a `Pending` grant for you to fulfill. Click **Create Entitlement** to save. > [tab] API > > Create the entitlement with `integration_config.fulfillment_mode` set to `manual`. > > ```typescript Node.js expandable theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', // defaults to 'live_mode' > }); > > const entitlement = await client.entitlements.create({ > name: 'Pro License (Manual)', > integration_type: 'license_key', > integration_config: { > fulfillment_mode: 'manual', > activations_limit: 5, > duration_count: 1, > duration_interval: 'Year', > }, > }); > > console.log(entitlement.id); // ent_... > ``` > > ```python Python expandable theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), > environment="test_mode", # defaults to "live_mode" > ) > > entitlement = client.entitlements.create( > name="Pro License (Manual)", > integration_type="license_key", > integration_config={ > "fulfillment_mode": "manual", > "activations_limit": 5, > "duration_count": 1, > "duration_interval": "Year", > }, > ) > > print(entitlement.id) > ``` > > ```bash cURL expandable theme={null} > curl -X POST https://test.dodopayments.com/entitlements \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "name": "Pro License (Manual)", > "integration_type": "license_key", > "integration_config": { > "fulfillment_mode": "manual", > "activations_limit": 5, > "duration_count": 1, > "duration_interval": "Year" > } > }' > ``` > [!NOTE] > > `fulfillment_mode` defaults to `auto`. If you omit it, or leave an existing entitlement unchanged, the entitlement keeps automatic fulfillment. Only entitlements explicitly set to `manual` create pending grants. ## Step 2 — Attach the Entitlement to a Product Open the product you want to sell, go to its **Entitlements** section, and select the **License Key entitlement you set to Manual** in Step 1. One product can deliver this license key together with other entitlements on the same purchase. If you don't have a product yet, create a one-time or subscription product first. To sell it through checkout, see the [Integration Guide](/developer-resources/integration-guide). ![Product entitlements panel with License Key selected](https://mintcdn.com/dodopayments/do-W-dMDGVB_xzr_/images/entitlements/attach-to-product.png?fit=max\&auto=format\&n=do-W-dMDGVB_xzr_\&q=85\&s=965ad78262791fa8dbb712b4fdf89538) Selecting the License Key entitlement in the product entitlements panel. > [!NOTE] > > Fulfillment mode is a property of the **entitlement**, not the product. Because you set it to **Manual** in Step 1, every product with this entitlement attached creates `Pending` license-key grants on purchase. You don't configure anything else on the product. ## Step 3 — Detect Pending Grants When a customer buys the product, Dodo Payments creates a grant in `Pending` status with **no key attached** and sends an `entitlement_grant.created` webhook. This event is your signal that a customer is waiting for a key. ### Listen for the Webhook Add a webhook endpoint under **Developer → Webhooks** in the dashboard, then act on pending license-key grants. The webhooks follow the [Standard Webhooks](https://standardwebhooks.com/) specification, so you can verify them with the `standardwebhooks` library: ```typescript expandable theme={null} import { Webhook } from 'standardwebhooks'; const webhook = new Webhook(process.env.DODO_PAYMENTS_WEBHOOK_KEY!); export async function POST(request: Request) { const rawBody = await request.text(); const headers = { 'webhook-id': request.headers.get('webhook-id') || '', 'webhook-signature': request.headers.get('webhook-signature') || '', 'webhook-timestamp': request.headers.get('webhook-timestamp') || '', }; await webhook.verify(rawBody, headers); const event = JSON.parse(rawBody); // A customer bought a manual-mode license key and is waiting for it. if ( event.type === 'entitlement_grant.created' && event.data.integration_type === 'license_key' && event.data.status === 'Pending' ) { // queueLicenseKeyFulfillment is your own job queue, not part of the SDK. await queueLicenseKeyFulfillment({ grantId: event.data.id, customerId: event.data.customer_id, }); } return new Response('ok'); } ``` The grant payload carries `integration_type: "license_key"`, so you can recognize a license-key grant without an extra lookup. Webhook deliveries can repeat, so skip events whose `webhook-id` header you've already processed. See the [Entitlement Grant webhook reference](/developer-resources/webhooks/intents/entitlement-grant) for the full payload. ### Or Poll the List Grants API If you'd rather not rely on webhooks, list the grants for your License Key entitlement and filter by `status`. Every grant on a License Key entitlement is a license-key grant, so you don't need an `integration_type` filter: ```typescript Node.js theme={null} // Uses the client from Step 1. const pending = await client.entitlements.grants.list('ent_license_key_id', { status: 'Pending', }); for (const grant of pending.items) { console.log(`Grant ${grant.id} for customer ${grant.customer_id} needs a key`); } ``` ```bash cURL theme={null} curl -G https://test.dodopayments.com/entitlements/ent_license_key_id/grants \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ --data-urlencode "status=Pending" ``` ## Step 4 — Deliver the Key Get the key value from your own system, then submit it to the [Fulfill License Key Grant](/api-reference/entitlements/fulfill-license-key) endpoint. The call requires your secret API key with **Write** access to **Entitlements**. It is **not** one of the public license endpoints. The SDKs also expose it, for example as `client.entitlements.grants.fulfillLicenseKey()` in TypeScript and `client.entitlements.grants.fulfill_license_key()` in Python. ```typescript Node.js expandable theme={null} async function fulfill(grantId: string, key: string) { const res = await fetch( `https://test.dodopayments.com/grants/${grantId}/license-key`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${process.env.DODO_PAYMENTS_API_KEY}`, }, body: JSON.stringify({ key, // Optional — fall back to the entitlement config when omitted activations_limit: 5, expires_at: '2027-05-01T00:00:00Z', }), }, ); if (!res.ok) { // See the status code table below for handling throw new Error(`Fulfillment failed: ${res.status}`); } return res.json(); // updated grant, now status: "Delivered" } ``` ```bash cURL expandable theme={null} curl -X POST https://test.dodopayments.com/grants/entg_8VbC6JDZ/license-key \ -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "key": "PRO-AAAA-BBBB-CCCC-DDDD", "activations_limit": 5, "expires_at": "2027-05-01T00:00:00Z" }' ``` ### Request Fields **key** `string` *required* The license key string to deliver to the customer, up to 255 characters. Surrounding whitespace is trimmed, and an empty or whitespace-only value is rejected. **activations\_limit** `integer` Per-key activation limit, at least 1. When omitted, the entitlement's **Activations Limit** applies. **expires\_at** `string` Per-key expiry (ISO 8601). When omitted, a one-time grant's key expires according to the entitlement's **License Length**, and a subscription grant's key has no expiry, so its validity follows the subscription. On success, the grant moves to `Delivered`, Dodo Payments emails the key to the customer (the same email they receive under automatic fulfillment), and the `license_key.created` and `entitlement_grant.delivered` webhook events fire. The email contains the license key, the product, the activation limit, the expiry, and your activation instructions: ![Customer license key email showing the key, product, activation limit, expiry, and activation instructions](https://mintcdn.com/dodopayments/sZYZEc6Biy3IrQNZ/images/entitlements/license-keys/customer-email.png?fit=max\&auto=format\&n=sZYZEc6Biy3IrQNZ\&q=85\&s=981f1f80ec973ae2af3592167787bc68) The license key email the customer receives once you fulfill the grant. > [!TIP] > > You don't need to email the key yourself. Delivery happens automatically when the grant is fulfilled. ## Step 5 — Handle Errors and Retries The endpoint validates the grant before it delivers anything. Handle these responses: | Status | Meaning | What to do | | - | - | - | | `200` | Key delivered. The grant is now `Delivered`. | Done. | | `400` | Not a license-key grant, or the key is empty or only whitespace. | Fix the request. Don't retry it unchanged. | | `404` | No grant with that ID exists for your business. | Check the `grant_id`. | | `409` | The grant isn't awaiting fulfillment (it's already delivered, revoked, or already has a key), **or** the key value already exists. | If the grant is already delivered, treat the call as successful. If the key is a duplicate, supply a different key. | | `422` | The request body failed validation, for example `activations_limit` below 1 or a key longer than 255 characters. | Correct the field and retry. | > [!WARNING] > > Fulfillment is safe to retry on transient errors such as timeouts and `5xx` responses. Each grant can be fulfilled only once, so a retry after a successful but unacknowledged call returns `409` instead of issuing a second key or sending a duplicate email. Use the grant `id` as your idempotency key. ## Verify the Flow To test the flow end to end: 1. Buy the product in test mode. See the [checkout guides](/developer-resources/integration-guide). 2. Confirm that your webhook received `entitlement_grant.created` with `status: "Pending"` and `integration_type: "license_key"`, or that the grant appears in the List Grants response filtered by `status=Pending`. 3. Call the fulfill endpoint with a test key. 4. Confirm that the response shows `status: "Delivered"` with a populated `license_key`, that the customer receives the key email, and that `entitlement_grant.delivered` fires. > [!TIP] > > Once the key is delivered, the customer can [activate and validate](/features/license-keys#activation-validation-deactivation) it against the public license endpoints, like an auto-generated key. ## Related API Reference > [card] [Create Entitlement](/api-reference/entitlements/create-entitlement) > > Create the License Key entitlement with `fulfillment_mode: manual`. > [card] [List Grants](/api-reference/entitlements/list-grants) > > Filter by `status` and `customer_id` to find pending grants. > [card] [Fulfill License Key Grant](/api-reference/entitlements/fulfill-license-key) > > Deliver the key value and move the grant to `Delivered`. > [card] [Entitlement Grant Webhooks](/developer-resources/webhooks/intents/entitlement-grant) > > The `entitlement_grant.*` events that signal pending and delivered grants. # Dodo Payments MCP Server Source: https://docs.dodopayments.com/developer-resources/mcp-server Connect AI agents to Dodo Payments with one MCP server. Search the docs and SDK, and run TypeScript SDK code against your account in a sandbox. Use the Dodo Payments remote Model Context Protocol (MCP) server to give AI agents access to the Dodo Payments docs and your account. Agents can look up how a feature works, then create payments, manage subscriptions, issue refunds and more. The server lives at `https://mcp.dodopayments.com/mcp`. We recommend naming it `dodopayments` in your client. > [!NOTE] > > The MCP server uses OAuth. When you add the server, your client opens your browser so you can sign in and approve access. You never copy an API key into your agent. ## Connect Your Agent The [Dodo Agent Plugin](/developer-resources/build-with-ai-coding-agents) (0.7.0 and later) adds this server and the `dodo-payments` skill for you. To connect a client yourself, pick it below. > [tab] Claude Code > > Run: > > ```bash theme={null} > claude mcp add --transport http dodopayments https://mcp.dodopayments.com/mcp > ``` > > To sign in, run `/mcp` inside Claude Code and pick `dodopayments`. > [tab] Cursor > > Add the following to `.cursor/mcp.json` in your project, or to `~/.cursor/mcp.json` to make Dodo Payments available in every project: > > ```json theme={null} > { > "mcpServers": { > "dodopayments": { > "url": "https://mcp.dodopayments.com/mcp" > } > } > } > ``` > > Open Cursor's MCP settings and connect to `dodopayments` to sign in. > [tab] VS Code > > Add the following to `.vscode/mcp.json` in your workspace, or run **MCP: Add Server** from the command palette: > > ```json theme={null} > { > "servers": { > "dodopayments": { > "type": "http", > "url": "https://mcp.dodopayments.com/mcp" > } > } > } > ``` > > Start the server from the MCP UI in VS Code to sign in. > [tab] Codex > > Run: > > ```bash theme={null} > codex mcp add dodopayments --url https://mcp.dodopayments.com/mcp > ``` > > To sign in, run: > > ```bash theme={null} > codex mcp login dodopayments > ``` > [tab] OpenCode > > Add the server to `opencode.json`: > > ```json theme={null} > { > "$schema": "https://opencode.ai/config.json", > "mcp": { > "dodopayments": { > "type": "remote", > "url": "https://mcp.dodopayments.com/mcp", > "enabled": true > } > } > } > ``` > > To sign in, run: > > ```bash theme={null} > opencode mcp auth dodopayments > ``` > [tab] Gemini CLI > > Run: > > ```bash theme={null} > gemini mcp add --transport http dodopayments https://mcp.dodopayments.com/mcp > ``` > > To sign in, run `/mcp auth dodopayments` inside Gemini CLI. > [tab] Claude Desktop and claude.ai > > Open **Settings**, then **Connectors**, select **Add custom connector**, and enter: > > * **Name:** `dodopayments` > * **MCP server URL:** `https://mcp.dodopayments.com/mcp` > > Save the connector, select **Connect**, and sign in in the browser. > [tab] Windsurf and other clients > > If your client accepts a remote MCP URL, add `https://mcp.dodopayments.com/mcp`. > > If it only supports local commands, use the `mcp-remote` bridge. This needs Node.js 18 or later: > > ```json theme={null} > { > "mcpServers": { > "dodopayments": { > "command": "npx", > "args": ["-y", "mcp-remote@latest", "https://mcp.dodopayments.com/mcp"] > } > } > } > ``` > > See [modelcontextprotocol.io/clients](https://modelcontextprotocol.io/clients) for other clients. ### Approve the Connection The first sign-in opens the Dodo Payments consent page in your browser. Your [team role](/features/team) caps what you can grant, so a connection can never do more than you can. 1. **Choose the business** the AI client can use. ![Consent page, step 1 of 4: choose the business that the app can access](https://mintcdn.com/dodopayments/u6pal2lLxg9AIE0G/images/mcp/oauth-consent-business.png?fit=max\&auto=format\&n=u6pal2lLxg9AIE0G\&q=85\&s=59dce2f2dcba7701381be5d7f9cf18d0) 2. **Choose the mode**: test mode or live mode. ![Consent page, step 2: Choose a Mode, with one choice of Live Mode or Test Mode](https://mintcdn.com/dodopayments/KtfSqp9QC-l5YuUH/images/mcp/oauth-consent-mode.png?fit=max\&auto=format\&n=KtfSqp9QC-l5YuUH\&q=85\&s=fe3edbe02860a1c4583884a1f191061a) 3. **Set the permissions**: **Read**, **Write**, or **Customise** to pick a level for each resource. ![Consent page, step 3 of 4: Set Permissions, with Read, Write, and Customise options and resource groups such as Payments and Catalog](https://mintcdn.com/dodopayments/u6pal2lLxg9AIE0G/images/mcp/oauth-consent-permissions.png?fit=max\&auto=format\&n=u6pal2lLxg9AIE0G\&q=85\&s=16749540508bec2e6c86ee43996ed3f8) 4. **Review and authorize** the connection. > [!TIP] > > Start with test mode and **Read** access. Approve live mode or **Write** access only when you need them. Each connection holds one mode. To work in the other mode, add a second connection and approve the other mode. ### How the Sign-In Is Secured * Access tokens expire after 1 hour. Refresh tokens rotate on each use. * Your client never holds an API key. For each call, the MCP server exchanges your token for an API token that lasts 5 minutes and carries only the permissions you approved. * You can revoke a connection at any time in **Settings → Connected Apps**. Revoke stops new tokens at once, and tokens already issued stop working within about a minute. See [Connected Apps](/features/connected-apps). ## How the Tools Work Dodo Payments has many API operations. Instead of sending every operation and its input schema to your agent at the start of every conversation, the server gives it a few tools. The agent finds what it needs, then writes a short TypeScript snippet to call it. This is code mode. | Tool | What it does | | - | - | | `search_docs` | Searches the Dodo Payments guides. | | `read_docs_page` | Reads a documentation page as Markdown. | | `search` | Searches SDK and API methods, with their parameters. | | `execute` | Runs TypeScript SDK code against your account in a sandbox. | | `feedback` | Sends your agent's feedback about Dodo Payments, these tools or the docs. | The server asks your client to sign in before it lists the tools, so your client starts the OAuth sign-in when you add the server. **1. Search** The agent calls `search_docs` to find the right guide and `read_docs_page` to read it. It calls `search` to find the SDK methods for its task, such as "list a customer's active subscriptions", and their exact parameters. **2. Execute** The agent calls `execute` with code that defines `async function run(client) { ... }`, where `client` is an authenticated Dodo Payments SDK client. It can chain calls, page through results and return only the fields it needs. ```typescript theme={null} async function run(client) { const page = await client.payments.list({ page_size: 10 }); return page.items.map((p) => ({ id: p.payment_id, status: p.status })); } ``` Code runs in an isolated sandbox. It can only call the Dodo Payments SDK, with the access you approved on the consent page. > [!TIP] > > Agents can chain several API calls, handle conditional logic and do calculations in one script, without a round trip to the model for each step. ## What `execute` Can Do `execute` gives your agent the Dodo Payments TypeScript SDK, limited to the permissions you approved. The SDK covers these resources: | Area | Resources | | - | - | | Payments and checkout | Payments, checkout sessions, refunds, disputes | | Subscriptions | Subscriptions, add-ons | | Customers | Customers, entitlements | | Catalog and pricing | Products, product collections, discounts, brands | | Usage and credits | Meters, usage events, credit entitlements, balance ledger | | Software licensing | Licenses | | Operations | Webhooks, payouts, blocklist, moderation | Use the `search` tool to see the exact methods and parameters available for each resource. See the [API Reference](/api-reference/introduction) for the full list of endpoints. ## Telemetry and Feedback The `feedback` tool lets your agent tell us what worked and what didn't, about Dodo Payments, the MCP tools or these docs. It needs sign-in. Before the text is stored, the server removes emails, IDs and keys from it. The Dodo Payments team reads and triages each message, with your business ID so we can follow up. The tool returns a reference ID. Ask your agent to write feedback without customer names, emails or IDs. Removal matches the shape of an identifier, not its meaning, so a name written in plain words can still pass. ## Docs-Only Access If your client can't sign in with OAuth, or you only want docs search, connect to `https://mcp.dodopayments.com/mcp?auth=optional`. Then `search_docs`, `read_docs_page` and `search` work without an account, and `execute` and `feedback` ask you to sign in. `https://knowledge.dodopayments.com/mcp` is another docs-only address that needs no account. ## Advanced: Local Server with an API Key Run the MCP server yourself when you need a stdio server, an air-gapped setup, or a fixed API key. This setup uses an API key from **Developer → API Keys** and does not use the OAuth sign-in. Install the server with NPM or Docker. ### NPM Package Install and run the MCP server locally. > [!WARNING] > > The local server runs your code in a [Deno](https://deno.land) sandbox. Install Deno 2.8 or earlier and make sure `deno` is on your `PATH`; the sandbox fails to start on Deno 2.9 and later. Local code execution works on macOS and Linux only. On Windows, use the remote server or run the local server under WSL2. > [tab] NPX (No Installation) > > ```bash theme={null} > # Set your environment variables > export DODO_PAYMENTS_API_KEY="dodo_test_..." > export DODO_PAYMENTS_WEBHOOK_KEY="your_webhook_key" > export DODO_PAYMENTS_ENVIRONMENT="test_mode" > > # Run the latest version > npx -y dodopayments-mcp@latest > ``` > [tab] MCP Client Configuration > > ```json theme={null} > { > "mcpServers": { > "dodopayments": { > "command": "npx", > "args": ["-y", "dodopayments-mcp@latest"], > "env": { > "DODO_PAYMENTS_API_KEY": "dodo_test_...", > "DODO_PAYMENTS_WEBHOOK_KEY": "your_webhook_key", > "DODO_PAYMENTS_ENVIRONMENT": "test_mode" > } > } > } > } > ``` > [!TIP] > > Use `@latest` to always pull the most recent version, or pin to a specific version like `@2.51.0` for stability. ### Docker Run the MCP server in a container. ```bash theme={null} # Pull the latest image docker pull ghcr.io/dodopayments/mcp:latest # Run the container (-i keeps stdin open for the stdio transport) docker run -i -e DODO_PAYMENTS_API_KEY="dodo_test_..." \ -e DODO_PAYMENTS_WEBHOOK_KEY="your_webhook_key" \ -e DODO_PAYMENTS_ENVIRONMENT="test_mode" \ ghcr.io/dodopayments/mcp:latest ``` > [!NOTE] > > Docker images are available on [GitHub Container Registry](https://github.com/orgs/dodopayments/packages/container/package/mcp). > [!WARNING] > > Never commit API keys to version control. Keep them in environment variables or a secret manager, use test mode keys during development, and rotate keys from the dashboard. If you run the server remotely, always require the `Authorization` or `x-dodo-payments-api-key` header and serve it over HTTPS. ## Environment Variables Configure the MCP server behavior using environment variables. | Variable | Description | Required | | - | - | - | | `DODO_PAYMENTS_API_KEY` | Your Dodo Payments API key | Yes | | `DODO_PAYMENTS_WEBHOOK_KEY` | Your webhook signing key | No | | `DODO_PAYMENTS_ENVIRONMENT` | `live_mode` or `test_mode`; defaults to `live_mode` | No | ## Running Remotely Deploy the MCP server as a remote HTTP server for web-based clients or agentic workflows. ```bash theme={null} # Start as remote server npx -y dodopayments-mcp --transport=http # Specify a custom port npx -y dodopayments-mcp --transport=http --port=3000 ``` ### Remote Server Configuration Once deployed, clients can connect using the server URL: ```json theme={null} { "mcpServers": { "dodopayments": { "url": "http://localhost:3000", "headers": { "Authorization": "Bearer dodo_test_..." } } } } ``` ### Authorization Headers The remote server accepts authentication via the following headers: | Header | Purpose | | - | - | | `Authorization` | Bearer token authentication | | `x-dodo-payments-api-key` | Direct API key header | ## Resources > [card] [API Reference](/api-reference/introduction) > > Explore the complete Dodo Payments API documentation > [card] [MCP Protocol](https://modelcontextprotocol.io) > > Learn more about the Model Context Protocol standard > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-typescript/tree/main/packages/mcp-server) > > View the MCP server source code and contribute > [card] [NPM Package](https://www.npmjs.com/package/dodopayments-mcp) > > Install the MCP server from NPM # Mobile Integration Guide Source: https://docs.dodopayments.com/developer-resources/mobile-integration Open Dodo Payments hosted checkout from Android, iOS, React Native, and Flutter apps, customize it for mobile, and run subscription flows. > [card] [Quick Start](#integration-workflow) > > The four steps from your backend to the checkout and back. > [card] [Platform Examples](#choose-your-sdk) > > Code for Android, iOS, React Native, and Flutter. > [card] [Checkout Customization](#checkout-page-customization) > > The 14 checkout session parameters that matter most on mobile. > [card] [Mobile Recipes](#mobile-optimized-recipes) > > Complete request bodies for 5 common mobile scenarios. Your mobile app opens Dodo Payments hosted checkout in the platform's system browser surface and gets the customer back into the app when checkout ends. Your backend creates the checkout session and grants access from webhooks. > [!NOTE] > > Dodo Payments ships an official checkout SDK for **Android, iOS, React Native, and Flutter**. Each SDK opens the checkout URL, captures the return, and parses the result behind one typed `start(...)` call, and each one includes abandoned-session recovery. Build the flow by hand only if none of the SDKs fits your stack. ## Prerequisites Before you start, you need: * A Dodo Payments account. * An API key from **Developer → API Keys** and a webhook signing secret from **Developer → Webhooks**. * An Android, iOS, React Native, or Flutter app. * A backend server that creates checkout sessions. The API key stays on this server. ## Integration Workflow Your backend makes every Dodo Payments API call. Your app only asks your backend for a checkout URL, opens it, and shows the result. ```mermaid theme={null} sequenceDiagram participant App as Mobile App participant Backend as Your Backend participant Dodo as Dodo Payments participant Browser as System Browser App->>Backend: Request checkout (user session token) Backend->>Dodo: Create checkout session (API key) Dodo-->>Backend: checkout_url Backend-->>App: checkout_url App->>Browser: Open checkout_url (Custom Tab / SFSafariViewController) Browser->>Dodo: Customer pays Dodo-->>Browser: Redirect to return_url Browser-->>App: Deep link with status + payment_id (UI hint only) Dodo->>Backend: payment.succeeded / subscription.active webhook Backend->>Backend: Grant access (source of truth) ``` > [!NOTE] > > The `status` in the deep link tells your app what to show the customer. It is not proof of payment. Grant access from the `payment.succeeded` or `subscription.active` **webhook** on your backend, not from the mobile result. **1. Backend: Create Checkout Session** Your backend creates a checkout session with your API key and returns its `checkout_url` to the app. Set the session's `return_url` to the deep link your app registers, for example `myapp://checkout/return`. > [card] [Checkout Session API Docs](/developer-resources/checkout-session) > > Create a checkout session from Node.js, Python, and other languages, with the full parameter reference. > [!NOTE] > > **Security**: Create checkout sessions on your backend server, never in the mobile app. Anyone can extract an API key from an app binary. **2. Mobile: Get Checkout URL** Your app calls your backend to get the checkout URL. Authenticate this request with the signed-in user's own session token. In each example, `userSessionToken` is that token and `CheckoutResponse` is your own response type. > [tab] iOS (Swift) > > ```swift theme={null} > func getCheckoutURL(productId: String, customerEmail: String, customerName: String) async throws -> String { > let url = URL(string: "https://your-backend.com/api/create-checkout-session")! > var request = URLRequest(url: url) > request.httpMethod = "POST" > request.setValue("application/json", forHTTPHeaderField: "Content-Type") > request.setValue("Bearer \(userSessionToken)", forHTTPHeaderField: "Authorization") > > let requestData: [String: Any] = [ > "productId": productId, > "customerEmail": customerEmail, > "customerName": customerName > ] > request.httpBody = try JSONSerialization.data(withJSONObject: requestData) > > let (data, _) = try await URLSession.shared.data(for: request) > let response = try JSONDecoder().decode(CheckoutResponse.self, from: data) > return response.checkout_url > } > ``` > [tab] Android (Kotlin) > > ```kotlin theme={null} > suspend fun getCheckoutURL(productId: String, customerEmail: String, customerName: String): String { > val client = OkHttpClient() > val requestBody = JSONObject().apply { > put("productId", productId) > put("customerEmail", customerEmail) > put("customerName", customerName) > }.toString().toRequestBody("application/json".toMediaType()) > > val request = Request.Builder() > .url("https://your-backend.com/api/create-checkout-session") > .header("Authorization", "Bearer $userSessionToken") > .post(requestBody) > .build() > > val response = client.newCall(request).execute() > val responseBody = response.body?.string() > val jsonResponse = JSONObject(responseBody ?: "") > return jsonResponse.getString("checkout_url") > } > ``` > [tab] React Native (JavaScript) > > ```javascript theme={null} > const getCheckoutURL = async (productId, customerEmail, customerName) => { > try { > const response = await fetch('https://your-backend.com/api/create-checkout-session', { > method: 'POST', > headers: { > 'Content-Type': 'application/json', > 'Authorization': `Bearer ${userSessionToken}`, > }, > body: JSON.stringify({ > productId, > customerEmail, > customerName > }) > }); > > const data = await response.json(); > return data.checkout_url; > } catch (error) { > console.error('Failed to get checkout URL:', error); > throw error; > } > }; > ``` > [tab] Flutter (Dart) > > ```dart theme={null} > import 'dart:convert'; > import 'package:http/http.dart' as http; > > Future getCheckoutUrl({ > required String productId, > required String customerEmail, > required String customerName, > }) async { > final response = await http.post( > Uri.parse('https://your-backend.com/api/create-checkout-session'), > headers: { > 'Content-Type': 'application/json', > 'Authorization': 'Bearer $userSessionToken', > }, > body: jsonEncode({ > 'productId': productId, > 'customerEmail': customerEmail, > 'customerName': customerName, > }), > ); > > if (response.statusCode != 200) { > throw Exception('Failed to get checkout URL: ${response.statusCode}'); > } > return jsonDecode(response.body)['checkout_url'] as String; > } > ``` > [!NOTE] > > **Security**: The app talks only to your backend, never directly to the Dodo Payments API. **3. Mobile: Open Checkout in Browser** Open the checkout URL in the platform's system browser surface. The official checkout SDK for your platform does this for you and returns a typed result. > [card] [Pick your mobile SDK](#choose-your-sdk) > > Install steps and setup instructions for Android, iOS, React Native, and Flutter. **4. Backend: Handle Payment Completion** Grant access when your backend receives the `payment.succeeded` or `subscription.active` webhook. Use the result from the return URL only to update the app's screen. ## Choose Your SDK Every mobile SDK has the same contract. One `start(...)` call opens Dodo Payments hosted checkout in the platform's system browser surface and returns a typed `CheckoutResult` whose `status` is `succeeded`, `failed`, `cancelled`, `pending`, or `expired`. No SDK holds an API key or calls the Dodo Payments API, and all four support abandoned-session recovery. > [card] [Android](/developer-resources/sdks/android) > > `com.dodopayments.api:checkout-android` opens a Custom Tab. Requires `minSdk` 23. > [card] [iOS](/developer-resources/sdks/ios) > > `dodopayments-mobile-sdk-ios` opens `SFSafariViewController`. Requires iOS 16+. > [card] [React Native](/developer-resources/sdks/react-native) > > `@dodopayments/react-native-checkout`, a Turbo Module over both native cores. Requires React Native 0.77+ with the New Architecture. > [card] [Flutter](/developer-resources/sdks/flutter) > > `dodopayments_checkout`, a Pigeon channel over both native cores. Requires Flutter 3.44+. > [!WARNING] > > The returned `status` is a UI hint, not proof of payment. Confirm every payment on your backend from the `payment.succeeded` or `subscription.active` webhook, or by retrieving the payment with your API key. A `cancelled` status means the customer closed the browser before the return URL arrived, so the payment may still have succeeded. Don't show it as a failure. ### Registering a Callback URL Scheme All four SDKs return control to your app through a custom URL scheme that you choose, for example `myapp://checkout/return`. Register it once per platform: > [tab] Android > > ```kotlin android/app/build.gradle theme={null} > android { > defaultConfig { > manifestPlaceholders["dodoCallbackScheme"] = "myapp" > } > } > ``` > > The SDK's own manifest already declares the redirect activity, so you add no manifest XML. The scheme must match the scheme of `returnUrl`. > [tab] iOS > > ```xml Info.plist theme={null} > CFBundleURLTypes > > > CFBundleURLName > myapp > CFBundleURLSchemes > > myapp > > > > ``` > > On iOS, also forward incoming URLs into the SDK, because `SFSafariViewController` can't catch its own return URL. For the exact handler, see the [iOS](/developer-resources/sdks/ios) or [React Native](/developer-resources/sdks/react-native) page. > [tab] Expo > > `@dodopayments/react-native-checkout` includes a config plugin that registers the scheme for both platforms during `prebuild`. Pass it a `scheme` option: > > ```json app.json theme={null} > { > "expo": { > "scheme": "myapp", > "plugins": [ > [ > "@dodopayments/react-native-checkout", > { "scheme": "myappcheckout" } > ] > ] > } > } > ``` > > `scheme` must match the scheme of `returnUrl` and must differ from `expo.scheme`, which Expo already registers on `MainActivity`. For details, see the [React Native SDK](/developer-resources/sdks/react-native) page. > > The plugin edits the `defaultConfig { }` block of `android/app/build.gradle`. If your file has no standard `defaultConfig { }` block, set the placeholder by hand as shown in the Android tab. > > The plugin works with development builds only, not Expo Go. Run `npx expo prebuild --clean` after you edit `app.json`. > [!NOTE] > > To build the flow yourself, open the `checkout_url` in the platform's system browser surface (a Custom Tab on Android, `SFSafariViewController` on iOS), intercept the navigation to your `return_url`, and read the `status` and `payment_id` query parameters. The SDKs do this for you. > [!WARNING] > > **Don't open checkout inside an embedded WebView (`WKWebView` or Android `WebView`).** An embedded WebView can break 3-D Secure challenges and saved-card autofill, so customers see more failed payments. Use the SDK, or open the `checkout_url` in the system browser surface. On iOS, open it in `SFSafariViewController` or `ASWebAuthenticationSession`, or in the system browser, so that Apple Pay is available. On Android, open it in a Custom Tab, which runs in the customer's browser, so Google Pay keeps working. ## Appearance Customization Every SDK accepts an optional `customization` parameter on `start(...)` or `CheckoutParams`. It controls the system browser surface: the toolbar, the buttons, and how the browser is presented. The checkout page's own theme is separate. You set it on your server with [`customization.theme_config`](/developer-resources/checkout-session) when you create the checkout session. The options are grouped by platform, because a Custom Tab on Android and `SFSafariViewController` on iOS expose different native controls. Every field is optional. An unset field leaves the platform's own default in place. > [accordion] Android - Custom Tab > > **toolbarColor** `Color` > > Toolbar background color. > > **navigationBarColor** `Color` > > Navigation bar color. > > **navigationBarDividerColor** `Color` > > Divider color above the navigation bar. > > **closeButtonStyle** `'default' | 'back'` > > `default` shows the system "X" icon; `back` draws a back arrow instead. > > **closeButtonPosition** `'start' | 'end'` > > Which side of the toolbar the close button appears on. > > **shareButtonEnabled** `boolean` > > Shows the toolbar's share icon. > > **showTitleEnabled** `boolean` > > Shows the page title under the URL in the toolbar. > > **urlBarHidingEnabled** `boolean` > > Lets the toolbar auto-hide as the page scrolls. > > **bookmarksButtonEnabled** `boolean` > > Shows "Bookmark this page" in the overflow menu. > > **downloadsButtonEnabled** `boolean` > > Shows "Download page" in the overflow menu. > > **colorScheme** `'system' | 'light' | 'dark'` > > Forces light or dark appearance regardless of the device's system setting. > [accordion] iOS - SFSafariViewController > > **dismissButtonStyle** `'done' | 'close' | 'cancel'` > > Label or icon for the dismiss button. > > **presentationStyle** `'pageSheet' | 'fullScreen'` (default: pageSheet) > > `pageSheet` presents checkout as a card that the customer can swipe to dismiss. `fullScreen` covers the whole screen. > > **barCollapsingEnabled** `boolean` > > Lets the toolbar collapse on scroll. It has a visible effect only when `presentationStyle` is `fullScreen`. With `pageSheet`, the bars stay pinned. > > **colorScheme** `'system' | 'light' | 'dark'` > > Forces light or dark appearance regardless of the device's system setting. The examples below set a toolbar color and close button on Android, and a full-screen dark presentation on iOS. React Native and Flutter take separate `android` and `ios` option groups. The native SDKs take only their own platform's options. > [tab] React Native > > ```typescript theme={null} > const result = await DodoCheckout.start({ > checkoutUrl, > returnUrl: 'myapp://checkout/return', > customization: { > android: { toolbarColor: '#6366F1', closeButtonStyle: 'back' }, > ios: { presentationStyle: 'fullScreen', colorScheme: 'dark' }, > }, > }); > ``` > [tab] Flutter > > ```dart theme={null} > final result = await DodoCheckout.instance.start( > CheckoutParams( > checkoutUrl: Uri.parse(checkoutUrl), > returnUrl: Uri.parse('myapp://checkout/return'), > customization: BrowserCustomization( > android: AndroidBrowserOptions( > toolbarColor: Color(0xFF6366F1), > closeButtonStyle: CloseButtonStyle.back, > ), > ios: IosBrowserOptions( > presentationStyle: PresentationStyle.fullScreen, > colorScheme: BrowserColorScheme.dark, > ), > ), > ), > ); > ``` > [tab] Android (Kotlin) > > ```kotlin theme={null} > val result = DodoCheckout.start( > activity, > CheckoutParams( > checkoutUrl = checkoutUrl, > returnUrl = "myapp://checkout/return", > customization = BrowserCustomization( > toolbarColor = Color.parseColor("#6366F1"), > closeButtonStyle = BrowserCustomization.CloseButtonStyle.BACK, > ) > ) > ) { event -> } > ``` > [tab] iOS (Swift) > > ```swift theme={null} > let result = try await DodoCheckout.start( > checkoutUrl: checkoutUrl, > returnUrl: URL(string: "myapp://checkout/return")!, > customization: BrowserCustomization( > presentationStyle: .fullScreen, > colorScheme: .dark > ) > ) > ``` ## Checkout Page Customization The checkout page itself (which fields appear, the theme, and which payment methods show) is set on your server when you create the checkout session. [Appearance Customization](#appearance-customization) covers only the browser surface around it. The parameters below have the most effect on mobile conversion. These parameters sit in three places on the checkout session request: at the top level, in `customization`, or in `feature_flags`. The **Where it goes** column names the object for each one. Place each parameter in the object shown, because a parameter in the wrong object has no effect. | Parameter | Where it goes | Mobile benefit | Default | Set when… | | - | - | - | - | - | | `show_order_details` | `customization` | `false` collapses the order summary, so payment methods appear at the top of the screen | `true` | Set `false` on mobile, so payment methods appear above the fold | | `minimal_address` | top-level | Collects only a postcode, or a region in countries that require one, instead of the full street, city, and state fields | `false` (`true` when `feature_flags.single_page` is `true`) | On most mobile checkouts, because each extra field adds work for the customer | | `theme` | `customization` | Sets the checkout page to `light`, `dark`, or `system` | Business theme | Use `"system"` to follow the device setting | | `theme_config` | `customization` | Sets your brand palette, fonts, border radius, and pay button label | None | When checkout must look like part of your app | | `force_language` | `customization` | Overrides browser language detection, for example `en` or `es` | Auto-detect | Set it from your app's language instead of the browser's | | `show_on_demand_tag` | `customization` | Shows or hides the on-demand label on the checkout page | `true` | Set `false` when you use on-demand billing only to save a card | | `show_saved_payment_methods` | top-level | Shows a returning customer's saved payment methods | `false` | For signed-in customers who have paid before | | `allow_discount_code` | `feature_flags` | Shows the discount code field | `true` | Set `false` to shorten the form | | `allow_currency_selection` | `feature_flags` | Lets the customer change the billing currency | `true` | Set `false` when you fix the currency with `billing_currency` | | `redirect_immediately` | `feature_flags` | Skips the success page and redirects to `return_url` | `false` | To return the customer to your app right after payment | | `confirm` | top-level | Finalizes the session details at creation. The API returns an error if required data is missing | `false` | With `payment_method_id` for one-click checkout | | `short_link` | top-level | Returns a shortened checkout URL | `false` | When the URL must fit in a push notification or SMS | | `payment_method_id` | top-level | Charges a saved payment method. Requires `confirm: true` and an existing `customer_id` | None | For one-click checkout | | `allowed_payment_method_types` | top-level | Limits checkout to the listed payment methods. A listed method still appears only when it is eligible | All enabled | To show only the methods that suit your product | > [!WARNING] > > **Pass `billing_currency` and `billing_address.country` together.** If you omit either one, Adaptive Currency can pick the billing currency from the customer's IP address. For example, a US customer who travels to Europe can be billed in EUR when the billing country isn't set. > [!TIP] > > **Largest mobile conversion gain:** set `show_order_details: false` and `minimal_address: true`. Together they move payment methods above the fold and remove most address fields. ![Side-by-side checkout: order details expanded (fields below the fold) vs collapsed (fields at the top)](https://mintcdn.com/dodopayments/AWuB1jewz3Hh35sI/images/developer-resources/mobile-checkout-order-details-compare.png?fit=max\&auto=format\&n=AWuB1jewz3Hh35sI\&q=85\&s=af5be5a101610f89a59ea2cf917c4a6d) show\_order\_details: false moves the contact and payment fields above the fold, instead of behind the order summary. Set `minimal_address: true` to collect only a postcode instead of the full street, city, and state fields: ![Side-by-side checkout: full billing address form vs postcode-only](https://mintcdn.com/dodopayments/AWuB1jewz3Hh35sI/images/developer-resources/mobile-checkout-address-compare.png?fit=max\&auto=format\&n=AWuB1jewz3Hh35sI\&q=85\&s=8581345ed2da8992548b34889a1bfb43) minimal\_address: true reduces the billing address to a single postcode field. Set `theme: "system"` so the checkout follows the device's light or dark mode preference: ![Side-by-side checkout: same page rendered in light mode and dark mode](https://mintcdn.com/dodopayments/AWuB1jewz3Hh35sI/images/developer-resources/mobile-checkout-theme-compare.png?fit=max\&auto=format\&n=AWuB1jewz3Hh35sI\&q=85\&s=a9ce3c2a6b3574e6618d5cd76e53040c) With theme: system, the checkout follows the device's light or dark appearance automatically. > [!NOTE] > > **Payment methods depend on the product type.** Apple Pay and Cash App Pay support non-zero recurring subscriptions. One-time payments can use every payment method enabled for your business. See [Payment Methods](/features/payment-methods). > [card] [Full checkout session parameter reference](/developer-resources/checkout-session) > > Every parameter, type, and default value, in the Checkout Sessions guide. ## Mobile-Optimized Recipes Each recipe is a complete checkout session request that your backend sends. Pick the one that matches your scenario and replace the product ID with your own. The Node.js and Python clients are set up in the first recipe, and the other recipes reuse them. > [accordion] Minimal Mobile Checkout - fastest path to payment > > Use this recipe for the shortest form: payment methods at the top, only a postcode for the address, no discount field, and a theme that follows the device. > > > [tab] Node.js SDK > > > > ```javascript expandable theme={null} > > import DodoPayments from 'dodopayments'; > > > > const client = new DodoPayments({ > > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > > environment: 'test_mode', > > }); > > > > const session = await client.checkoutSessions.create({ > > product_cart: [{ product_id: 'pdt_your_product_id', quantity: 1 }], > > customer: { email: 'user@example.com', name: 'Jane Smith' }, > > billing_address: { country: 'US' }, > > return_url: 'myapp://checkout/success', > > cancel_url: 'myapp://checkout/cancelled', > > billing_currency: 'USD', > > minimal_address: true, > > customization: { > > show_order_details: false, > > theme: 'system', > > }, > > feature_flags: { > > allow_discount_code: false, > > allow_currency_selection: false, > > }, > > }); > > > > console.log(session.checkout_url); > > ``` > > > [tab] Python SDK > > > > ```python expandable theme={null} > > import os > > import dodopayments > > > > client = dodopayments.DodoPayments( > > bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), > > environment="test_mode", > > ) > > > > session = client.checkout_sessions.create( > > product_cart=[{"product_id": "pdt_your_product_id", "quantity": 1}], > > customer={"email": "user@example.com", "name": "Jane Smith"}, > > billing_address={"country": "US"}, > > return_url="myapp://checkout/success", > > cancel_url="myapp://checkout/cancelled", > > billing_currency="USD", > > minimal_address=True, > > customization={ > > "show_order_details": False, > > "theme": "system", > > }, > > feature_flags={ > > "allow_discount_code": False, > > "allow_currency_selection": False, > > }, > > ) > > > > print(session.checkout_url) > > ``` > > > [!NOTE] > > > > See [Checkout Sessions](/developer-resources/checkout-session) for all available parameters and their defaults. > [accordion] Branded Mobile Checkout - custom colors, fonts, and button label > > Use this recipe when the checkout page must look like part of your app. It sets your brand colors, a border radius, and a custom pay button label. > > ![Branded mobile checkout with a custom dark navy palette applied via theme\_config](https://mintcdn.com/dodopayments/AWuB1jewz3Hh35sI/images/developer-resources/mobile-checkout-branded.png?fit=max\&auto=format\&n=AWuB1jewz3Hh35sI\&q=85\&s=0d6a85364079e819e1fd882f40e258f4) > > > [tab] Node.js SDK > > > > ```javascript expandable theme={null} > > const session = await client.checkoutSessions.create({ > > product_cart: [{ product_id: 'pdt_your_product_id', quantity: 1 }], > > customer: { email: 'user@example.com', name: 'Jane Smith' }, > > billing_address: { country: 'US' }, > > billing_currency: 'USD', > > return_url: 'myapp://checkout/success', > > minimal_address: true, > > customization: { > > show_order_details: false, > > theme: 'dark', > > theme_config: { > > dark: { > > button_primary: '#7C3AED', > > button_primary_hover: '#6D28D9', > > button_text_primary: '#FFFFFF', > > bg_primary: '#1A1A2E', > > bg_secondary: '#16213E', > > text_primary: '#E2E8F0', > > }, > > pay_button_text: 'Complete Purchase', > > radius: '8px', > > }, > > }, > > }); > > ``` > > > [tab] Python SDK > > > > ```python expandable theme={null} > > session = client.checkout_sessions.create( > > product_cart=[{"product_id": "pdt_your_product_id", "quantity": 1}], > > customer={"email": "user@example.com", "name": "Jane Smith"}, > > billing_address={"country": "US"}, > > billing_currency="USD", > > return_url="myapp://checkout/success", > > minimal_address=True, > > customization={ > > "show_order_details": False, > > "theme": "dark", > > "theme_config": { > > "dark": { > > "button_primary": "#7C3AED", > > "button_primary_hover": "#6D28D9", > > "button_text_primary": "#FFFFFF", > > "bg_primary": "#1A1A2E", > > "bg_secondary": "#16213E", > > "text_primary": "#E2E8F0", > > }, > > "pay_button_text": "Complete Purchase", > > "radius": "8px", > > }, > > }, > > ) > > ``` > > > [!NOTE] > > > > `theme_config` accepts separate `dark` and `light` objects, so the palette follows the device's appearance. For every color key and the font option, see [Checkout Sessions](/developer-resources/checkout-session). > [accordion] One-Click Returning Customer - saved card, instant confirmation > > Use this recipe for signed-in customers who have paid before. Pass the customer's `customer_id`, their saved `payment_method_id`, and `confirm: true` to skip the checkout form. With a `payment_method_id`, the session charges the saved method directly and returns no `checkout_url`, so your app has nothing to open. Learn the outcome from webhooks. > > > [tab] Node.js SDK > > > > ```javascript expandable theme={null} > > const session = await client.checkoutSessions.create({ > > product_cart: [{ product_id: 'pdt_your_product_id', quantity: 1 }], > > customer: { customer_id: 'cus_returning_customer_id' }, > > // confirm: true requires a complete billing address > > billing_address: { > > country: 'US', > > state: 'CA', > > city: 'San Francisco', > > street: '123 Main St', > > zipcode: '94102', > > }, > > billing_currency: 'USD', > > return_url: 'myapp://checkout/success', > > payment_method_id: 'pm_saved_payment_method_id', > > confirm: true, > > show_saved_payment_methods: true, // top-level parameter > > feature_flags: { redirect_immediately: true }, > > }); > > ``` > > > [tab] Python SDK > > > > ```python expandable theme={null} > > session = client.checkout_sessions.create( > > product_cart=[{"product_id": "pdt_your_product_id", "quantity": 1}], > > customer={"customer_id": "cus_returning_customer_id"}, > > # confirm=True requires a complete billing address > > billing_address={ > > "country": "US", > > "state": "CA", > > "city": "San Francisco", > > "street": "123 Main St", > > "zipcode": "94102", > > }, > > billing_currency="USD", > > return_url="myapp://checkout/success", > > payment_method_id="pm_saved_payment_method_id", > > confirm=True, > > show_saved_payment_methods=True, # top-level parameter > > feature_flags={"redirect_immediately": True}, > > ) > > ``` > > > [!NOTE] > > > > Grant access when your backend receives the `payment.succeeded` webhook. Any `status` your app shows is a UI hint only. > [accordion] Subscription with Free Trial - trial before first charge > > Use this recipe for a subscription product with a free trial before the first charge. `trial_period_days` sets the trial length for this session. > > > [tab] Node.js SDK > > > > ```javascript expandable theme={null} > > const session = await client.checkoutSessions.create({ > > product_cart: [{ product_id: 'pdt_your_subscription_product_id', quantity: 1 }], > > customer: { email: 'user@example.com', name: 'Jane Smith' }, > > billing_address: { country: 'US' }, > > billing_currency: 'USD', > > return_url: 'myapp://subscription/activated', > > cancel_url: 'myapp://subscription/cancelled', > > minimal_address: true, > > customization: { > > show_order_details: false, > > theme: 'system', > > }, > > subscription_data: { trial_period_days: 14 }, > > }); > > ``` > > > [tab] Python SDK > > > > ```python expandable theme={null} > > session = client.checkout_sessions.create( > > product_cart=[{"product_id": "pdt_your_subscription_product_id", "quantity": 1}], > > customer={"email": "user@example.com", "name": "Jane Smith"}, > > billing_address={"country": "US"}, > > billing_currency="USD", > > return_url="myapp://subscription/activated", > > cancel_url="myapp://subscription/cancelled", > > minimal_address=True, > > customization={"show_order_details": False, "theme": "system"}, > > subscription_data={"trial_period_days": 14}, > > ) > > ``` > > > [!NOTE] > > > > Grant access when your backend receives the `subscription.active` webhook, not when the mobile SDK returns. For the full webhook flow, see the [Subscription Integration Guide](/developer-resources/subscription-integration-guide). > [accordion] On-Demand Mandate - save a card for future variable charges > > Use this recipe to save a customer's payment method for later charges, such as wallet top-ups, pay-as-you-go, or BNPL, without showing a subscription label. The customer authorizes the payment method once, and you charge variable amounts later. > > > [!NOTE] > > > > Apps that charge by usage follow this pattern. For example, an astrology app charges a pre-authorized card for each session instead of on a fixed schedule. > > > [tab] Node.js SDK > > > > ```javascript expandable theme={null} > > // Step 1: Authorize the mandate (no charge yet) > > const session = await client.checkoutSessions.create({ > > product_cart: [{ product_id: 'pdt_your_subscription_product_id', quantity: 1 }], > > customer: { email: 'user@example.com', name: 'Jane Smith' }, > > billing_address: { country: 'US' }, > > billing_currency: 'USD', > > return_url: 'myapp://mandate/authorized', > > cancel_url: 'myapp://mandate/cancelled', > > minimal_address: true, > > customization: { > > show_order_details: false, > > show_on_demand_tag: false, // hides the "on-demand" / "subscription" label > > theme: 'system', > > }, > > subscription_data: { > > on_demand: { mandate_only: true }, > > }, > > }); > > > > // Step 2: Later, charge any amount using the subscription ID > > // (received via the subscription.active webhook after mandate authorization) > > // await client.subscriptions.charge(subscriptionId, { > > // product_price: 2000, // $20.00 in cents > > // product_currency: 'USD', > > // product_description: 'Session credits', > > // }); > > ``` > > > [tab] Python SDK > > > > ```python expandable theme={null} > > # Step 1: Authorize the mandate (no charge yet) > > session = client.checkout_sessions.create( > > product_cart=[{"product_id": "pdt_your_subscription_product_id", "quantity": 1}], > > customer={"email": "user@example.com", "name": "Jane Smith"}, > > billing_address={"country": "US"}, > > billing_currency="USD", > > return_url="myapp://mandate/authorized", > > cancel_url="myapp://mandate/cancelled", > > minimal_address=True, > > customization={ > > "show_order_details": False, > > "show_on_demand_tag": False, # hides the "on-demand" / "subscription" label > > "theme": "system", > > }, > > subscription_data={"on_demand": {"mandate_only": True}}, > > ) > > > > # Step 2: Later, charge any amount using the subscription ID > > # client.subscriptions.charge( > > # subscription_id, > > # product_price=2000, # $20.00 in cents > > # product_currency="USD", > > # product_description="Session credits", > > # ) > > ``` > > > [!WARNING] > > > > An on-demand charge must be at least `100` in the smallest currency unit (\$1.00 for USD). The API rejects a lower `product_price` with `"product_price: value out of range"`. To authorize without charging, use `mandate_only: true` as shown above, then charge at least that minimum later. > > > [!NOTE] > > > > For the full charge flow, webhook events, and retry policies, see [On-Demand Subscriptions](/developer-resources/ondemand-subscriptions). ## Subscription Flows from Mobile A mobile app starts a subscription with the same checkout session flow as a one-time payment. The SDK opens hosted checkout, the customer subscribes, and your app handles the deep-link return. Your backend manages the rest of the subscription lifecycle. ### Regular Recurring Subscriptions For billing at a fixed interval, such as monthly or yearly, create a checkout session with a subscription product and a deep-link `return_url`. Your backend receives `subscription.active` when the subscription starts. > [!NOTE] > > **Apple Pay** and **Cash App Pay** support non-zero recurring subscriptions. For the complete backend webhook flow, see the [Subscription Integration Guide](/developer-resources/subscription-integration-guide). *** ### On-Demand Subscriptions An on-demand subscription authorizes a customer's payment method once, so you can charge variable amounts later. Use it for wallet top-ups, pay-as-you-go, and any charge whose amount you don't know in advance. For the full request body, see the **On-Demand Mandate** recipe. On mobile, keep these points in mind: * Set `show_on_demand_tag: false` so the checkout page doesn't show subscription or on-demand wording. Customers who save a card for top-ups don't expect subscription terms. * After the customer authorizes the mandate, your backend receives `subscription.active`. Store the `subscription_id`, because every later charge uses it. > [!WARNING] > > An on-demand charge must be at least `100` in the smallest currency unit (\$1.00 for USD). The API rejects a lower amount with `"product_price: value out of range"`. Charge at least that minimum, or use `mandate_only: true` to authorize without charging and collect the first amount later. > > **Don't retry charges in quick succession.** While a previous charge on the same subscription is still processing, a new charge fails with `"Cannot create new charge as previous payment is not successful yet"`. This happens most often with Indian payment methods (UPI and Indian debit and credit cards), where the deduction happens 48 hours after the charge starts. Check that the previous charge has finished before you retry. For the charge endpoint, webhook events, and retry policies, see [On-Demand Subscriptions](/developer-resources/ondemand-subscriptions). *** ### Subscription with Free Trial To offer a trial before the first charge, pass `subscription_data.trial_period_days` in the checkout session. The customer authorizes a payment method at signup, and Dodo Payments charges it when the trial ends. For the full request body, see the **Subscription with Free Trial** recipe. *** ### Upgrades and Downgrades Your backend changes plans through the API, not through a new checkout session. Dodo Payments calculates proration with the proration mode you choose. To let customers change plans themselves, link to the [Customer Portal](/features/customer-portal). > [card] [Subscription Integration Guide](/developer-resources/subscription-integration-guide) > > Backend setup: webhook flow, access provisioning, and cancellation. > [card] [On-Demand Subscriptions](/developer-resources/ondemand-subscriptions) > > Mandate authorization, variable charges, and retry policies. > [card] [Upgrade / Downgrade](/developer-resources/subscription-upgrade-downgrade) > > Proration modes, plan changes, and seat adjustments. > [card] [Customer Portal](/features/customer-portal) > > Self-service subscription management for your customers. ## Reducing Checkout Drop-Offs On a small screen, every form field takes more effort to fill in. The checkout session settings below shorten the form and reduce drop-offs. ### Optimize the Form These settings shorten the checkout form on mobile: | Setting | Recommended value | Effect | | - | - | - | | `show_order_details` | `false` | Collapses the order summary, so payment methods appear at the top | | `minimal_address` | `true` | Asks for only a postcode, or a region where required, instead of street, city, and state | | `show_saved_payment_methods` | `true` | Shows saved payment methods to returning customers | | `allow_discount_code` | `false` | Removes the discount code field | | `theme` | `"system"` | Follows the device's light or dark setting | | `force_language` | Your app's language | Stops checkout from using the browser language | ### Pre-Fill Customer Data Each field you pre-fill is one the customer doesn't have to type: * **New customers**: set `customer.email` and `customer.name` from your auth session. * **Returning customers**: set `customer.customer_id` to use the customer's stored details. * **Currency**: pass `billing_currency` and `billing_address.country` together. ### Recovery Tools Recovery tools bring back customers whose checkout or renewal didn't complete: > [card] [Abandoned Cart Recovery](/features/recovery/abandoned-cart-recovery) > > Email sequences for abandoned or failed checkouts. > [card] [Payment Retries](/features/recovery/payment-retries) > > Automatic retries for failed subscription renewals. > [card] [Subscription Dunning](/features/recovery/subscription-dunning) > > Emails that recover subscriptions with failed payments. > [card] [Recovery Overview](/features/recovery/overview) > > Every recovery tool and the revenue it recovers. ## Best Practices * **Security**: Never ship an API key in your app. Create checkout sessions on your backend and pass only the `checkout_url` to the app. * **Authority**: Treat `CheckoutResult.status` as a UI hint. Grant access only after your backend confirms the payment. * **User Experience**: Show a loading state while your backend creates the session. Don't treat `cancelled` as a failure, because the payment may still have succeeded. * **Testing**: Use test mode and test cards, and check the return URL round trip on a real device as well as a simulator. * **Conversion**: Set `show_order_details: false` and `minimal_address: true`. Together they move payment methods above the fold and remove most address fields. * **Currency**: Pass both `billing_currency` and `billing_address.country`. If you omit either one, Adaptive Currency can pick the billing currency from the customer's IP address. * **On-demand billing**: Set `show_on_demand_tag: false` when you use on-demand subscriptions only to save a card. Customers who top up a wallet don't expect subscription wording. * **Recovery**: Turn on Abandoned Cart Recovery in the dashboard to email customers who don't complete checkout. ## Troubleshooting ### Common Issues * **Callback never arrives**: The scheme in `returnUrl` must match the scheme you registered. On Android, that is the `dodoCallbackScheme` manifest placeholder. On iOS, it is the `Info.plist` URL type. React Native and Flutter apps need both, and in Expo the config plugin sets both. * **Checkout returns to the browser instead of your app (iOS)**: Your app doesn't forward the incoming URL. Call `DodoCheckout.handleOpenURL(url)` from `.onOpenURL`, `scene(_:openURLContexts:)`, or a React Native `Linking` listener. * **`PLATFORM_ERROR` on Android**: The most common cause is a scheme mismatch. It also appears when your `MainActivity` sets `android:taskAffinity=""` (the `flutter create` default), which lets some Android OEM builds lose the in-progress checkout. * **`ALREADY_IN_PROGRESS`**: A checkout is still open. Wait for the previous one to finish, or dismiss it, before you start another. * **Build fails with an unresolved placeholder**: You added the Android SDK but didn't set `manifestPlaceholders["dodoCallbackScheme"]`. * **Payment succeeded but access wasn't granted**: Your app grants access from the mobile result. Grant access from the `payment.succeeded` or `subscription.active` webhook instead. * **Apple Pay or Google Pay doesn't appear on mobile**: Check whether checkout is loading inside an embedded WebView (`WKWebView` or Android `WebView`). Open it with the SDK, or in the system browser surface: a Custom Tab on Android, or `SFSafariViewController` or `ASWebAuthenticationSession` on iOS. ## Additional Resources * [Payment Integration Guide](/developer-resources/integration-guide) * [Webhook Documentation](/developer-resources/webhooks/intents/webhook-events-guide) * [Testing Process](/miscellaneous/testing-process) * [Technical FAQs](/miscellaneous/faq) * [Checkout Session Customization](/developer-resources/checkout-session) * [On-Demand Subscriptions](/developer-resources/ondemand-subscriptions) * [Subscription Upgrade/Downgrade](/developer-resources/subscription-upgrade-downgrade) * [Abandoned Cart Recovery](/features/recovery/abandoned-cart-recovery) * [Customer Portal](/features/customer-portal) > [card] [Contact Support](mailto:support@dodopayments.com) > > For questions or support, email [support@dodopayments.com](mailto:support@dodopayments.com). # Next.js Adaptor Source: https://docs.dodopayments.com/developer-resources/nextjs-adaptor Add Dodo Payments checkout, Customer Portal, and webhook route handlers to a Next.js App Router project with the @dodopayments/nextjs package. The `@dodopayments/nextjs` package gives your Next.js App Router project three route handlers. `Checkout` returns checkout URLs, `CustomerPortal` sends a customer to the Customer Portal, and `Webhooks` verifies webhook events and routes them to your code. The package supports Next.js 14, 15, and 16. > [card] [Checkout Handler](#checkout-route-handler) > > Create checkout URLs with static and checkout session flows. > [card] [Customer Portal](#customer-portal-route-handler) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-route-handler) > > Receive and process Dodo Payments webhook events. ## Installation **1. Install the Package** Run this command in your project root: ```bash theme={null} npm install @dodopayments/nextjs ``` The package also requires Zod 3.25 or Zod 4 as a peer dependency. **2. Set Up Environment Variables** Create a `.env` file in your project root. Create the API key under **Developer → API Keys** and the webhook secret under **Developer → Webhooks** in the dashboard: ```env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_RETURN_URL=https://yourdomain.com/checkout/success DODO_PAYMENTS_ENVIRONMENT="test_mode" # or "live_mode" ``` `DODO_PAYMENTS_RETURN_URL` is where customers land after checkout. If you don't pass an environment, the handlers use `live_mode`. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## Route Handler Examples > [!NOTE] > > All examples assume you use the Next.js App Router. > [tab] Checkout Handler > > > [!NOTE] > > > > Use this handler to add Dodo Payments checkout to your app. A `GET` handler serves static checkout. A `POST` handler serves checkout sessions. > > ```typescript Next.js Route Handler expandable theme={null} > // app/checkout/route.ts > import { Checkout } from "@dodopayments/nextjs"; > > export const GET = Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > type: "static", // optional, defaults to 'static' > }); > > export const POST = Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > type: "session", // for checkout sessions > }); > ``` > > ```bash Static Checkout cURL Example expandable theme={null} > curl --request GET \ > --url 'https://example.com/checkout?productId=pdt_123' > ``` > > ```bash Checkout Session cURL Example expandable theme={null} > curl --request POST \ > --url https://example.com/checkout \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_123", > "quantity": 1 > } > ], > "customer": { > "email": "customer@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal Handler > > > [!NOTE] > > > > Use this handler to send customers to the Dodo Payments Customer Portal, where they manage their subscriptions and details. > > ```typescript Next.js Route Handler expandable theme={null} > // app/customer-portal/route.ts > import { CustomerPortal } from "@dodopayments/nextjs"; > > export const GET = CustomerPortal({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > }); > ``` > > ```bash Customer Portal cURL Example expandable theme={null} > curl --request GET \ > --url 'https://example.com/customer-portal?customer_id=cus_123&send_email=true' > ``` > [tab] Webhook Handler > > > [!NOTE] > > > > Use this handler to receive Dodo Payments webhook events in your Next.js app and verify their signatures. > > ```typescript Next.js Route Handler expandable theme={null} > // app/api/webhook/dodo-payments/route.ts > import { Webhooks } from "@dodopayments/nextjs"; > > export const POST = Webhooks({ > webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, > onPayload: async (payload) => { > // handle the payload > }, > // ... other event handlers for granular control > }); > ``` ## Checkout Route Handler The checkout handler supports all three ways to take payments with Dodo Payments: * **Static Payment Links:** Shareable URLs that collect payments without code. * **Dynamic Payment Links (deprecated):** Payment links you generate with custom details. They use deprecated endpoints. * **Checkout Sessions:** Hosted checkout with a product cart, customer details, and customization options. This is the recommended flow. > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_123`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's address line. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's ZIP or postal code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > Payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed as metadata. > > The handler adds `returnUrl` from its config to the link as `redirect_url`. > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters and product IDs that don't exist also return 400. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL. In test mode, the URL uses `test.checkout.dodopayments.com`. > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/..." > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send the parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. > * `billing` and `customer` are required. > * For every supported body field, see: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic checkout proxies the deprecated `POST /payments` and `POST /subscriptions` endpoints. It keeps working for existing integrations, but new integrations should use checkout sessions. > > ### Response Format > > Dynamic checkout returns a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/..." > } > ``` > [accordion] Checkout Sessions (POST) > > Checkout sessions create a hosted checkout for one-time purchases and subscriptions, with full control over customization. `product_cart` is the only required field, and it needs at least one product. If the body has no `return_url`, the handler uses `returnUrl` from its config. > > For more details and every supported field, see the [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session). > > A session created with `payment_method_id` returns no checkout URL, so the handler responds with 400. To charge a saved payment method, create the session with the SDK instead. > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/session/..." > } > ``` ## Customer Portal Route Handler The Customer Portal route handler creates a Customer Portal session for the customer you pass and redirects the browser to it. > [!WARNING] > > The handler doesn't check who is calling it. Anyone who requests it with a customer ID gets that customer's portal. Protect the route with your own authentication, and pass only the signed-in user's customer ID. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, Dodo Payments also emails the portal link to the customer. The handler returns 400 if `customer_id` is missing, and 500 if the portal session can't be created. ## Webhook Route Handler The webhook route handler verifies each request before it runs your code: * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the raw request body against the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`. Returns 401 if verification fails. * **Payload Validation:** Parses the verified body as JSON and validates it with Zod. Returns 400 when a parsed payload doesn't match the webhook schema. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Unexpected verification errors, malformed JSON, or errors thrown by your callbacks * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200. The adaptor doesn't catch errors thrown in your handlers. They propagate to Next.js, and the request fails. ### Supported Webhook Event Handlers Each handler receives the verified payload for its event type: ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` For what each event means, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). ## Prompt for LLM Copy this prompt into your AI coding assistant to have it add the adaptor to your project. To give your agent the Dodo Payments docs and skills as well, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ```text expandable theme={null} You are an expert Next.js developer assistant. Your task is to guide a user through integrating the @dodopayments/nextjs adapter into their existing Next.js project. The @dodopayments/nextjs adapter provides route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed for the Next.js App Router. First, install the necessary packages. Use the package manager appropriate for your project (npm, yarn, or bun) based on the presence of lock files (e.g., package-lock.json for npm, yarn.lock for yarn, bun.lockb for bun): npm install @dodopayments/nextjs Here's how you should structure your response: Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/nextjs adapter would you like to integrate into your project? You can choose one or more of the following: Checkout Route Handler (for handling product checkouts) Customer Portal Route Handler (for managing customer subscriptions/details) Webhook Route Handler (for receiving Dodo Payments webhook events) All (integrate all three)" Based on the user's selection, provide detailed integration steps for each chosen functionality. If Checkout Route Handler is selected: Purpose: This handler manages static checkout and checkout sessions. Both return JSON responses with checkout URLs for programmatic handling. File Creation: Create a new file at app/checkout/route.ts in your Next.js project. Code Snippet: // app/checkout/route.ts import { Checkout } from '@dodopayments/nextjs' export const GET = Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY!, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", type: "static", }); export const POST = Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY!, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", type: "session", // for checkout sessions }); Configuration & Usage: bearerToken: Your Dodo Payments API key. It's recommended to set this via the DODO_PAYMENTS_API_KEY environment variable. returnUrl: (Optional) The URL to redirect the user to after a successful checkout. environment: (Optional) Set to "test_mode" for testing, or omit/set to "live_mode" for production. type: (Optional) Set to "static" for GET/static checkout or "session" for POST/checkout sessions. Static Checkout (GET) Query Parameters: productId (required): Product identifier (e.g., ?productId=pdt_123) quantity (optional): Quantity of the product Customer Fields (optional): fullName, firstName, lastName, email, country, addressLine, city, state, zipCode Disable Flags (optional, set to true to disable): disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode Advanced Controls (optional): paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts Metadata (optional): Any query parameter starting with metadata_ (e.g., ?metadata_userId=abc123) Returns: {"checkout_url": "https://checkout.dodopayments.com/..."} Checkout Sessions (POST) - (Recommended) A more customizable checkout experience. Returns JSON with checkout_url: Parameters are sent as a JSON body. Supports both one-time and recurring payments. Returns: {"checkout_url": "https://checkout.dodopayments.com/session/..."}. For a complete list of supported fields, refer to: Checkout Sessions Integration Guide: https://docs.dodopayments.com/developer-resources/checkout-session Error Handling: If productId is missing or other parameters are invalid, the handler will return a 400 response. If Customer Portal Route Handler is selected: Purpose: This handler redirects a customer to their Dodo Payments customer portal. It does not authenticate the caller, so protect the route and pass only the signed-in user's customer ID. File Creation: Create a new file at app/customer-portal/route.ts in your Next.js project. Code Snippet: // app/customer-portal/route.ts import { CustomerPortal } from '@dodopayments/nextjs' export const GET = CustomerPortal({ bearerToken: process.env.DODO_PAYMENTS_API_KEY!, environment: "test_mode", }); Query Parameters: customer_id (required): The customer ID for the portal session (e.g., ?customer_id=cus_123) send_email (optional, boolean): If set to true, sends an email to the customer with the portal link. Returns 400 if customer_id is missing. If Webhook Route Handler is selected: Purpose: This handler processes incoming webhook events from Dodo Payments, allowing your application to react to events like successful payments, refunds, or subscription changes. File Creation: Create a new file at app/api/webhook/dodo-payments/route.ts in your Next.js project. Code Snippet: // app/api/webhook/dodo-payments/route.ts import { Webhooks } from '@dodopayments/nextjs' export const POST = Webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, onPayload: async (payload) => { // handle the payload }, // ... other event handlers for granular control }); Handler Details: Method: Only POST requests are supported. Other methods return 405. Signature Verification: The handler verifies the webhook signature using the webhookKey and returns 401 if verification fails. Payload Validation: The payload is validated with Zod. Returns 400 for invalid payloads. Error Handling: 401: Invalid signature 400: Invalid payload 500: Internal error during verification Event Routing: Calls the appropriate event handler based on the payload type. Supported Webhook Event Handlers: onPayload?: (payload: WebhookPayload) => Promise onPaymentSucceeded?: (payload: WebhookPayload) => Promise onPaymentFailed?: (payload: WebhookPayload) => Promise onPaymentProcessing?: (payload: WebhookPayload) => Promise onPaymentCancelled?: (payload: WebhookPayload) => Promise onRefundSucceeded?: (payload: WebhookPayload) => Promise onRefundFailed?: (payload: WebhookPayload) => Promise onDisputeOpened?: (payload: WebhookPayload) => Promise onDisputeExpired?: (payload: WebhookPayload) => Promise onDisputeAccepted?: (payload: WebhookPayload) => Promise onDisputeCancelled?: (payload: WebhookPayload) => Promise onDisputeChallenged?: (payload: WebhookPayload) => Promise onDisputeWon?: (payload: WebhookPayload) => Promise onDisputeLost?: (payload: WebhookPayload) => Promise onSubscriptionActive?: (payload: WebhookPayload) => Promise onSubscriptionOnHold?: (payload: WebhookPayload) => Promise onSubscriptionRenewed?: (payload: WebhookPayload) => Promise onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise onSubscriptionCancelled?: (payload: WebhookPayload) => Promise onSubscriptionFailed?: (payload: WebhookPayload) => Promise onSubscriptionExpired?: (payload: WebhookPayload) => Promise onSubscriptionUpdated?: (payload: WebhookPayload) => Promise onSubscriptionPaused?: (payload: WebhookPayload) => Promise onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise onLicenseKeyCreated?: (payload: WebhookPayload) => Promise onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise onDunningStarted?: (payload: WebhookPayload) => Promise onDunningRecovered?: (payload: WebhookPayload) => Promise onCreditAdded?: (payload: WebhookPayload) => Promise onCreditDeducted?: (payload: WebhookPayload) => Promise onCreditExpired?: (payload: WebhookPayload) => Promise onCreditRolledOver?: (payload: WebhookPayload) => Promise onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise onCreditOverageCharged?: (payload: WebhookPayload) => Promise onCreditOverageReset?: (payload: WebhookPayload) => Promise onCreditManualAdjustment?: (payload: WebhookPayload) => Promise onCreditBalanceLow?: (payload: WebhookPayload) => Promise onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise onPayoutCreated?: (payload: WebhookPayload) => Promise onPayoutOnHold?: (payload: WebhookPayload) => Promise onPayoutInProgress?: (payload: WebhookPayload) => Promise onPayoutFailed?: (payload: WebhookPayload) => Promise onPayoutSuccess?: (payload: WebhookPayload) => Promise Environment Variable Setup: To ensure the adapter functions correctly, you will need to manually set up the following environment variables in your Next.js project's deployment environment (e.g., Vercel, Netlify, AWS, etc.): DODO_PAYMENTS_API_KEY: Your Dodo Payments API Key (required for Checkout and Customer Portal). DODO_PAYMENTS_RETURN_URL: (Optional) The URL to redirect to after a successful checkout (for Checkout handler). DODO_PAYMENTS_WEBHOOK_KEY: Your Dodo Payments Webhook Secret (required for Webhook handler). Example .env file: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_ENVIRONMENT="test_mode" # or "live_mode" DODO_PAYMENTS_RETURN_URL=your-return-url Usage in your code: bearerToken: process.env.DODO_PAYMENTS_API_KEY! webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY! Important: Never commit sensitive environment variables directly into your version control. Use environment variables for all sensitive information. If the user needs assistance setting up environment variables for their specific deployment environment, ask them what platform they are using (e.g., Vercel, Netlify, AWS, etc.), and provide guidance. You can also add comments to their PR or chat depending on the context ``` # Next.js Minimal Boilerplate Source: https://docs.dodopayments.com/developer-resources/nextjs-boilerplate Clone the Next.js minimal boilerplate to get a pricing page, checkout sessions, a webhook handler, and a Customer Portal link wired to Dodo Payments. ## Overview The Next.js minimal boilerplate is a starter app with Dodo Payments already connected. Add your API keys and product IDs, and you get a pricing page that opens checkout, a webhook endpoint for payment events, and a link to the Customer Portal. > [!NOTE] > > This boilerplate uses the Next.js 16 App Router with TypeScript, Tailwind CSS 4, and the `@dodopayments/nextjs` adaptor. To add the same route handlers to an existing app, see the [Next.js Adaptor](/developer-resources/nextjs-adaptor). ### Features The boilerplate includes: * **Quick Setup**: Go from clone to a running pricing page in about five minutes. * **Checkout**: A pre-configured checkout flow built on `@dodopayments/nextjs`. * **Pricing Page**: A dark-themed pricing page styled with Tailwind CSS. * **Webhook Handler**: An endpoint that verifies each webhook signature and runs your code for the event. * **Customer Portal**: A header link that opens the Customer Portal, where customers manage their subscriptions. * **TypeScript**: Typed product definitions and handlers. * **Pre-filled Checkout**: Passes the customer's name and email to checkout, so the customer doesn't retype them. ## Prerequisites Before you begin, you need: * **Node.js 20.9 or later**, which Next.js 16 requires. * **A Dodo Payments account**, to create an API key and a webhook signing secret in the dashboard. ## Quick Start **1. Clone the Repository** ```bash theme={null} git clone https://github.com/dodopayments/dodo-nextjs-minimal-boilerplate.git cd dodo-nextjs-minimal-boilerplate ``` **2. Install Dependencies** ```bash theme={null} npm install ``` **3. Get API Credentials** Sign up at [Dodo Payments](https://dodopayments.com/), then get your credentials from the dashboard: * **API Key:** Create a key under [Dashboard → Developer → API Keys](https://app.dodopayments.com/developer/api-keys). * **Webhook Key:** Add an endpoint under [Dashboard → Developer → Webhooks](https://app.dodopayments.com/developer/webhooks), then copy its signing secret. The endpoint URL must be public and use HTTPS. To receive events on your machine, see [Webhook Events](#webhook-events). > [!TIP] > > Create both while the **Live Mode** switch in the sidebar is off. A test mode key works only with `DODO_PAYMENTS_ENVIRONMENT=test_mode`, and test mode payments don't move real money. **4. Configure Environment Variables** Copy the example file to create a `.env` file in the root directory: ```bash theme={null} cp .env.example .env ``` Set the values to your Dodo Payments credentials: ```env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_signing_key_here DODO_PAYMENTS_RETURN_URL=http://localhost:3000 DODO_PAYMENTS_ENVIRONMENT=test_mode ``` The route handlers read these variables: * `DODO_PAYMENTS_API_KEY` authenticates the checkout and Customer Portal handlers. * `DODO_PAYMENTS_WEBHOOK_KEY` verifies webhook signatures. * `DODO_PAYMENTS_RETURN_URL` is where checkout sends the customer after payment. * `DODO_PAYMENTS_ENVIRONMENT` is `test_mode` or `live_mode`. > [!WARNING] > > Don't commit your `.env` file to version control. The repository's `.gitignore` already excludes it. **5. Add Your Products** Replace the sample products in `src/lib/products.ts` with your own. Set each `product_id` to the ID of a product under **Products** in your dashboard: ```typescript theme={null} export const products: Product[] = [ { product_id: "pdt_001", // Replace with your product ID name: "Basic Plan", description: "Get access to basic features and support", price: 9999, // in cents features: [ "Access to basic features", "Email support", "1 Team member", "Basic analytics", ], }, // ... add more products ]; ``` The pricing page displays `name`, `description`, `price`, and `features` from this file. Checkout charges the price set on the product in Dodo Payments, so keep `price` in sync with it. **6. Run the Development Server** ```bash theme={null} npm run dev ``` Open [http://localhost:3000](http://localhost:3000) to see your pricing page. ## Project Structure The checkout, Customer Portal, and webhook route handlers live under `src/app/api/`: ```text theme={null} src/ ├── app/ │ ├── api/ │ │ ├── checkout/ # Checkout session handler │ │ ├── customer-portal/ # Customer portal redirect │ │ └── webhook/ # Webhook event handler │ ├── components/ │ │ ├── Footer.tsx # Reusable footer │ │ ├── Header.tsx # Navigation header │ │ └── ProductCard.tsx # Product pricing card │ ├── globals.css # Global styles │ ├── layout.tsx # Root layout │ └── page.tsx # Pricing page (home) └── lib/ └── products.ts # Product definitions ``` ## Customization ### Update Product Information Edit `src/lib/products.ts` to change: * Product IDs, from **Products** in your Dodo Payments dashboard * Prices * Features * Descriptions ### Pre-fill Customer Data `src/app/components/ProductCard.tsx` sends a hardcoded name and email with each checkout request. Replace them with the signed-in user's details: ```typescript theme={null} customer: { name: "John Doe", email: "john@example.com", }, ``` ### Update Customer Portal The **Customer Portal** link in `src/app/components/Header.tsx` opens `/api/customer-portal` with a hardcoded customer ID. Replace it with the signed-in user's Dodo Payments customer ID: ```typescript theme={null} const CUSTOMER_ID = "cus_001"; // Replace with actual customer ID ``` To get a customer ID for testing, complete a test purchase, then copy the customer's ID from **Customers** in the dashboard. In production, fetch the ID from your backend. ## Webhook Events The handler in `src/app/api/webhook/route.ts` verifies each request with `DODO_PAYMENTS_WEBHOOK_KEY`, then handles two events: * `onSubscriptionActive` runs when a subscription becomes active (`subscription.active`). * `onPaymentSucceeded` runs when a payment succeeds (`payment.succeeded`). Add your business logic inside these handlers: ```typescript theme={null} onSubscriptionActive: async (payload) => { // Grant access to your product // Update user database // Send welcome email }, ``` To handle more events, add their handlers, such as `onSubscriptionCancelled`. The [Next.js Adaptor](/developer-resources/nextjs-adaptor#supported-webhook-event-handlers) lists every supported handler. Dodo Payments can't reach `localhost`. For local development, use a tunnel such as [ngrok](https://ngrok.com/) to expose your local server, and use the tunnel URL as your webhook endpoint. ## Deployment ### Build for Production ```bash theme={null} npm run build npm start ``` ### Deploy to Vercel [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/dodopayments/dodo-nextjs-minimal-boilerplate) Add the four environment variables in the Vercel dashboard, and set `DODO_PAYMENTS_RETURN_URL` to your production URL. ### Update Webhook URL After deploying, add your production webhook URL in the [Dodo Payments Dashboard](https://app.dodopayments.com/developer/webhooks), with your domain in place of `example.com`: ```text theme={null} https://example.com/api/webhook ``` Each endpoint has its own signing secret. Copy the new endpoint's secret into `DODO_PAYMENTS_WEBHOOK_KEY` in your production environment. ## Troubleshooting > [accordion] Module not found or build errors > > Delete `node_modules` and `package-lock.json`, then reinstall dependencies: > > ```bash theme={null} > rm -rf node_modules package-lock.json > npm install > ``` > [accordion] Checkout redirect fails > > Check for these common causes: > > * The product ID doesn't exist in your Dodo Payments dashboard. > * The API key or `DODO_PAYMENTS_ENVIRONMENT` in `.env` is wrong. A test mode key works only with `test_mode`. > > Look for the error in the browser console and in the terminal that runs `npm run dev`. > [accordion] Webhooks not receiving events > > For local testing, use [ngrok](https://ngrok.com) to expose your server: > > ```bash theme={null} > ngrok http 3000 > ``` > > In your [Dodo dashboard](https://app.dodopayments.com/developer/webhooks), add an endpoint with the ngrok HTTPS URL followed by `/api/webhook`. Copy that endpoint's signing secret into `DODO_PAYMENTS_WEBHOOK_KEY` in your `.env` file. > [accordion] Customer portal link doesn't work > > Replace the hardcoded `CUSTOMER_ID` in `src/app/components/Header.tsx` with the ID of a customer in your Dodo Payments dashboard. > > In production, get the customer ID from your authentication system and database instead. ## Learn More * [Dodo Payments Documentation](https://docs.dodopayments.com/) * [Checkout Sessions Documentation](https://docs.dodopayments.com/developer-resources/checkout-session) * [Webhooks Documentation](https://docs.dodopayments.com/developer-resources/webhooks) * [Next.js Adaptor](/developer-resources/nextjs-adaptor): options for the `Checkout`, `CustomerPortal`, and `Webhooks` handlers ## Support For help with the boilerplate: * Ask questions in the [Discord community](https://discord.gg/bYqAp4ayYh). * Report issues and follow updates in the [GitHub repository](https://github.com/dodopayments/dodo-nextjs-minimal-boilerplate). * Email the [support team](mailto:support@dodopayments.com). # Nuxt Adaptor Source: https://docs.dodopayments.com/developer-resources/nuxt-adaptor Add Dodo Payments checkout, Customer Portal, and webhook server routes to a Nuxt 3 app with the @dodopayments/nuxt module and runtime config. The `@dodopayments/nuxt` module gives your Nuxt app three server route handlers. `checkoutHandler` returns checkout URLs, `customerPortalHandler` sends a customer to the Customer Portal, and `Webhooks` verifies webhook events and routes them to your code. > [card] [Checkout API Route](#checkout-route-handler) > > Create checkout URLs from a Nuxt server route. > [card] [Customer Portal API Route](#customer-portal-route-handler) > > Let customers manage their subscriptions and details from a Nuxt server route. > [card] [Webhooks API Route](#webhook-route-handler) > > Receive and verify Dodo Payments webhook events in Nuxt. ## Overview > [!NOTE] > > The module registers its handlers as Nuxt server auto-imports, so your server routes call `checkoutHandler`, `customerPortalHandler`, and `Webhooks` without import statements. Each route reads your credentials from `runtimeConfig`. Nuxt exposes only `runtimeConfig.public` to the browser, so the API key and webhook secret stay on the server. ## Installation **1. Install the Nuxt Module** Run this command in your project root: ```bash theme={null} npm install @dodopayments/nuxt ``` The module lists Nuxt 3 (3.13.1 or later) and `zod` 3.25 or later as peer dependencies. **2. Register the Module in nuxt.config.ts** Add `@dodopayments/nuxt` to your `modules` array, and map your credentials into `runtimeConfig`: ```typescript nuxt.config.ts expandable theme={null} export default defineNuxtConfig({ modules: ["@dodopayments/nuxt"], devtools: { enabled: true }, compatibilityDate: "2025-02-25", runtimeConfig: { private: { bearerToken: process.env.NUXT_PRIVATE_BEARER_TOKEN, webhookKey: process.env.NUXT_PRIVATE_WEBHOOK_KEY, environment: process.env.NUXT_PRIVATE_ENVIRONMENT, returnUrl: process.env.NUXT_PRIVATE_RETURN_URL }, } }); ``` Set these environment variables, for example in a `.env` file in your project root: | Variable | Value | | - | - | | `NUXT_PRIVATE_BEARER_TOKEN` | Your API key. Create it under **Developer → API Keys** in the dashboard. | | `NUXT_PRIVATE_WEBHOOK_KEY` | Your webhook secret. Add your endpoint under **Developer → Webhooks** and copy its signing secret. | | `NUXT_PRIVATE_ENVIRONMENT` | `test_mode` or `live_mode`. If it's unset, the handlers use `live_mode`. | | `NUXT_PRIVATE_RETURN_URL` | Optional. The URL customers land on after checkout. | A built Nuxt server doesn't read your `.env` file. At runtime, Nuxt overrides a `runtimeConfig` value only from the variable that matches its path, such as `NUXT_PRIVATE_RETURN_URL` for `private.returnUrl`, so set these variables in your hosting environment too. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## API Route Handler Examples > [!NOTE] > > The examples create server routes in the `server/routes/api/` directory. Nuxt routes each file by its name and method suffix, so `checkout.get.ts` handles `GET /api/checkout`. > [tab] Checkout API Route > > > [!NOTE] > > > > Use this handler to add Dodo Payments checkout to your Nuxt app. A GET route serves static checkout. A POST route serves checkout sessions. > > Create a GET route for static checkout: > > ```typescript server/routes/api/checkout.get.ts expandable theme={null} > export default defineEventHandler((event) => { > const { > private: { bearerToken, environment, returnUrl }, > } = useRuntimeConfig(); > > const handler = checkoutHandler({ > bearerToken: bearerToken, > environment: environment as "test_mode" | "live_mode", > returnUrl: returnUrl, > }); > > return handler(event); > }); > ``` > > Create a POST route for checkout sessions: > > ```typescript server/routes/api/checkout.post.ts expandable theme={null} > export default defineEventHandler((event) => { > const { > private: { bearerToken, environment, returnUrl }, > } = useRuntimeConfig(); > > const handler = checkoutHandler({ > bearerToken: bearerToken, > environment: environment as "test_mode" | "live_mode", > returnUrl: returnUrl, > type: "session" > }); > > return handler(event); > }); > ``` > > > [!WARNING] > > > > If `productId` is missing or invalid, the handler returns a 400 response. > > To test the routes, send these requests: > > ```bash Static Checkout cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/checkout?productId=pdt_fqJhl7pxKWiLhwQR042rh' > ``` > > ```bash Checkout Session cURL Example expandable theme={null} > curl --request POST \ > --url https://example.com/api/checkout \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_QMDuvLkbVzCRWRQjLNcs", > "quantity": 1 > } > ], > "customer": { > "email": "customer@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal API Route > > > [!NOTE] > > > > Create a GET route that sends customers to their Customer Portal. The route reads `customer_id` from the query string. > > ```typescript server/routes/api/customer-portal.get.ts expandable theme={null} > export default defineEventHandler((event) => { > const { > private: { bearerToken, environment }, > } = useRuntimeConfig(); > > const handler = customerPortalHandler({ > bearerToken, > environment: environment as "test_mode" | "live_mode", > }); > > return handler(event); > }); > ``` > > **Query Parameters:** > > * `customer_id` (required): The customer ID for the portal session, for example `?customer_id=cus_123`. > > * `send_email` (optional, boolean): If `true`, Dodo Payments also emails the portal link to the customer. > > > [!WARNING] > > > > From `@dodopayments/nuxt` 0.2.11, the handler returns HTTP `400` if `customer_id` is missing and HTTP `500` if the portal session can't be created. Earlier versions return HTTP `200` in both cases, with a JSON body such as `{ "status": 400, "body": "Missing customer_id in query parameters" }`. To rely on the HTTP status, upgrade to 0.2.11 or later. > > ```bash Customer Portal cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/customer-portal?customer_id=cus_9VuW4K7O3GHwasENg31m&send_email=true' > ``` > [tab] Webhook API Route > > > [!NOTE] > > > > Create a POST route to receive Dodo Payments webhook events and verify their signatures. > > ```typescript server/routes/api/webhook.post.ts expandable theme={null} > export default defineEventHandler((event) => { > const { > private: { webhookKey }, > } = useRuntimeConfig(); > > const handler = Webhooks({ > webhookKey: webhookKey, > onPayload: async (payload: any) => { > // Handle webhook payload here > }, > // ...add other event handlers as needed > }); > > return handler(event); > }); > ``` ## Checkout Route Handler The checkout handler supports all three ways to take payments with Dodo Payments: * **Static Payment Links:** Shareable URLs that collect payments without code. * **Dynamic Payment Links (deprecated):** Payment links you generate with custom details. They use deprecated endpoints. * **Checkout Sessions:** Hosted checkout with a product cart, customer details, and customization options. This is the recommended flow. `checkoutHandler` takes these options: | Option | Type | Description | | - | - | - | | `bearerToken` | `string` | Your Dodo Payments API key. | | `environment` | `string` | `test_mode` or `live_mode`. Defaults to `live_mode`. | | `returnUrl` | `string` | Optional. The URL that checkout redirects the customer to after payment. A `return_url` in a POST body takes precedence. | | `type` | `string` | Optional. On a GET route, leave it unset or set `static`, because other values make static checkout return 400. On a POST route, `dynamic` selects dynamic checkout, and any other value, or none, selects checkout sessions. | > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_nZuwz45WAs64n3l07zpQR`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's address line. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's ZIP or postal code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > Payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed as metadata. > > The handler adds `returnUrl` from its config to the link as `redirect_url`. > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters and product IDs that don't exist also return 400. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL. In test mode, the URL uses `test.checkout.dodopayments.com`. > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/..." > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send the parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. > * `billing` and `customer` are required. > * For every supported body field, see: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic checkout proxies the deprecated `POST /payments` and `POST /subscriptions` endpoints. It keeps working for existing integrations, but new integrations should use checkout sessions. > > ### Response Format > > Dynamic checkout returns a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/..." > } > ``` > [accordion] Checkout Sessions (POST) > > Checkout sessions create a hosted checkout for one-time purchases and subscriptions, with full control over customization. `product_cart` is the only required field, and it needs at least one product. If the body has no `return_url`, the handler uses `returnUrl` from its config. > > For more details and every supported field, see the [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session). > > A session created with `payment_method_id` returns no checkout URL, so the handler responds with 400. To charge a saved payment method, create the session with the SDK instead. > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/session/..." > } > ``` ## Customer Portal Route Handler The Customer Portal route handler creates a Customer Portal session for the customer you pass and redirects the browser to it. > [!WARNING] > > The handler doesn't check who is calling it. Anyone who requests it with a customer ID gets that customer's portal. Protect the route with your own authentication, and pass only the signed-in user's customer ID. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, Dodo Payments also emails the portal link to the customer. > [!WARNING] > > From `@dodopayments/nuxt` 0.2.11, the handler returns HTTP `400` if `customer_id` is missing and HTTP `500` if the portal session can't be created. Earlier versions return HTTP `200` in both cases, with a JSON body such as `{ "status": 400, "body": "Missing customer_id in query parameters" }`. To rely on the HTTP status, upgrade to 0.2.11 or later. ## Webhook Route Handler The webhook route handler verifies each request before it runs your code: * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the raw request body and the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`, following the [Standard Webhooks](https://standardwebhooks.com/) specification. Returns 401 if verification fails. * **Payload Validation:** Validates the payload with Zod. Returns 400 for an invalid payload. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Internal error during verification * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200. The adaptor doesn't catch errors thrown in your handlers. They propagate to Nuxt, and the request fails. ### Supported Webhook Event Handlers Each handler receives the verified payload for its event type: ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` For what each event means, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). *** ## Prompt for LLM Copy this prompt into your AI coding assistant to have it add the module to your project. To give your agent the Dodo Payments docs and skills as well, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ```text expandable theme={null} You are an expert Nuxt developer assistant. Your task is to guide a user through integrating the @dodopayments/nuxt module into their existing Nuxt project. The @dodopayments/nuxt module provides API route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed for Nuxt 3 server routes. The module auto-imports checkoutHandler, customerPortalHandler, and Webhooks into server routes, so the route files need no import statements. First, install the necessary package: npm install @dodopayments/nuxt Second, add the configuration to nuxt.config.ts export default defineNuxtConfig({ modules: ["@dodopayments/nuxt"], devtools: { enabled: true }, compatibilityDate: "2025-02-25", runtimeConfig: { private: { bearerToken: process.env.NUXT_PRIVATE_BEARER_TOKEN, webhookKey: process.env.NUXT_PRIVATE_WEBHOOK_KEY, environment: process.env.NUXT_PRIVATE_ENVIRONMENT, returnUrl: process.env.NUXT_PRIVATE_RETURN_URL }, } }); Here's how you should structure your response: Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/nuxt module would you like to integrate into your project? You can choose one or more of the following: Checkout API Route (for handling product checkouts) Customer Portal API Route (for managing customer subscriptions/details) Webhook API Route (for receiving Dodo Payments webhook events) All (integrate all three)" Based on the user's selection, provide detailed integration steps for each chosen functionality. If Checkout API Route is selected: Purpose: This route returns a JSON response with a checkout_url for the Dodo Payments checkout page. File Creation: Create a new file at server/routes/api/checkout.get.ts in your Nuxt project. Code Snippet: // server/routes/api/checkout.get.ts export default defineEventHandler((event) => { const { private: { bearerToken, environment, returnUrl }, } = useRuntimeConfig(); const handler = checkoutHandler({ bearerToken: bearerToken, environment: environment as "test_mode" | "live_mode", returnUrl: returnUrl, }); return handler(event); }); Configuration & Usage: - bearerToken: Your Dodo Payments API key. Set via the NUXT_PRIVATE_BEARER_TOKEN environment variable. - returnUrl: (Optional) The URL to redirect the user to after a successful checkout. - environment: (Optional) "test_mode" or "live_mode". Defaults to "live_mode". - type: (Optional) On a POST route (server/routes/api/checkout.post.ts), set "session" for checkout sessions. Static Checkout (GET) Query Parameters: - productId (required): Product identifier (e.g., ?productId=pdt_nZuwz45WAs64n3l07zpQR) - quantity (optional): Quantity of the product - Customer Fields (optional): fullName, firstName, lastName, email, country, addressLine, city, state, zipCode - Disable Flags (optional, set to true to disable): disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode - Advanced Controls (optional): paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts - Metadata (optional): Any query parameter starting with metadata_ (e.g., ?metadata_userId=abc123) Checkout Sessions (POST) - (Recommended) A more customizable checkout experience. Returns JSON with checkout_url: Parameters are sent as a JSON body, and product_cart is required. Supports both one-time and recurring payments. Returns: {"checkout_url": "https://checkout.dodopayments.com/session/..."}. For a complete list of supported fields, refer to: Checkout Sessions Integration Guide: https://docs.dodopayments.com/developer-resources/checkout-session Error Handling: If productId is missing or other query parameters are invalid, the handler will return a 400 response. If Customer Portal API Route is selected: Purpose: This route redirects a customer to their Dodo Payments customer portal. It does not authenticate the caller, so protect the route and pass only the signed-in user's customer ID. File Creation: Create a new file at server/routes/api/customer-portal.get.ts in your Nuxt project. Code Snippet: // server/routes/api/customer-portal.get.ts export default defineEventHandler((event) => { const { private: { bearerToken, environment }, } = useRuntimeConfig(); const handler = customerPortalHandler({ bearerToken, environment: environment as "test_mode" | "live_mode", }); return handler(event); }); Query Parameters: - customer_id (required): The customer ID for the portal session (e.g., ?customer_id=cus_123) - send_email (optional, boolean): If set to true, sends an email to the customer with the portal link. - Returns 400 if customer_id is missing, and 500 if the portal session cannot be created (@dodopayments/nuxt 0.2.11 or later). If Webhook API Route is selected: Purpose: This route processes incoming webhook events from Dodo Payments, allowing your application to react to events like successful payments, refunds, or subscription changes. File Creation: Create a new file at server/routes/api/webhook.post.ts in your Nuxt project. Code Snippet: // server/routes/api/webhook.post.ts export default defineEventHandler((event) => { const { private: { webhookKey }, } = useRuntimeConfig(); const handler = Webhooks({ webhookKey: webhookKey, onPayload: async (payload) => { // handle the payload }, // ... other event handlers for granular control }); return handler(event); }); Handler Details: - Method: Only POST requests are supported. Other methods return 405. - Signature Verification: The handler verifies the webhook signature using webhookKey and returns 401 if verification fails. - Payload Validation: The payload is validated with Zod. Returns 400 for invalid payloads. Error Handling: - 401: Invalid signature - 400: Invalid payload - 500: Internal error during verification Event Routing: Calls onPayload for every event, then the handler for the event's type. Supported event handlers include: - onPayload?: (payload: WebhookPayload) => Promise - onPaymentSucceeded?: (payload: WebhookPayload) => Promise - onPaymentFailed?: (payload: WebhookPayload) => Promise - onPaymentProcessing?: (payload: WebhookPayload) => Promise - onPaymentCancelled?: (payload: WebhookPayload) => Promise - onRefundSucceeded?: (payload: WebhookPayload) => Promise - onRefundFailed?: (payload: WebhookPayload) => Promise - onDisputeOpened?: (payload: WebhookPayload) => Promise - onDisputeExpired?: (payload: WebhookPayload) => Promise - onDisputeAccepted?: (payload: WebhookPayload) => Promise - onDisputeCancelled?: (payload: WebhookPayload) => Promise - onDisputeChallenged?: (payload: WebhookPayload) => Promise - onDisputeWon?: (payload: WebhookPayload) => Promise - onDisputeLost?: (payload: WebhookPayload) => Promise - onSubscriptionActive?: (payload: WebhookPayload) => Promise - onSubscriptionOnHold?: (payload: WebhookPayload) => Promise - onSubscriptionRenewed?: (payload: WebhookPayload) => Promise - onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise - onSubscriptionCancelled?: (payload: WebhookPayload) => Promise - onSubscriptionFailed?: (payload: WebhookPayload) => Promise - onSubscriptionExpired?: (payload: WebhookPayload) => Promise - onSubscriptionUpdated?: (payload: WebhookPayload) => Promise - onSubscriptionPaused?: (payload: WebhookPayload) => Promise - onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise - onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise - onLicenseKeyCreated?: (payload: WebhookPayload) => Promise - onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise - onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise - onDunningStarted?: (payload: WebhookPayload) => Promise - onDunningRecovered?: (payload: WebhookPayload) => Promise - onCreditAdded?: (payload: WebhookPayload) => Promise - onCreditDeducted?: (payload: WebhookPayload) => Promise - onCreditExpired?: (payload: WebhookPayload) => Promise - onCreditRolledOver?: (payload: WebhookPayload) => Promise - onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise - onCreditOverageCharged?: (payload: WebhookPayload) => Promise - onCreditOverageReset?: (payload: WebhookPayload) => Promise - onCreditManualAdjustment?: (payload: WebhookPayload) => Promise - onCreditBalanceLow?: (payload: WebhookPayload) => Promise - onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise - onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise - onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise - onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise - onPayoutCreated?: (payload: WebhookPayload) => Promise - onPayoutOnHold?: (payload: WebhookPayload) => Promise - onPayoutInProgress?: (payload: WebhookPayload) => Promise - onPayoutFailed?: (payload: WebhookPayload) => Promise - onPayoutSuccess?: (payload: WebhookPayload) => Promise Environment Variable Setup: To ensure the module functions correctly, set up the following environment variables in your Nuxt project's deployment environment (e.g., Vercel, Netlify, AWS, etc.). A built Nuxt server does not read the .env file, and Nuxt overrides runtime config values at runtime only from variables whose names match the config path: - NUXT_PRIVATE_BEARER_TOKEN: Your Dodo Payments API Key (required for Checkout and Customer Portal). - NUXT_PRIVATE_WEBHOOK_KEY: Your Dodo Payments Webhook Secret (required for Webhook handler). - NUXT_PRIVATE_ENVIRONMENT: (Optional) "test_mode" or "live_mode". Defaults to "live_mode". - NUXT_PRIVATE_RETURN_URL: (Optional) The URL to redirect to after a successful checkout (for Checkout handler). Usage in your code: bearerToken: useRuntimeConfig().private.bearerToken webhookKey: useRuntimeConfig().private.webhookKey Important: Never commit sensitive environment variables directly into your version control. Use environment variables for all sensitive information. If the user needs assistance setting up environment variables for their specific deployment environment, ask them what platform they are using (e.g., Vercel, Netlify, AWS, etc.), and provide guidance. ``` # Overlay Checkout Source: https://docs.dodopayments.com/developer-resources/overlay-checkout Open Dodo Payments checkout as a modal on your page. The overlay checkout SDK handles payment collection while your page remains visible behind it. Overlay checkout opens a modal window on top of your page. Customers enter their payment details in the modal while your page stays visible behind it. When they close the modal, control returns to your page. When they complete payment, they are redirected to your `return_url`. ![Overlay checkout modal displayed on top of a product page](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/cover-images/overlay-checkout.png?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=15d90c695e92914a9d54b10509d6fe47) > [card] [Interactive Demo](https://atlas.dodopayments.com/pricing) > > See the overlay checkout in action with our live demo. ## Quick Start Install the SDK, initialize it, and open checkout with a checkout URL from the [create checkout session API](/api-reference/checkout-sessions/create): ```typescript theme={null} import { DodoPayments } from "dodopayments-checkout"; DodoPayments.Initialize({ mode: "test", displayType: "overlay", onEvent: (event) => { console.log("Checkout event:", event); }, }); DodoPayments.Checkout.open({ checkoutUrl: "https://test.checkout.dodopayments.com/session/cks_123" }); ``` ## Step-by-Step Integration **1. Install the SDK** Install via npm, yarn, or pnpm: ```bash npm theme={null} npm install dodopayments-checkout ``` ```bash yarn theme={null} yarn add dodopayments-checkout ``` ```bash pnpm theme={null} pnpm add dodopayments-checkout ``` **2. Initialize the SDK** Call `Initialize` once when your app loads, typically in your main component or app entry point: ```typescript theme={null} import { DodoPayments } from "dodopayments-checkout"; DodoPayments.Initialize({ mode: "test", // Change to 'live' for production displayType: "overlay", onEvent: (event) => { console.log("Checkout event:", event); switch (event.event_type) { case "checkout.opened": // Modal has opened break; case "checkout.closed": // Modal has closed break; case "checkout.error": console.error("Checkout error:", event.data?.message); break; } }, }); ``` > [!WARNING] > > Always initialize the SDK before opening the checkout. Initialize it once when your application loads, not before every checkout attempt. **3. Create a Checkout Button** Build a component that opens the checkout modal: ```typescript theme={null} // components/CheckoutButton.tsx "use client"; import { Button } from "@/components/ui/button"; import { DodoPayments } from "dodopayments-checkout"; import { useEffect, useState } from "react"; export function CheckoutButton() { const [isLoading, setIsLoading] = useState(false); useEffect(() => { DodoPayments.Initialize({ mode: "test", displayType: "overlay", onEvent: (event) => { if (event.event_type === "checkout.opened") { setIsLoading(false); } if (event.event_type === "checkout.error") { setIsLoading(false); console.error("Checkout error:", event.data?.message); } }, }); }, []); const handleCheckout = async () => { setIsLoading(true); try { await DodoPayments.Checkout.open({ checkoutUrl: "https://test.checkout.dodopayments.com/session/cks_123" }); } catch (error) { console.error("Failed to open checkout:", error); setIsLoading(false); } }; return ( ); } ``` **4. Add the Button to Your Page** Use the checkout button component in your application: ```typescript theme={null} // app/page.tsx import { CheckoutButton } from "@/components/CheckoutButton"; export default function Home() { return (

Welcome to Our Store

); } ``` **5. Handle Redirects** Create pages to handle checkout redirects after payment: ```typescript theme={null} // app/success/page.tsx export default function SuccessPage() { return (

Payment Successful

Thank you for your purchase.

); } // app/failure/page.tsx export default function FailurePage() { return (

Payment Failed

Please try again or contact support.

); } ``` **6. Test Your Integration** 1. Start your development server: ```bash theme={null} npm run dev ``` 2. Test the checkout flow: * Click the checkout button * Verify the modal appears * Test the payment flow using test credentials * Confirm redirects work correctly > [!TIP] > > You should see checkout events logged in your browser console. **7. Go Live** When ready for production: 1. Change the mode to `'live'`: ```typescript theme={null} DodoPayments.Initialize({ mode: "live", displayType: "overlay", onEvent: (event) => { console.log("Checkout event:", event); } }); ``` 2. Update your checkout URLs to use live checkout sessions from your backend 3. Test the complete flow in production 4. Monitor events and errors ## API Reference ### Initialize Call `Initialize` once to set up the SDK: ```typescript theme={null} interface InitializeOptions { mode: "test" | "live"; displayType?: "overlay" | "inline"; onEvent: (event: CheckoutEvent) => void; } DodoPayments.Initialize(options); ``` | Option | Type | Required | Description | | - | - | - | - | | `mode` | `"test" \| "live"` | Yes | Environment mode: `"test"` for development, `"live"` for production | | `displayType` | `"overlay" \| "inline"` | No | Display type: `"overlay"` for modal checkout (default), `"inline"` for embedded checkout | | `onEvent` | `function` | Yes | Callback function for handling checkout events | ### Open Checkout Open the checkout modal: ```typescript theme={null} interface CheckoutOptions { checkoutUrl: string; options?: { showTimer?: boolean; showSecurityBadge?: boolean; manualRedirect?: boolean; payButtonText?: string; fontSize?: FontSize; fontWeight?: FontWeight; }; } DodoPayments.Checkout.open(options); ``` | Option | Type | Required | Description | | - | - | - | - | | `checkoutUrl` | `string` | Yes | Checkout session URL from the [create checkout session API](/api-reference/checkout-sessions/create) | | `options.showTimer` | `boolean` | No | Show or hide the session timer. Defaults to `true`. When disabled, you receive the `checkout.link_expired` event when the session expires. | | `options.showSecurityBadge` | `boolean` | No | Show or hide the security badge. Defaults to `true` | | `options.manualRedirect` | `boolean` | No | When `true`, prevent automatic redirects. Checkout emits `checkout.status` with the payment outcome and `checkout.redirect_requested` with the URL to open, and you handle navigation | | `options.payButtonText` | `string` | No | Custom text for the pay button | | `options.fontSize` | `"xs" \| "sm" \| "md" \| "lg" \| "xl" \| "2xl"` | No | Global font size for the checkout | | `options.fontWeight` | `"normal" \| "medium" \| "bold" \| "extraBold"` | No | Global font weight for the checkout | ### Close Checkout Programmatically close the modal: ```typescript theme={null} DodoPayments.Checkout.close(); ``` ### Check Status Check if the modal is currently open: ```typescript theme={null} const isOpen = DodoPayments.Checkout.isOpen(); // Returns: boolean ``` ### Events Listen for checkout events via the `onEvent` callback passed to `Initialize`: ```typescript theme={null} DodoPayments.Initialize({ onEvent: (event: CheckoutEvent) => { switch (event.event_type) { case "checkout.opened": // Modal has opened break; case "checkout.form_ready": // Form is ready for user input break; case "checkout.payment_page_opened": // Payment page is displayed break; case "checkout.customer_details_submitted": // Customer details submitted break; case "checkout.closed": // Modal has closed break; case "checkout.redirect": // Checkout will redirect break; case "checkout.error": console.error("Error:", event.data?.message); break; case "checkout.link_expired": // Session expired (only when showTimer is false) break; } } }); ``` | Event | Description | | - | - | | `checkout.opened` | Modal has opened | | `checkout.form_ready` | Form is ready for user input. Use this to hide loading states | | `checkout.payment_page_opened` | Payment page is displayed | | `checkout.customer_details_submitted` | Customer and billing details submitted | | `checkout.closed` | Modal has closed | | `checkout.redirect` | Checkout will redirect (e.g., to a bank page) | | `checkout.error` | An error occurred during checkout | | `checkout.link_expired` | The checkout session expired. Only received when `showTimer` is set to `false`. | | `checkout.payment_method_selected` | Customer picked or changed a payment method in [single page checkout](/features/single-page-checkout#embedded-checkout-events). `data.message.payment_method_type` holds the method, for example `card` or `upi_collect`. Requires SDK `2.1.1` or later. | ## CDN Implementation For quick integration without a build step, load the SDK from CDN: ```html theme={null} Dodo Payments Checkout ``` ## Theme Customization Configure the checkout theme when you create the checkout session, with the `customization.theme_config` parameter. See [Checkout Theme Customization](/features/checkout#theme-customization). You can also configure it visually on the [Design page](/features/design) in the dashboard. A theme set on the session applies to overlay, inline, and hosted checkout. > [!NOTE] > > Checkout SDK 2.0.1 removes the client-side `themeConfig` option. If you still pass `themeConfig` in `options`, the SDK ignores it. Move the theme to `customization.theme_config` on the checkout session. ## Error Handling Always implement error handling in your `onEvent` callback: ```typescript theme={null} DodoPayments.Initialize({ mode: "test", displayType: "overlay", onEvent: (event: CheckoutEvent) => { if (event.event_type === "checkout.error") { console.error("Checkout error:", event.data?.message); // Show user-friendly error message // Optionally retry the checkout } if (event.event_type === "checkout.link_expired") { console.warn("Checkout session has expired"); // Create a new checkout session and try again } } }); ``` > [!WARNING] > > Always handle the `checkout.error` event to provide a good user experience when errors occur. ## Best Practices 1. **Initialize once**: Call `Initialize` once when your app loads, not before every checkout 2. **Error handling**: Implement proper error handling in your event callback 3. **Test mode**: Use `"test"` mode during development and switch to `"live"` only when ready for production 4. **Event handling**: Handle all relevant events for a complete user experience 5. **Valid URLs**: Always use valid checkout URLs from the create checkout session API 6. **TypeScript**: Use TypeScript for better type safety and developer experience 7. **Loading states**: Show loading states while the checkout is opening to improve UX 8. **Timer management**: Disable the timer (`showTimer: false`) if you want to handle session expiration manually ## Troubleshooting > [accordion] Checkout modal not opening > > **Possible causes:** > > * SDK not initialized before calling `open()` > * Invalid checkout URL > * JavaScript errors in console > * Network connectivity issues > > **Solutions:** > > * Verify SDK initialization happens before opening checkout > * Check browser console for errors > * Ensure checkout URL is valid and from the create checkout session API > * Verify network connectivity > [accordion] Events not firing > > **Possible causes:** > > * Event handler not properly set up > * JavaScript errors preventing event propagation > * SDK not initialized correctly > > **Solutions:** > > * Confirm event handler is properly configured in `Initialize()` > * Check browser console for JavaScript errors > * Verify SDK initialization completed successfully > * Test with a simple event handler first > [accordion] Styling issues > > **Possible causes:** > > * CSS conflicts with your application styles > * Theme settings not applied correctly > * Responsive design issues > > **Solutions:** > > * Check for CSS conflicts in browser DevTools > * Verify theme settings are correct > * Test on different screen sizes > * Ensure no z-index conflicts with modal ## Digital Wallets For detailed information about setting up Google Pay and other digital wallets, see the [Digital Wallets](/features/payment-methods/digital-wallets) page. > [!NOTE] > > Apple Pay is not yet supported in overlay checkout. ## Browser Support The Dodo Payments Checkout SDK supports: * Chrome (latest) * Firefox (latest) * Safari (latest) * Edge (latest) * IE11+ ## Overlay vs Inline Checkout Choose the right checkout type for your use case: | Feature | Overlay | Inline | | - | - | - | | Integration depth | Modal on top of page | Fully embedded in page | | Layout control | Limited | Full control | | Branding | Separate from page | Matches your page | | Implementation effort | Lower | Higher | | Best for | Quick integration, existing pages | Custom checkout pages, high-conversion flows | > [!TIP] > > Use overlay checkout for faster integration with minimal changes to your existing pages. Use inline checkout when you want maximum control over the checkout experience and consistent branding. ## Related Resources > [card] [Inline Checkout](/developer-resources/inline-checkout) > > Embed checkout directly into your page for fully integrated experiences. > [card] [Checkout Sessions API](/api-reference/checkout-sessions/create) > > Create checkout sessions to power your checkout experiences. > [card] [Webhooks](/developer-resources/webhooks) > > Handle payment events server-side with webhooks. > [card] [Integration Guide](/developer-resources/integration-guide) > > Complete guide to integrating Dodo Payments. For more help, visit our [Discord community](https://discord.gg/bYqAp4ayYh) or contact our developer support team. # Remix Adaptor Source: https://docs.dodopayments.com/developer-resources/remix-adaptor Add Dodo Payments checkout, Customer Portal, and webhook handlers to Remix loaders and actions with the @dodopayments/remix package. The `@dodopayments/remix` package gives your Remix app three request handlers. `Checkout` returns checkout URLs, `CustomerPortal` sends a customer to the Customer Portal, and `Webhooks` verifies webhook events and routes them to your code. Each handler takes a `Request` and returns a `Response`, so you call it from a route's `loader` or `action`. > [card] [Checkout Handler](#checkout-route-handler) > > Create checkout URLs from your Remix app. > [card] [Customer Portal](#customer-portal-route-handler) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-route-handler) > > Receive and verify Dodo Payments webhook events. ## Installation **1. Install the Package** Run this command in your project root: ```bash theme={null} npm install @dodopayments/remix ``` The package lists Remix 2 (`remix` 2.16.8 or later) and `zod` 3.25 or later as peer dependencies. **2. Set Up Environment Variables** Create a `.env` file in your project root: ```env expandable theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_RETURN_URL=https://yourdomain.com/checkout/success # test_mode or live_mode DODO_PAYMENTS_ENVIRONMENT=test_mode ``` Create the API key under **Developer → API Keys**. Add your webhook endpoint under **Developer → Webhooks** and copy its signing secret into `DODO_PAYMENTS_WEBHOOK_KEY`. `DODO_PAYMENTS_RETURN_URL` is where customers land after checkout. If you don't pass an environment, the handlers use `live_mode`. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## Route Handler Examples > [!NOTE] > > The examples are Remix resource routes, which export a `loader` for GET requests or an `action` for POST requests and no component. With flat file routes, `app/routes/api.checkout.tsx` serves `/api/checkout`. > [tab] Checkout Handler > > > [!NOTE] > > > > Use this handler to add Dodo Payments checkout to your Remix app. The `loader` serves static checkout. The `action` serves checkout sessions. > > ```typescript Remix Route Handler expandable theme={null} > // app/routes/api.checkout.tsx > import { Checkout } from "@dodopayments/remix"; > import type { LoaderFunctionArgs } from "@remix-run/node"; > > const checkoutGetHandler = Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > type: "static" > }); > > const checkoutSessionHandler = Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > type: "session", // for checkout sessions > }); > > export const loader = ({ request }: LoaderFunctionArgs) => checkoutGetHandler(request); > export const action = ({ request }: LoaderFunctionArgs) => checkoutSessionHandler(request); > ``` > > ```bash Static Checkout cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/checkout?productId=pdt_fqJhl7pxKWiLhwQR042rh' > ``` > > ```bash Checkout Session cURL Example expandable theme={null} > curl --request POST \ > --url https://example.com/api/checkout \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_QMDuvLkbVzCRWRQjLNcs", > "quantity": 1 > } > ], > "customer": { > "email": "customer@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal Handler > > > [!NOTE] > > > > Use this handler to send customers to the Dodo Payments Customer Portal, where they manage their subscriptions and details. > > ```typescript Remix Route Handler expandable theme={null} > // app/routes/api.customer-portal.tsx > import { CustomerPortal } from "@dodopayments/remix"; > import type { LoaderFunctionArgs } from "@remix-run/node"; > > const customerPortalHandler = CustomerPortal({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode" > }); > > export const loader = ({ request }: LoaderFunctionArgs) => customerPortalHandler(request); > ``` > > ```bash Customer Portal cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/customer-portal?customer_id=cus_9VuW4K7O3GHwasENg31m&send_email=true' > ``` > [tab] Webhook Handler > > > [!NOTE] > > > > Use this handler to receive Dodo Payments webhook events in your Remix app and verify their signatures. > > ```typescript Remix Route Handler expandable theme={null} > // app/routes/api.webhook.tsx > import { Webhooks } from "@dodopayments/remix"; > import type { LoaderFunctionArgs } from "@remix-run/node"; > > const webhookHandler = Webhooks({ > webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, > onPayload: async (payload) => { > //Handle Payload Here > console.log(payload) > } > }); > export const action = ({ request }: LoaderFunctionArgs) => webhookHandler(request); > ``` ## Checkout Route Handler The checkout handler supports all three ways to take payments with Dodo Payments: * **Static Payment Links:** Shareable URLs that collect payments without code. * **Dynamic Payment Links (deprecated):** Payment links you generate with custom details. They use deprecated endpoints. * **Checkout Sessions:** Hosted checkout with a product cart, customer details, and customization options. This is the recommended flow. `Checkout` takes these options: | Option | Type | Description | | - | - | - | | `bearerToken` | `string` | Your Dodo Payments API key. | | `environment` | `string` | `test_mode` or `live_mode`. Defaults to `live_mode`. | | `returnUrl` | `string` | Optional. The URL that checkout redirects the customer to after payment. A `return_url` in a POST body takes precedence. | | `type` | `string` | Optional. `static` (the default) for the handler your `loader` calls. For POST requests, `dynamic` selects dynamic checkout, and any other value, or none, selects checkout sessions. | > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_nZuwz45WAs64n3l07zpQR`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's address line. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's ZIP or postal code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > Payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed as metadata. > > The handler adds `returnUrl` from its config to the link as `redirect_url`. > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters and product IDs that don't exist also return 400. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL. In test mode, the URL uses `test.checkout.dodopayments.com`. > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/..." > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send the parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. > * `billing` and `customer` are required. > * For every supported body field, see: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic checkout proxies the deprecated `POST /payments` and `POST /subscriptions` endpoints. It keeps working for existing integrations, but new integrations should use checkout sessions. > > ### Response Format > > Dynamic checkout returns a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/..." > } > ``` > [accordion] Checkout Sessions (POST) > > Checkout sessions create a hosted checkout for one-time purchases and subscriptions, with full control over customization. `product_cart` is the only required field, and it needs at least one product. If the body has no `return_url`, the handler uses `returnUrl` from its config. > > For more details and every supported field, see the [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session). > > A session created with `payment_method_id` returns no checkout URL, so the handler responds with 400. To charge a saved payment method, create the session with the SDK instead. > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/session/..." > } > ``` ## Customer Portal Route Handler The Customer Portal route handler creates a Customer Portal session for the customer you pass and redirects the browser to it with a 307 response. > [!WARNING] > > The handler doesn't check who is calling it. Anyone who requests it with a customer ID gets that customer's portal. Protect the route with your own authentication, and pass only the signed-in user's customer ID. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, Dodo Payments also emails the portal link to the customer. > [!WARNING] > > Returns 400 if `customer_id` is missing, and 500 if the portal session can't be created. ## Webhook Route Handler The webhook route handler verifies each request before it runs your code: * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the raw request body and the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`, following the [Standard Webhooks](https://standardwebhooks.com/) specification. Returns 401 if verification fails. * **Payload Validation:** Validates the payload with Zod. Returns 400 for an invalid payload. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Internal error during verification * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200. The adaptor doesn't catch errors thrown in your handlers. They propagate to Remix, and the request fails. ### Supported Webhook Event Handlers Each handler receives the verified payload for its event type: ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` For what each event means, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). *** ## Prompt for LLM Copy this prompt into your AI coding assistant to have it add the adaptor to your project. To give your agent the Dodo Payments docs and skills as well, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ```text expandable theme={null} You are an expert Remix developer assistant. Your task is to guide a user through integrating the @dodopayments/remix adapter into their existing Remix project. The @dodopayments/remix adapter provides route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed for Remix route handlers. First, install the necessary packages. Use the package manager appropriate for your project (npm, yarn, or bun) based on the presence of lock files (e.g., package-lock.json for npm, yarn.lock for yarn, bun.lockb for bun): npm install @dodopayments/remix Here's how you should structure your response: Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/remix adapter would you like to integrate into your project? You can choose one or more of the following: Checkout Route Handler (for handling product checkouts) Customer Portal Route Handler (for managing customer subscriptions/details) Webhook Route Handler (for receiving Dodo Payments webhook events) All (integrate all three)" Based on the user's selection, provide detailed integration steps for each chosen functionality. If Checkout Route Handler is selected: Purpose: This handler returns a JSON response with a checkout_url for the Dodo Payments checkout page. The loader serves static checkout (GET). The action serves checkout sessions (POST). File Creation: Create a new file at app/routes/api.checkout.tsx in your Remix project. Code Snippet: // app/routes/api.checkout.tsx import { Checkout } from "@dodopayments/remix"; import type { LoaderFunctionArgs } from "@remix-run/node"; const checkoutGetHandler = Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", type: "static", }); const checkoutSessionHandler = Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", type: "session", // for checkout sessions }); export const loader = ({ request }: LoaderFunctionArgs) => checkoutGetHandler(request); export const action = ({ request }: LoaderFunctionArgs) => checkoutSessionHandler(request); If Customer Portal Route Handler is selected: Purpose: This handler redirects a customer to their Dodo Payments customer portal. It does not authenticate the caller, so protect the route and pass only the signed-in user's customer ID. File Creation: Create a new file at app/routes/api.customer-portal.tsx in your Remix project. Code Snippet: // app/routes/api.customer-portal.tsx import { CustomerPortal } from "@dodopayments/remix"; import type { LoaderFunctionArgs } from "@remix-run/node"; const customerPortalHandler = CustomerPortal({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode" }); export const loader = ({ request }: LoaderFunctionArgs) => customerPortalHandler(request); Query Parameters: customer_id (required): The customer ID for the portal session (e.g., ?customer_id=cus_123) send_email (optional, boolean): If set to true, sends an email to the customer with the portal link. Returns 400 if customer_id is missing. If Webhook Route Handler is selected: Purpose: This handler processes incoming webhook events from Dodo Payments, allowing your application to react to events like successful payments, refunds, or subscription changes. File Creation: Create a new file at app/routes/api.webhook.tsx in your Remix project. Code Snippet: // app/routes/api.webhook.tsx import { Webhooks } from "@dodopayments/remix"; import type { LoaderFunctionArgs } from "@remix-run/node"; const webhookHandler = Webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, onPayload: async (payload) => { //Handle Payload Here console.log(payload) } }); export const action = ({ request }: LoaderFunctionArgs) => webhookHandler(request); Handler Details: Method: Only POST requests are supported. Other methods return 405. Signature Verification: The handler verifies the webhook signature using the webhookKey and returns 401 if verification fails. Payload Validation: The payload is validated with Zod. Returns 400 for invalid payloads. Error Handling: 401: Invalid signature 400: Invalid payload 500: Internal error during verification Event Routing: Calls onPayload for every event, then the handler for the event's type. Supported Webhook Event Handlers: onPayload?: (payload: WebhookPayload) => Promise onPaymentSucceeded?: (payload: WebhookPayload) => Promise onPaymentFailed?: (payload: WebhookPayload) => Promise onPaymentProcessing?: (payload: WebhookPayload) => Promise onPaymentCancelled?: (payload: WebhookPayload) => Promise onRefundSucceeded?: (payload: WebhookPayload) => Promise onRefundFailed?: (payload: WebhookPayload) => Promise onDisputeOpened?: (payload: WebhookPayload) => Promise onDisputeExpired?: (payload: WebhookPayload) => Promise onDisputeAccepted?: (payload: WebhookPayload) => Promise onDisputeCancelled?: (payload: WebhookPayload) => Promise onDisputeChallenged?: (payload: WebhookPayload) => Promise onDisputeWon?: (payload: WebhookPayload) => Promise onDisputeLost?: (payload: WebhookPayload) => Promise onSubscriptionActive?: (payload: WebhookPayload) => Promise onSubscriptionOnHold?: (payload: WebhookPayload) => Promise onSubscriptionRenewed?: (payload: WebhookPayload) => Promise onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise onSubscriptionCancelled?: (payload: WebhookPayload) => Promise onSubscriptionFailed?: (payload: WebhookPayload) => Promise onSubscriptionExpired?: (payload: WebhookPayload) => Promise onSubscriptionUpdated?: (payload: WebhookPayload) => Promise onSubscriptionPaused?: (payload: WebhookPayload) => Promise onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise onLicenseKeyCreated?: (payload: WebhookPayload) => Promise onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise onDunningStarted?: (payload: WebhookPayload) => Promise onDunningRecovered?: (payload: WebhookPayload) => Promise onCreditAdded?: (payload: WebhookPayload) => Promise onCreditDeducted?: (payload: WebhookPayload) => Promise onCreditExpired?: (payload: WebhookPayload) => Promise onCreditRolledOver?: (payload: WebhookPayload) => Promise onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise onCreditOverageCharged?: (payload: WebhookPayload) => Promise onCreditOverageReset?: (payload: WebhookPayload) => Promise onCreditManualAdjustment?: (payload: WebhookPayload) => Promise onCreditBalanceLow?: (payload: WebhookPayload) => Promise onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise onPayoutCreated?: (payload: WebhookPayload) => Promise onPayoutOnHold?: (payload: WebhookPayload) => Promise onPayoutInProgress?: (payload: WebhookPayload) => Promise onPayoutFailed?: (payload: WebhookPayload) => Promise onPayoutSuccess?: (payload: WebhookPayload) => Promise Environment Variable Setup: To ensure the adapter functions correctly, you will need to manually set up the following environment variables in your Remix project's deployment environment (e.g., Vercel, Netlify, AWS, etc.): DODO_PAYMENTS_API_KEY: Your Dodo Payments API Key (required for Checkout and Customer Portal). DODO_PAYMENTS_RETURN_URL: (Optional) The URL to redirect to after a successful checkout (for Checkout handler). DODO_PAYMENTS_ENVIRONMENT: (Optional) "test_mode" or "live_mode". Defaults to "live_mode". DODO_PAYMENTS_WEBHOOK_KEY: Your Dodo Payments Webhook Secret (required for Webhook handler). Example .env file: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_RETURN_URL=your-return-url DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret Usage in your code: bearerToken: process.env.DODO_PAYMENTS_API_KEY webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY! Important: Never commit sensitive environment variables directly into your version control. Use environment variables for all sensitive information. If the user needs assistance setting up environment variables for their specific deployment environment, ask them what platform they are using (e.g., Vercel, Netlify, AWS, etc.), and provide guidance. You can also add comments to their PR or chat depending on the context ``` # Android Source: https://docs.dodopayments.com/developer-resources/sdks/android Open Dodo Payments hosted checkout from an Android app in a Custom Tab with the official Android SDK, and get a typed checkout result back from one call. > [!NOTE] > > This page covers the Android checkout SDK, `com.dodopayments.api:checkout-android`, which opens Dodo Payments hosted checkout inside your app. To call the Dodo Payments API from your server, use the [backend Kotlin SDK](/developer-resources/sdks/kotlin) instead. > [card] [Checkout Sessions API](/developer-resources/checkout-session) > > Create the `checkout_url` that this SDK opens. > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > Best practices for mobile checkout flows. The Android SDK opens Dodo Payments hosted checkout in a Custom Tab (`androidx.browser.customtabs`) and returns a typed `CheckoutResult` when the customer finishes or leaves checkout. Your backend creates the checkout session and sends its `checkout_url` to the app. The SDK contains no networking code and holds no API key, so it never calls the Dodo Payments API. **Requirements:** `minSdk` 23, Kotlin, and Java 17. The SDK depends only on `androidx.activity`, `androidx.browser`, and `kotlinx-coroutines-android`. ## Installation **1. Add the Dependency** Add the SDK from Maven Central to your app module's `build.gradle.kts`: ```kotlin build.gradle.kts theme={null} dependencies { implementation("com.dodopayments.api:checkout-android:1.1.0") } ``` [Appearance customization](#appearance-customization) requires version 1.1.0 or later. **2. Register a Callback URL Scheme** Set your callback scheme as a Gradle manifest placeholder. The SDK's own manifest declares the redirect activity's intent filter with the `${dodoCallbackScheme}` placeholder, so this property is the only setup step. You don't add any manifest XML: ```kotlin build.gradle.kts theme={null} android { defaultConfig { manifestPlaceholders["dodoCallbackScheme"] = "myapp" } } ``` Use the same scheme in `CheckoutParams.returnUrl`, for example `myapp://checkout/return`, and set the same URL as the checkout session's `return_url` when your backend creates the session. The SDK matches the return URL on scheme, host, and path, and ignores the query string. The URL doesn't need to load a real page. > [!NOTE] > > If you omit the placeholder, the build fails with an unresolved-placeholder error. If the placeholder doesn't match the scheme of `returnUrl`, the SDK throws `PLATFORM_ERROR` before it opens checkout. ## Usage The SDK has two ways to start checkout: an activity result launcher and a suspend function. Both return the same `CheckoutResult`. > [tab] Launcher (Recommended) > > Register the contract with `registerForActivityResult`, then launch it: > > ```kotlin theme={null} > import com.dodopayments.checkout.CheckoutParams > import com.dodopayments.checkout.CheckoutStatus > import com.dodopayments.checkout.DodoCheckout > > // showSuccess(), showFailure(), showExpired(), and reconcileAbandonedSession() > // are your own functions. See Abandoned Sessions for what to reconcile. > private val checkoutLauncher = > registerForActivityResult(DodoCheckout.contract()) { result -> > when (result.status) { > CheckoutStatus.SUCCEEDED -> showSuccess(result.paymentId) > CheckoutStatus.FAILED -> showFailure() > CheckoutStatus.CANCELLED -> reconcileAbandonedSession() // outcome unknown, not a failure > CheckoutStatus.PENDING -> reconcileAbandonedSession() > CheckoutStatus.EXPIRED -> showExpired() > } > } > > checkoutLauncher.launch( > CheckoutParams( > checkoutUrl = checkoutUrl, // from your backend's checkout session > returnUrl = "myapp://checkout/return" > ) > ) > ``` > > > [!TIP] > > > > Use this style when you can. Android delivers the result through its `ActivityResultRegistry`, so the result survives process death. > [tab] Suspend Function > > Call `DodoCheckout.start` from a coroutine scope: > > ```kotlin theme={null} > import androidx.lifecycle.lifecycleScope > import com.dodopayments.checkout.CheckoutParams > import com.dodopayments.checkout.CheckoutStatus > import com.dodopayments.checkout.DodoCheckout > import kotlinx.coroutines.launch > > // showSuccess(), showFailure(), showExpired(), and reconcileAbandonedSession() > // are your own functions. See Abandoned Sessions for what to reconcile. > lifecycleScope.launch { > val result = DodoCheckout.start( > activity = this@MyActivity, > params = CheckoutParams( > checkoutUrl = checkoutUrl, // from your backend's checkout session > returnUrl = "myapp://checkout/return" > ), > onEvent = { event -> println(event.name) } // logging only > ) > > when (result.status) { > CheckoutStatus.SUCCEEDED -> showSuccess(result.paymentId) > CheckoutStatus.FAILED -> showFailure() > CheckoutStatus.CANCELLED -> reconcileAbandonedSession() // outcome unknown, not a failure > CheckoutStatus.PENDING -> reconcileAbandonedSession() > CheckoutStatus.EXPIRED -> showExpired() > } > } > ``` > > `onEvent` receives `checkout.opened`, `checkout.return_received`, and `checkout.closed` events. Use them for logging only, never to decide the outcome. > > > [!WARNING] > > > > This style waits on an in-memory `CompletableDeferred`, so the result does **not** survive process death. `onEvent` is available only in this style, not with the launcher. ## What the Result Means The SDK builds `CheckoutResult` from the query parameters on the return URL. > [!WARNING] > > The `status` field is a UI hint, not proof of payment. Before you grant access, confirm the payment on your backend with a webhook or the Get Payment Detail endpoint. **status** `CheckoutStatus` *required* One of five values: * `SUCCEEDED`: the return URL has `status=succeeded` (one-time payment) or `status=active` (subscription). * `FAILED`: the payment was declined (`status=failed`). * `CANCELLED`: the customer closed the Custom Tab before the return URL arrived. The SDK doesn't know the outcome, and the payment may have succeeded, so don't show a failure screen. Reconcile the [abandoned session](#abandoned-sessions) instead. * `PENDING`: the payment settles later (`status=processing` or any `requires_*` value), or the `status` parameter was missing or unrecognized. Reconcile it like `CANCELLED`. * `EXPIRED`: the checkout session expired (`status=expired`). **paymentId** `String?` The `payment_id` query parameter, when the return URL includes one. Show it in your UI, but don't use it to grant access. See [Verify the Payment](#verify-the-payment). **subscriptionId** `String?` The `subscription_id` query parameter. Set for subscription checkouts. **licenseKeys** `List\?` The `license_key` query parameter. Set when the checkout includes license key products. **customerEmail** `String?` The `email` query parameter. Set when checkout captures an email address. **raw** `Map\` Every query parameter from the return URL, verbatim. ## Verify the Payment > [card] [Webhooks](/developer-resources/webhooks) > > Listen for payment events in real time. > [card] [Get Payment Detail](/api-reference/payments/get-payments-1) > > Query the payment status on demand. Grant access only after one of these confirms the payment, for example with the `payment.succeeded` or `subscription.active` webhook. Don't rely on `CheckoutResult.status` alone. ## Appearance Customization To change the Custom Tab's toolbar, buttons, and color scheme, pass a `BrowserCustomization` as `customization` on `CheckoutParams`. Every field is optional and defaults to `null`. For a `null` field, the SDK doesn't set that option, so the browser that hosts the Custom Tab applies its own default. **toolbarColor** `Int?` Toolbar background color, as an ARGB `Color` int. **navigationBarColor** `Int?` Navigation bar color, as an ARGB `Color` int. **navigationBarDividerColor** `Int?` Color of the divider above the navigation bar, as an ARGB `Color` int. **closeButtonStyle** `CloseButtonStyle?` `DEFAULT` shows the system "X" icon. `BACK` shows a back arrow that the SDK draws. **closeButtonPosition** `CloseButtonPosition?` The side of the toolbar where the close button appears: `START` or `END`. **shareButtonEnabled** `Boolean?` Shows the toolbar's share icon. `false` hides it. **showTitleEnabled** `Boolean?` Shows the page title under the URL in the toolbar. **urlBarHidingEnabled** `Boolean?` Hides the toolbar automatically as the page scrolls. **bookmarksButtonEnabled** `Boolean?` Shows "Bookmark this page" in the overflow menu. **downloadsButtonEnabled** `Boolean?` Shows "Download page" in the overflow menu. **colorScheme** `ColorScheme?` `LIGHT` or `DARK` forces that appearance regardless of the device's system setting. `SYSTEM` follows the system setting. This example reuses `checkoutLauncher` from [Usage](#usage): ```kotlin theme={null} import android.graphics.Color import com.dodopayments.checkout.BrowserCustomization import com.dodopayments.checkout.CheckoutParams checkoutLauncher.launch( CheckoutParams( checkoutUrl = checkoutUrl, returnUrl = "myapp://checkout/return", customization = BrowserCustomization( toolbarColor = Color.parseColor("#6366F1"), closeButtonStyle = BrowserCustomization.CloseButtonStyle.BACK, colorScheme = BrowserCustomization.ColorScheme.DARK, ) ) ) ``` ## Errors `DodoCheckout.start` throws `CheckoutError` only for misuse or a platform failure. Read the reason from `CheckoutError.code`: * `INVALID_CHECKOUT_URL`: `checkoutUrl` isn't an `https` checkout session URL (path starting with `/session/`) on `checkout.dodopayments.com` or `test.checkout.dodopayments.com`. * `INVALID_RETURN_URL`: `returnUrl` isn't an absolute URL with a scheme and a host. * `ALREADY_IN_PROGRESS`: another checkout is running. Only one checkout can run at a time. * `PLATFORM_ERROR`: an unexpected platform failure, including a `returnUrl` scheme that doesn't match your `dodoCallbackScheme` placeholder. A customer who cancels, or a declined payment, is always a result (`CANCELLED` or `FAILED`), never a thrown error. With the launcher, validation errors throw from `launcher.launch(...)`. A platform failure after the launch can't be thrown through the activity result callback, so the launcher returns `CANCELLED` with the error code in `raw["error"]`. ## Abandoned Sessions The SDK records the checkout session when checkout starts, and clears the record only when checkout ends with `SUCCEEDED`, `FAILED`, or `EXPIRED`. The record stays when the app is killed during checkout, and after a `CANCELLED` or `PENDING` result, because in those cases the SDK doesn't know the outcome. Check for it on the next app launch and after every `CANCELLED` or `PENDING` result: ```kotlin theme={null} // context is any Context, such as your Activity. DodoCheckout.getAbandonedSession(context)?.let { abandoned -> // Ask your backend for the outcome of abandoned.sessionId, and show it. // Clear the record only after the outcome is final: DodoCheckout.clearAbandonedSession(context) } ``` `abandoned.sessionId` is the checkout session ID, which starts with `cks_`. `abandoned.createdAt` is the time checkout started, as an epoch timestamp in milliseconds. Your backend can look up the session with [Get Checkout Session](/api-reference/checkout-sessions/get-checkouts), which returns its `payment_id` and `payment_status`. Until the payment reaches a final status, treat it as pending, not failed. ## Related > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > Best practices for mobile checkout flows. > [card] [Kotlin SDK](/developer-resources/sdks/kotlin) > > Backend SDK for server-side operations. # Dodo CLI Source: https://docs.dodopayments.com/developer-resources/sdks/cli Manage Dodo Payments resources, query your account with an AI assistant, create checkout sessions, and test webhooks from your terminal with the Dodo CLI. The Dodo CLI manages your Dodo Payments resources, answers questions about your account with a built-in AI assistant, creates checkout sessions, and tests webhooks, all from your terminal. Use its interactive TUI, or run direct subcommands from scripts. [Dodo CLI | Dodo Payments](https://www.youtube.com/embed/gwtvQsANbW4) ## Features * **Interactive TUI**: Run `dodo` with no arguments to open the interactive interface, with a command palette, history, and live notifications. * **Built-in AI assistant**: Ask questions or take actions in plain English with `/ai`. The assistant runs `dodopayments-mcp` locally and needs no extra setup. * **Browser sign-in**: Run `dodo login` to sign in with your Dodo Payments account through OAuth. No API key needed. * **Encrypted credentials**: Credentials are stored in `~/.dodopayments/config.json`, encrypted with AES-256-GCM and a key derived from your machine. No plaintext credentials are stored on disk. * **Auto update**: The CLI checks for new versions on startup and notifies you in the TUI. For npm and Bun installs, run `/update` to upgrade in place. * **Webhook tooling**: Forward test mode webhooks to your local server, or send mock webhook payloads offline. * **Scaffolding**: Add billing routes to Next.js, Express, and Better Auth projects with `dodo init`. ## Installation On macOS or Linux, install the latest release binary with the install script: ```bash theme={null} curl -fsSL https://dodopayments.com/install.sh | sh ``` The script verifies the binary against the release's SHA-256 checksums. It installs `dodo` into the first writable directory among `/usr/local/bin`, `~/.local/bin`, and `~/bin`, or into `~/.local/bin` if none of them is writable. To install a specific release, set the `DODO_VERSION` environment variable to its tag. To choose the directory, set `DODO_INSTALL_DIR`. ### Install with NPM or Bun If you have Node.js or Bun, install the `dodopayments-cli` package globally. Package manager installs pull the latest published version: ```bash npm theme={null} npm install -g dodopayments-cli ``` ```bash Bun theme={null} bun install -g dodopayments-cli ``` > [!NOTE] > > Direct subcommands such as `dodo login` run on Node.js 18 or later. When you install through a package manager, the interactive TUI also needs Bun. Release binaries need neither runtime. ### Manual Installation (No Node / Bun Required) To install without running a remote script, download the binary yourself. **1. Download the Binary** Download the binary for your platform from the latest [GitHub Release](https://github.com/dodopayments/dodopayments-cli/releases). | Platform | Binary | | - | - | | macOS (Apple Silicon) | `dodo-cli-darwin-arm64` | | macOS (Intel) | `dodo-cli-darwin-x64` | | Linux (x86\_64) | `dodo-cli-linux-x64` | | Linux (arm64) | `dodo-cli-linux-arm64` | | Windows (x86\_64) | `dodo-cli-windows-x64.exe` | **2. Rename the Binary to `dodo`** ```bash Linux / macOS theme={null} mv ./dodo-cli-* ./dodo && chmod +x ./dodo ``` ```powershell Windows theme={null} ren .\dodo-cli-windows-x64.exe .\dodo.exe ``` **3. Move It to a Directory on Your PATH** > [!NOTE] > > On Windows, moving the file to `C:\Windows\System32` requires administrator privileges. ```bash Linux / macOS theme={null} sudo mv ./dodo /usr/local/bin/ ``` ```powershell Windows theme={null} move .\dodo.exe C:\Windows\System32\dodo.exe ``` **4. (Optional) Verify the Download** Each release publishes a `SHA256SUMS.txt` file. Download it next to the binary, then verify the binary: ```bash theme={null} shasum -a 256 -c SHA256SUMS.txt ``` ## Authentication Sign in with your Dodo Payments account. Browser sign-in requires v3.7.0 or later. Check your version with `dodo --version`. ```bash theme={null} npm install -g dodopayments-cli dodo login ``` `dodo login` opens your browser at the Dodo Payments consent page. Choose the business, the mode (test or live), and the permissions, then approve. Your [team role](/features/team) caps the permissions you can grant. Each sign-in holds one mode. To add the other mode, run `dodo login` again and choose it. The CLI keeps one browser sign-in for each mode, so you can be signed in to test mode and live mode at the same time. ![Dodo CLI consent page: Choose a Mode, with one choice of Live Mode or Test Mode](https://mintcdn.com/dodopayments/KtfSqp9QC-l5YuUH/images/mcp/oauth-consent-mode.png?fit=max\&auto=format\&n=KtfSqp9QC-l5YuUH\&q=85\&s=fe3edbe02860a1c4583884a1f191061a) ### Sign In Without a Browser Over SSH, or on a machine without a browser, the CLI shows a code instead. To force this flow, run: ```bash theme={null} dodo login --device ``` The CLI prints a code and a link. Open the link on any device with a browser. The Dodo Payments dashboard asks for the code: ![Connect the Dodo CLI page in the dashboard, with a code input in the XXXX-XXXX format and a Continue button](https://mintcdn.com/dodopayments/qcWXQ3CCdewP7gKI/images/mcp/cli-device-code.png?fit=max\&auto=format\&n=qcWXQ3CCdewP7gKI\&q=85\&s=112d72328e58c3bb28b6bc849bdeff76) Type the code and click **Continue**. The link that the CLI prints with `?user_code=` fills in the code for you. The consent page then starts with a **Confirm the code** step. It shows the code, the device name, the CLI version, the IP address, and the time of the request. Make sure that the code is the same as the code in your terminal. ![Consent page, step 1 of 5: Confirm the code, with the code, the device, the CLI version, the IP address, the request time, and a warning](https://mintcdn.com/dodopayments/qcWXQ3CCdewP7gKI/images/mcp/oauth-consent-device.png?fit=max\&auto=format\&n=qcWXQ3CCdewP7gKI\&q=85\&s=0b4d9e11683b618d616a1bb273aab195) > [!WARNING] > > Continue only if you ran `dodo login` yourself, just now. If somebody sent you a code or a link, click **Cancel**. Then choose the business, the mode, and the permissions, and approve. The CLI completes the sign-in when you approve, and the page shows **The CLI is connected**. ### Check and End Your Session ```bash Show the signed-in account theme={null} dodo whoami ``` ```bash Sign out everywhere theme={null} dodo logout all ``` `dodo whoami` shows one block for each signed-in mode and marks the active mode. It also shows the device name of each sign-in. The device name is the session name in Connected Apps. If the CLI can't read a stored sign-in, for example after the host name of a container changed, `dodo whoami` and other commands say so and give the file path. Run `dodo login` again, and revoke the old session in **Settings → Connected Apps**. `dodo logout all` also revokes the sign-in on the server. The refresh token is revoked and no new tokens are issued. An access token already issued stops working within about a minute. You can also revoke CLI sessions from **Settings → Connected Apps** in the dashboard. See [Connected Apps](/features/connected-apps). ### Log In with an API Key API key login still works. Pass the key and its mode, `test` or `live`: ```bash theme={null} dodo login "$DODO_PAYMENTS_API_KEY" test ``` Or, from inside the interactive TUI, run `/login`. The TUI opens the **Developer → API Keys** page, asks you to paste your key, and asks you to choose **Test Mode** or **Live Mode**. The CLI verifies the key with a request to the API, then stores it encrypted in `~/.dodopayments/config.json`. > [!NOTE] > > The encryption key is derived from your machine, so the stored credentials work only on that machine. If you upgrade from v3.0.x, which stored keys in the OS keychain, run `dodo login` again. Keys in the older plaintext `~/.dodopayments/api-key` file are migrated automatically, and that file is deleted. ### CI and Scripts When the `DODO_PAYMENTS_API_KEY` environment variable is set, the CLI uses it and ignores any stored sign-in. Use this in CI, where no browser is available. The CLI stores its sign-ins in `~/.dodopayments`. To use another directory, set `DODO_CONFIG_DIR`. Without a terminal, `dodo login` exits with code `1`. ### Switching Modes and Logging Out You can keep one sign-in for test mode and one for live mode at the same time, with browser sign-in or with API keys. A new browser sign-in for a mode replaces the earlier sign-in for that mode and revokes it on the server. A sign-in for the other mode keeps the first one. To switch the active mode in the TUI, run `/switch`. To remove stored credentials: ```bash Direct theme={null} dodo logout all ``` ```text TUI theme={null} /logout ``` In direct mode, pass `test`, `live`, or `all`. `dodo logout test` and `dodo logout live` also revoke the browser sign-in of that mode on the server. In the TUI, `/logout` asks you to choose **All accounts** or one of the modes you are signed in to, then asks you to confirm. ## Usage You can use the CLI in two modes. ### 1. Interactive TUI (Recommended) Run `dodo` with no arguments to open the interactive interface: ```bash theme={null} dodo ``` Type `/` to open the command palette. Text that doesn't start with `/` goes to the AI assistant. | Command | Description | | - | - | | `/help` | Show the command reference | | `/update` | Check for and install a CLI update | | `/login` | Authenticate with an API key | | `/logout` | Sign out of one or all environments | | `/switch` | Switch between test mode and live mode | | `/clear` | Clear the TUI screen | | `/exit` | Exit the TUI (also: type `exit`, or press `Esc` twice) | ### 2. Direct Subcommands Run a command without opening the TUI: ```bash theme={null} dodo [args...] ``` For example: ```bash theme={null} dodo payments list 1 dodo customers list 1 dodo wh trigger payment.success http://localhost:3000/webhook ``` The reference tables below list every command in direct-mode form. In the TUI, replace `dodo ` with `/`, for example `/payments list 1`. Commands marked **TUI only** are interactive wizards. In direct mode, they print a message that tells you to open the TUI. ## AI Assistant Ask questions about your account or take actions in plain English. The assistant runs `dodopayments-mcp` on your machine, so it needs no extra setup or OAuth flow. It calls the Dodo Payments API from your machine with your stored key and sends your prompts to the language model. | Command | Description | | - | - | | `/ai ` | Ask the AI assistant a question or give it an instruction | | *(any non-slash text)* | Sent to the AI assistant by default while in the TUI | In direct mode, run `dodo ai` followed by your question. Examples in the TUI: ```text theme={null} how much revenue did I make this week? /ai create a new customer named Acme Inc. /ai find my last failed payment ``` > [!TIP] > > The assistant uses your active mode (test mode or live mode) and works only with that mode's data. ## Project Scaffolding `dodo init` adds Dodo Payments billing routes to an existing project. It writes the route files, installs the matching `@dodopayments/*` adapter package, and appends any missing `DODO_PAYMENTS_*` variables to your `.env` file with placeholder values. It skips files and variables that already exist, and it runs **without logging in**. ```bash theme={null} dodo init ``` | Scaffold | Description | | - | - | | `dodo init nextjs` | Scaffold Next.js App Router billing routes (checkout, customer portal, and webhook handlers) using `@dodopayments/nextjs` | | `dodo init express` | Scaffold Express server billing routes using `@dodopayments/express` | | `dodo init better-auth` | Scaffold a Better-Auth plugin configuration using `@dodopayments/better-auth` | For the Better-Auth scaffold, you can pass a comma-separated list of plugins to generate: `checkout`, `portal`, `usage`, and `webhooks`. Without a list, it generates all four. ```bash theme={null} # Scaffold every Better-Auth plugin (default) dodo init better-auth # Scaffold only specific plugins dodo init better-auth checkout,portal ``` > [!NOTE] > > If your project has a `src/` directory, the scaffolder writes files inside it. It picks the install command from your project's lock file (`bun`, `pnpm`, or `yarn`) and uses `npm` when it finds none. ## Command Reference These commands need a logged-in API key. List commands take an optional page number, which defaults to 1, and show up to 100 items per page. ### Products Manage your product catalog. | Command | Description | | - | - | | `dodo products list ` | List products | | `dodo products create` | Open the dashboard to create a product | | `dodo products info ` | View details for a specific product | ### Payments View payment transactions. | Command | Description | | - | - | | `dodo payments list ` | List payments | | `dodo payments info ` | Get information about a specific payment | ### Customers Manage your customers. | Command | Description | | - | - | | `dodo customers list ` | List customers | | `dodo customers create` | Create a new customer (**TUI only**) | | `dodo customers update ` | Update an existing customer (**TUI only**) | | `dodo customers portal ` | Create a temporary Customer Portal session for a customer | ### Discounts Manage discount codes. | Command | Description | | - | - | | `dodo discounts list ` | List discounts | | `dodo discounts create` | Create a new percentage-based discount (**TUI only**) | | `dodo discounts delete ` | Remove a discount by ID (**TUI only**) | ### Licenses View license keys. The command is spelled `licences`. | Command | Description | | - | - | | `dodo licences list ` | List licenses | ### Addons Manage product add-ons. | Command | Description | | - | - | | `dodo addons list ` | List addons | | `dodo addons create` | Open the dashboard to create an addon | | `dodo addons info ` | View details for a specific addon | ### Refunds View refund information. | Command | Description | | - | - | | `dodo refunds list ` | List refunds | | `dodo refunds info ` | View details for a specific refund | ### Checkout Create hosted checkout sessions. | Command | Description | | - | - | | `dodo checkout new` | Interactively create a hosted checkout session and get a payment link (**TUI only**) | ## Webhooks The CLI has two webhook tools for development: a **listener** that forwards test mode webhooks to your local server, and a **trigger** that sends mock webhook payloads to any endpoint. | Command | Description | | - | - | | `dodo wh listen ` | Listen for webhooks in real time and forward them to your local dev server | | `dodo wh trigger ` | Send a mock webhook event, even while logged out | In direct mode, the arguments are required. In the TUI, run `/wh listen` or `/wh trigger` without arguments to open an interactive wizard. ### Listen for Webhooks Forward webhooks from your Dodo Payments account to your local development server in real time. > [!WARNING] > > `dodo wh listen` requires a **Test Mode** API key. Live Mode keys are not supported by the listen flow. ```bash theme={null} dodo wh listen http://localhost:3000/webhook ``` **1. Enter Your Local Endpoint URL** Pass the local URL that should receive webhooks, for example `http://localhost:3000/webhook`. In the TUI wizard, the CLI prompts you for it. **2. Automatic Setup** If your account has no webhook endpoint for the CLI's relay server, the CLI creates one. The endpoint appears in **Developer → Webhooks**. The CLI then opens a WebSocket connection to the relay to receive events in real time. **3. Receive and Forward** When a webhook event fires, for example from a test payment or a subscription change, the CLI forwards the payload and headers to your local endpoint as a `POST` request. It logs the event type and your endpoint's response, and sends the response back to the relay. > [!TIP] > > The listener preserves the original webhook headers (`webhook-id`, `webhook-signature`, `webhook-timestamp`) when forwarding to your local endpoint, so you can test your signature verification logic. > [!NOTE] > > The relay and the CLI parse the JSON body and serialize it again before forwarding. If the forwarded body differs byte for byte from the original, for example in number formatting, signature verification fails even though the headers are intact. ### Trigger Test Webhooks Send a mock webhook payload to any endpoint, without creating real transactions. > [!WARNING] > > Triggered events are **not signed**: the request carries no `webhook-id`, `webhook-signature`, or `webhook-timestamp` header. While testing, parse them with the unverified method (`unsafeUnwrap` in TypeScript, `unsafe_unwrap` in Python, `UnsafeUnwrap` in Go) instead of `unwrap`, and switch back to `unwrap` before you go live. ```bash theme={null} dodo wh trigger payment.success http://localhost:3000/webhook ``` In direct mode, the payload uses placeholder IDs and customer details. The `/wh trigger` wizard in the TUI guides you through: 1. Setting a destination **endpoint URL**. 2. Optionally entering a **Business ID**, **Product ID**, **Metadata** (a JSON object), **Customer email**, and **Customer ID** for the payload. Blank fields use placeholder values. 3. Selecting an **event** to send from an interactive menu. You can send several events in a row. Choose **exit** to finish. > [!NOTE] > > `dodo wh trigger` does **not** require login. It works as a local, offline webhook payload generator. ### Supported Webhook Events `dodo wh trigger` can send mock payloads for 46 of the 56 event types Dodo Payments delivers. It doesn't support `subscription.past_due`, `subscription.unpaused`, or the eight invoice events: `invoice.finalized`, `invoice.sent`, `invoice.paid`, `invoice.payment_failed`, `invoice.past_due`, `invoice.reopened`, `invoice.voided`, and `invoice.marked_uncollectable`. Pass the event name exactly as listed: | Category | Events | | - | - | | **Subscription** | `subscription.active`, `subscription.updated`, `subscription.on_hold`, `subscription.renewed`, `subscription.plan_changed`, `subscription.cancelled`, `subscription.failed`, `subscription.expired`, `subscription.paused`, `subscription.update_payment_method` | | **Payment** | `payment.success`, `payment.failed`, `payment.processing`, `payment.cancelled` | | **Refund** | `refund.success`, `refund.failed` | | **Dispute** | `dispute.opened`, `dispute.expired`, `dispute.accepted`, `dispute.cancelled`, `dispute.challenged`, `dispute.won`, `dispute.lost` | | **License Key** | `licence.created` | | **Payout** | `payout.created`, `payout.in_progress`, `payout.on_hold`, `payout.failed`, `payout.success` | | **Credit** | `credit.added`, `credit.deducted`, `credit.expired`, `credit.rolled_over`, `credit.rollover_forfeited`, `credit.overage_charged`, `credit.overage_reset`, `credit.manual_adjustment`, `credit.balance_low` | | **Abandoned Checkout** | `abandoned_checkout.detected`, `abandoned_checkout.recovered` | | **Dunning** | `dunning.started`, `dunning.recovered` | | **Entitlement Grant** | `entitlement_grant.created`, `entitlement_grant.delivered`, `entitlement_grant.failed`, `entitlement_grant.revoked` | Three trigger names differ from the event `type` in the payload they send: `payment.success` sends `payment.succeeded`, `refund.success` sends `refund.succeeded`, and `licence.created` sends `license_key.created`. > [!NOTE] > > Mock payload shapes follow the corresponding schemas in the API reference. See [Webhook Events](/developer-resources/webhooks/intents/webhook-events-guide) for what each event means and when Dodo Payments emits it in production. > [!TIP] > > `payout.created` is emitted while the payout still reports a `not_initiated` status, so the mock payload reflects that too. See [Payout Events](/developer-resources/webhooks/intents/payout) for the full payout lifecycle. ### Environment Variables This variable changes how `dodo wh listen` connects: | Variable | Description | | - | - | | `DODO_WH_TEST_SERVER_URL` | Override the default webhook relay server used by `dodo wh listen`. Set a host name without a scheme. | ## Updates The CLI checks for a newer version on startup and shows a notification in the status bar when one is available. To upgrade an npm or Bun install from the TUI, run: ```text theme={null} /update ``` `/update` can't upgrade a release binary. For binary installs, including the install script's, it links to the latest GitHub release instead. To upgrade from your shell, re-run the command you installed with: ```bash install.sh theme={null} curl -fsSL https://dodopayments.com/install.sh | sh ``` ```bash npm theme={null} npm install -g dodopayments-cli ``` ```bash Bun theme={null} bun install -g dodopayments-cli ``` ## Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-cli) > > Source code and releases. > [card] [npm Package](https://www.npmjs.com/package/dodopayments-cli) > > The `dodopayments-cli` package on the npm registry. ## Support * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-cli/issues). * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). # Flutter Source: https://docs.dodopayments.com/developer-resources/sdks/flutter Open Dodo Payments hosted checkout from a Flutter app in a system browser view with the official Flutter package, and get a typed checkout result back from one call. > [!NOTE] > > This page covers the official Dodo Payments Flutter package, `dodopayments_checkout` on pub.dev. A separate, community-built package also exists. See > [Community Projects](/community/projects). > [card] [Checkout Sessions API](/developer-resources/checkout-session) > > Create the `checkout_url` that this SDK opens, from your backend. > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > See how this SDK fits into the full mobile payment flow. `dodopayments_checkout` opens Dodo Payments hosted checkout in `SFSafariViewController` on iOS and in a Custom Tab on Android, and returns a typed `CheckoutResult`. It uses the same native code as the standalone [iOS](/developer-resources/sdks/ios) and [Android](/developer-resources/sdks/android) SDKs, and all checkout logic lives in that native code. The Dart layer passes each call through a typed [Pigeon](https://pub.dev/packages/pigeon) channel. The package holds no API key and never calls the Dodo Payments API. **Requirements:** Flutter 3.44 or later with Dart 3.12 or later, iOS 16 or later, and Android `minSdk` 23. ## Installation **1. Add the Dependency** Add the package to `pubspec.yaml`: ```yaml pubspec.yaml theme={null} dependencies: dodopayments_checkout: ^1.1.0 ``` [Appearance customization](#appearance-customization) requires version 1.1.0 or later. The Android plugin compiles against Android SDK 35 by default. If another plugin needs a higher `compileSdk`, set `dodoCompileSdk` in your app's `gradle.properties`. **2. Register a Callback URL Scheme** Register a URL scheme so that the operating system routes the checkout's return URL back to your app. Use this scheme in the `returnUrl` you pass to the SDK, and set the same URL as the checkout session's `return_url` when your backend creates the session. The URL doesn't need to load a real page. > [tab] iOS > > Add a URL type for your scheme in `ios/Runner/Info.plist`: > > ```xml ios/Runner/Info.plist theme={null} > CFBundleURLTypes > > > CFBundleURLName > myapp > CFBundleURLSchemes > > myapp > > > > ``` > > `SFSafariViewController` can't catch its own return URL, so iOS opens the URL in your app instead. Forward every incoming URL to the SDK, for example from > [`app_links`](https://pub.dev/packages/app_links): > > ```dart theme={null} > import 'package:dodopayments_checkout/dodopayments_checkout.dart'; > > // url is the incoming link as a String. For a Uri from app_links, pass uri.toString(). > DodoCheckout.instance.handleOpenURL(url); > ``` > > > [!NOTE] > > > > You can forward every URL. `handleOpenURL` acts only on a URL that matches the > > `returnUrl` of the checkout in progress, and resolves `true` for it. For any > > other URL, it resolves `false`. On Android, it always resolves `false`. > [tab] Android > > Set your callback scheme as a Gradle manifest placeholder in `android/app/build.gradle.kts`. The same line works in a Groovy `build.gradle` file: > > ```kotlin android/app/build.gradle.kts theme={null} > android { > defaultConfig { > manifestPlaceholders["dodoCallbackScheme"] = "myapp" > } > } > ``` > > > [!WARNING] > > > > If `MainActivity` sets `android:taskAffinity=""` (the default in the > > `flutter create` template), remove it or give the SDK's activities the same > > affinity. Otherwise, some OEM Android builds can lose the checkout in progress > > and fail with `PLATFORM_ERROR` and the message "Checkout was launched without its parameters." ## Usage Call `DodoCheckout.instance.start` with the `checkout_url` from your backend: ```dart theme={null} import 'package:dodopayments_checkout/dodopayments_checkout.dart'; // showSuccess(), showFailure(), showExpired(), and reconcileAbandonedSession() // are your own functions. See Abandoned Sessions for what to reconcile. final result = await DodoCheckout.instance.start( CheckoutParams( checkoutUrl: Uri.parse(checkoutUrl), // from your backend's checkout session returnUrl: Uri.parse('myapp://checkout/return'), // scheme must be registered (see Installation) onEvent: (event) => print(event.type), // logging only ), ); switch (result.status) { case CheckoutStatus.succeeded: showSuccess(result.paymentId); case CheckoutStatus.failed: showFailure(); case CheckoutStatus.cancelled: await reconcileAbandonedSession(); // outcome unknown, not a failure case CheckoutStatus.pending: await reconcileAbandonedSession(); case CheckoutStatus.expired: showExpired(); } ``` `onEvent` receives events whose `type` is `CheckoutEventType.opened`, `returnReceived`, or `closed`. Use them for logging only, never to decide the outcome. ## What the Result Means The SDK builds `CheckoutResult` from the query parameters on the return URL. > [!WARNING] > > `result.status` is a UI hint, not proof of payment. Confirm every payment > from your backend, with the `payment.succeeded` or `subscription.active` > webhook. **status** `CheckoutStatus` *required* One of five values: * `succeeded`: the return URL has `status=succeeded` (one-time payment) or `status=active` (subscription). * `failed`: the payment was declined (`status=failed`). * `cancelled`: the customer closed the browser view before the return URL arrived. The SDK doesn't know the outcome, and the payment may have succeeded, so don't show a failure screen. Reconcile the [abandoned session](#abandoned-sessions) instead. * `pending`: the payment settles later (`status=processing` or any `requires_*` value), or the `status` parameter was missing or unrecognized. Reconcile it like `cancelled`. * `expired`: the checkout session expired (`status=expired`). **paymentId** `String?` The `payment_id` query parameter, when the return URL includes one. Show it in your UI, but don't use it to grant access. See [Verify the Payment](#verify-the-payment). **subscriptionId** `String?` The `subscription_id` query parameter. Set for subscription checkouts. **licenseKeys** `List\?` The `license_key` query parameter. Set when the checkout includes license key products. **customerEmail** `String?` The `email` query parameter. Set when checkout captures an email address. **raw** `Map\` Every query parameter from the return URL, verbatim. ## Verify the Payment > [card] [Webhooks](/developer-resources/webhooks) > > Dodo Payments calls your backend when a payment succeeds or a subscription activates. > [card] [Get Payment Detail](/api-reference/payments/get-payments-1) > > Look up `paymentId` with your secret key to check its status. Grant access only after one of these confirms the payment. Don't rely on `result.status` alone. ## Appearance Customization To change the checkout browser's toolbar, buttons, and color scheme, pass a `BrowserCustomization` as `customization` on `CheckoutParams`. Android Custom Tabs and iOS `SFSafariViewController` expose different native controls, so the options are split into `AndroidBrowserOptions` and `IosBrowserOptions`. Each platform ignores the other's options. Every field is optional and defaults to `null`. For a `null` field, the SDK doesn't set that option and the platform applies its own default. > [accordion] Android — Custom Tab > > **toolbarColor** `Color?` > > Toolbar background color. > > **navigationBarColor** `Color?` > > Navigation bar color. > > **navigationBarDividerColor** `Color?` > > Color of the divider above the navigation bar. > > **closeButtonStyle** `CloseButtonStyle?` > > `standard` shows the system "X" icon. `back` shows a back arrow that the SDK draws. > > **closeButtonPosition** `CloseButtonPosition?` > > The side of the toolbar where the close button appears: `start` or `end`. > > **shareButtonEnabled** `bool?` > > Shows the toolbar's share icon. `false` hides it. > > **showTitleEnabled** `bool?` > > Shows the page title under the URL in the toolbar. > > **urlBarHidingEnabled** `bool?` > > Hides the toolbar automatically as the page scrolls. > > **bookmarksButtonEnabled** `bool?` > > Shows "Bookmark this page" in the overflow menu. > > **downloadsButtonEnabled** `bool?` > > Shows "Download page" in the overflow menu. > > **colorScheme** `BrowserColorScheme?` > > `light` or `dark` forces that appearance regardless of the device's system setting. `system` follows the system setting. > [accordion] iOS — SFSafariViewController > > **dismissButtonStyle** `DismissButtonStyle?` > > Style of the dismiss button: `done`, `close`, or `cancel`. iOS decides whether it renders as a label or an icon. > > **presentationStyle** `PresentationStyle?` > > `pageSheet` (used when you leave this `null`) presents a card that the customer can swipe down to dismiss. `fullScreen` covers the whole screen. > > **barCollapsingEnabled** `bool?` > > Lets the toolbar collapse as the page scrolls. It has a visible effect only when `presentationStyle` is `fullScreen`. With `pageSheet`, the bars stay pinned regardless of this setting. > > **colorScheme** `BrowserColorScheme?` > > `light` or `dark` forces that appearance regardless of the device's system setting. `system` follows the system setting. iOS has no toolbar color option, because the underlying `SFSafariViewController` tint properties are deprecated as of iOS 26. ```dart theme={null} import 'package:dodopayments_checkout/dodopayments_checkout.dart'; import 'package:flutter/material.dart' show Color; final result = await DodoCheckout.instance.start( CheckoutParams( checkoutUrl: Uri.parse(checkoutUrl), returnUrl: Uri.parse('myapp://checkout/return'), customization: BrowserCustomization( android: AndroidBrowserOptions( toolbarColor: Color(0xFF6366F1), closeButtonStyle: CloseButtonStyle.back, ), ios: IosBrowserOptions( presentationStyle: PresentationStyle.fullScreen, colorScheme: BrowserColorScheme.dark, ), ), ), ); ``` ## Errors `start` throws `CheckoutException` only for misuse or a platform failure. Read the reason from `code`, a `CheckoutErrorCode`. The native code string is in `nativeCode`. A customer who cancels, or a declined payment, is always a result, never an exception. * `invalidCheckoutUrl` (`INVALID_CHECKOUT_URL`): `checkoutUrl` isn't an `https` checkout session URL (path starting with `/session/`) on `checkout.dodopayments.com` or `test.checkout.dodopayments.com`. * `invalidReturnUrl` (`INVALID_RETURN_URL`): `returnUrl` isn't an absolute URL with a scheme and a host. * `alreadyInProgress` (`ALREADY_IN_PROGRESS`): another checkout is running. Only one checkout can run at a time. * `platformError` (`PLATFORM_ERROR`): an unexpected platform failure. Unknown native errors also map to this code. ## Abandoned Sessions > [!NOTE] > > The native SDK records the checkout session when checkout starts, and clears the > record only when checkout ends with `succeeded`, `failed`, or `expired`. The record > stays when the app is killed during checkout, and after a `cancelled` or `pending` > result. Check for it on the next launch and after every `cancelled` or `pending` result. ```dart theme={null} import 'package:dodopayments_checkout/dodopayments_checkout.dart'; final abandoned = await DodoCheckout.instance.getAbandonedSession(); if (abandoned != null) { // Ask your backend for the outcome of abandoned.sessionId, and show it. // Clear the record only after the outcome is final: await DodoCheckout.instance.clearAbandonedSession(); } ``` `abandoned.sessionId` is the checkout session ID, which starts with `cks_`. `abandoned.createdAt` is the `DateTime` checkout started. Your backend can look up the session with [Get Checkout Session](/api-reference/checkout-sessions/get-checkouts), which returns its `payment_id` and `payment_status`. Until the payment reaches a final status, treat it as pending, not failed. ## Related > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > The same contract for Android, iOS, and React Native. > [card] [Community Projects](/community/projects) > > A separate, community-built Flutter package also exists. # iOS Source: https://docs.dodopayments.com/developer-resources/sdks/ios Open Dodo Payments hosted checkout from an iOS app in SFSafariViewController with the official Swift SDK, and get a typed checkout result back from one call. > [!NOTE] > > This page covers the official Dodo Payments iOS checkout SDK for Swift. It opens Dodo Payments hosted checkout in a native browser view and returns a typed result. > [card] [Checkout Sessions API](/developer-resources/checkout-session) > > Create the `checkout_url` that this SDK opens, from your backend. > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > See how this SDK fits into the full mobile payment flow. The iOS SDK opens Dodo Payments hosted checkout in `SFSafariViewController` and returns a typed `CheckoutResult` when the customer finishes or leaves checkout. It holds no API key and contains no networking code, so it never calls the Dodo Payments API. Checkout runs in the browser view. The SDK presents and dismisses that view and reads the result from the return URL. **Requirements:** iOS 16 or later, and Swift 6.2 or later (the package declares `swift-tools-version: 6.2`). The SDK has no third-party dependencies. ## Installation **1. Add the Package** In Xcode, go to **File → Add Package Dependencies** and enter the package URL: ```text theme={null} https://github.com/dodopayments/dodopayments-mobile-sdk-ios ``` Select version 1.1.0 or later. [Appearance customization](#appearance-customization) requires 1.1.0. To add the package in `Package.swift` instead, add this dependency: ```swift Package.swift theme={null} .package(url: "https://github.com/dodopayments/dodopayments-mobile-sdk-ios", from: "1.1.0") ``` The library product is `DodoCheckout`. **2. Register a Callback URL Scheme** Register a URL scheme so that iOS routes the checkout's return URL back to your app. Add a URL type to your `Info.plist`: ```xml Info.plist theme={null} CFBundleURLTypes CFBundleURLName myapp CFBundleURLSchemes myapp ``` You can also add the URL type in Xcode under **Info → URL Types**. Use this scheme in the `returnUrl` you pass to the SDK, for example `myapp://checkout/return`, and set the same URL as the checkout session's `return_url` when your backend creates the session. The SDK matches the return URL on scheme, host, and path. The URL doesn't need to load a real page. ## Usage `DodoCheckout.start` is an `async` function that runs on the main actor. Pass `checkoutUrl` as a `URL` built from the `checkout_url` your backend returns: ```swift theme={null} import DodoCheckout // showSuccess(_:), showFailure(), showExpired(), and reconcileAbandonedSession() // are your own functions. See Abandoned Sessions for what to reconcile. let result = try await DodoCheckout.start( checkoutUrl: checkoutUrl, // from your backend's checkout session returnUrl: URL(string: "myapp://checkout/return")!, onEvent: { event in print(event.name) } // logging only ) switch result.status { case .succeeded: showSuccess(result.paymentId) case .failed: showFailure() case .cancelled: await reconcileAbandonedSession() // outcome unknown, not a failure case .pending: await reconcileAbandonedSession() case .expired: showExpired() } ``` `onEvent` receives `.opened`, `.returnReceived`, and `.closed` events. Their `name` values are `checkout.opened`, `checkout.return_received`, and `checkout.closed`. Use events for logging only, never to decide the outcome. ## Forwarding the Return URL `SFSafariViewController` can't catch its own return URL, so iOS opens the URL in your app instead. Forward every incoming URL to `DodoCheckout.handleOpenURL(_:)`. In an app without scenes, call it from your app delegate's `application(_:open:options:)`. > [tab] SwiftUI > > ```swift theme={null} > .onOpenURL { url in > DodoCheckout.handleOpenURL(url) > } > ``` > [tab] SceneDelegate > > ```swift SceneDelegate.swift theme={null} > func scene(_ scene: UIScene, openURLContexts URLContexts: Set) { > guard let url = URLContexts.first?.url else { return } > DodoCheckout.handleOpenURL(url) > } > ``` > [!NOTE] > > You can forward every URL. `handleOpenURL` acts only on a URL that matches the `returnUrl` of the checkout in progress, and returns `true` for it. For any other URL, it returns `false`, so handle that URL yourself. ## What the Result Means The SDK builds `CheckoutResult` from the query parameters on the return URL. > [!WARNING] > > `result.status` is a UI hint, not proof of payment. Confirm every payment from your backend, with the `payment.succeeded` or `subscription.active` webhook. **status** `CheckoutStatus` *required* One of five values: * `succeeded`: the return URL has `status=succeeded` (one-time payment) or `status=active` (subscription). * `failed`: the payment was declined (`status=failed`). * `cancelled`: the customer dismissed the sheet before the return URL arrived. The SDK doesn't know the outcome, and the payment may have succeeded, so don't show a failure screen. Reconcile the [abandoned session](#abandoned-sessions) instead. * `pending`: the payment settles later (`status=processing` or any `requires_*` value), or the `status` parameter was missing or unrecognized. Reconcile it like `cancelled`. * `expired`: the checkout session expired (`status=expired`). **paymentId** `String?` The `payment_id` query parameter, when the return URL includes one. Show it in your UI, but don't use it to grant access. See [Verify the Payment](#verify-the-payment). **subscriptionId** `String?` The `subscription_id` query parameter. Set for subscription checkouts. **licenseKeys** `[String]?` The `license_key` query parameter. Set when the checkout includes license key products. **customerEmail** `String?` The `email` query parameter. Set when checkout captures an email address. **raw** `[String: String]` Every query parameter from the return URL, verbatim. ## Verify the Payment > [card] [Webhooks](/developer-resources/webhooks) > > Dodo Payments calls your backend when a payment succeeds or a subscription activates. > [card] [Get Payment Detail](/api-reference/payments/get-payments-1) > > Look up `paymentId` with your secret key to check its status. Grant access only after one of these confirms the payment. Don't rely on `result.status` alone. ## Appearance Customization To change the sheet's dismiss button, presentation style, and color scheme, pass a `BrowserCustomization` as `customization` to `start(...)`. Every field is optional. For a `nil` field, the SDK doesn't set that option and iOS applies its own default. The exception is `presentationStyle`, where `nil` means `pageSheet`. **dismissButtonStyle** `DismissButtonStyle?` Style of the dismiss button: `done`, `close`, or `cancel`. iOS decides whether it renders as a label or an icon. **presentationStyle** `PresentationStyle?` `pageSheet` (the default) presents a card that the customer can swipe down to dismiss. `fullScreen` covers the whole screen and has no dismiss gesture. **barCollapsingEnabled** `Bool?` Lets the toolbar collapse as the page scrolls. It has a visible effect only when `presentationStyle` is `fullScreen`. With `pageSheet`, the bars stay pinned regardless of this setting. **colorScheme** `ColorScheme?` `light` or `dark` forces that appearance regardless of the device's system setting. `system` follows the system setting. This option themes only the native controls around the page. The checkout page's own light or dark mode comes from `customization.theme` on the checkout session, and its colors come from `customization.theme_config`. iOS has no toolbar color option. The underlying `SFSafariViewController` tint properties are deprecated as of iOS 26. ```swift theme={null} let result = try await DodoCheckout.start( checkoutUrl: checkoutUrl, returnUrl: URL(string: "myapp://checkout/return")!, customization: BrowserCustomization( dismissButtonStyle: .close, presentationStyle: .fullScreen, colorScheme: .dark ) ) ``` ## Errors `start` throws `CheckoutError` only for misuse or a platform failure. Read the reason from `error.code`. A customer who cancels, or a declined payment, is always a result, never a thrown error. * `invalidCheckoutUrl` (`INVALID_CHECKOUT_URL`): `checkoutUrl` isn't an `https` checkout session URL (path starting with `/session/`) on `checkout.dodopayments.com` or `test.checkout.dodopayments.com`. * `invalidReturnUrl` (`INVALID_RETURN_URL`): `returnUrl` isn't an absolute URL with a scheme and a host. * `alreadyInProgress` (`ALREADY_IN_PROGRESS`): another checkout is running. Only one checkout can run at a time. * `platformError` (`PLATFORM_ERROR`): an unexpected platform failure, such as no view controller to present from. After a thrown error, check for an abandoned session too. If the sheet didn't confirm that it appeared, the SDK keeps the session on record because checkout may still be open. The exception is `alreadyInProgress`: a record you find then belongs to the checkout that is still running. ## Abandoned Sessions > [!NOTE] > > The SDK records the checkout session when it presents checkout, and clears the record only when checkout ends with `succeeded`, `failed`, or `expired`. The record stays when the app is killed during checkout, and after a `cancelled` or `pending` result. Check for it on the next launch and after every `cancelled` or `pending` result. ```swift theme={null} import DodoCheckout if let abandoned = DodoCheckout.getAbandonedSession() { // Ask your backend for the outcome of abandoned.sessionId, and show it. // Clear the record only after the outcome is final: DodoCheckout.clearAbandonedSession() } ``` `abandoned.sessionId` is the checkout session ID, which starts with `cks_`. `abandoned.createdAt` is the `Date` checkout started. Your backend can look up the session with [Get Checkout Session](/api-reference/checkout-sessions/get-checkouts), which returns its `payment_id` and `payment_status`. Until the payment reaches a final status, treat it as pending, not failed. ## Related > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > The same contract for Android, React Native, and Flutter. > [card] [React Native SDK](/developer-resources/sdks/react-native) > > Wraps this same Swift core on iOS. # React Native Source: https://docs.dodopayments.com/developer-resources/sdks/react-native Open Dodo Payments hosted checkout from a React Native or Expo app in a system browser view, and get a typed checkout result back from one call. > [!NOTE] > > This page covers the official Dodo Payments React Native checkout SDK, `@dodopayments/react-native-checkout`. It opens Dodo Payments hosted checkout in a native browser view and returns a typed result. An older package, `dodopayments-react-native-sdk` (unscoped), has a different API. This page documents only the scoped package. > [card] [Checkout Sessions API](/developer-resources/checkout-session) > > Create the `checkout_url` that this SDK opens, from your backend. > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > See how this SDK fits into the full mobile payment flow. The React Native SDK is a Turbo Module that wraps the native [iOS](/developer-resources/sdks/ios) and [Android](/developer-resources/sdks/android) checkout SDKs. It opens `SFSafariViewController` on iOS and a Custom Tab on Android. It holds no API key and has no checkout logic of its own, so it never calls the Dodo Payments API. Checkout runs in the browser view. The SDK presents and dismisses that view and reads the result from the return URL. > [!WARNING] > > This SDK supports the **New Architecture only**. It requires React Native 0.77 or later, iOS 16 or later, and Android `minSdk` 24. Your Android app must build with `compileSdk` 34 or later. ## Installation **1. Install the Package** > [tab] Android > > The package is autolinked and pulls `com.dodopayments.api:checkout-android` from Maven Central. > > ```sh theme={null} > npm i @dodopayments/react-native-checkout > ``` > > The native dependency resolves automatically, so no other install step is needed. > [tab] iOS > > ```sh theme={null} > npm i @dodopayments/react-native-checkout > cd ios && pod install > ``` > > The package bundles the Swift core, and CocoaPods installs it. > [tab] Expo > > The SDK works in development builds only, not in Expo Go. > > ```sh theme={null} > npm i @dodopayments/react-native-checkout > ``` > > Then configure the plugin in `app.json`, as shown in the next step. [Appearance customization](#appearance-customization) requires version 1.2.0 or later. **2. Register a Callback URL Scheme** Register a URL scheme so that the operating system routes the checkout's return URL back to your app. > [tab] Android (Gradle) > > Set the scheme as a manifest placeholder in `android/app/build.gradle`: > > ```groovy android/app/build.gradle theme={null} > android { > defaultConfig { > manifestPlaceholders["dodoCallbackScheme"] = "myapp" > } > } > ``` > > Replace `"myapp"` with your app's scheme. > [tab] iOS (Info.plist) > > Add a URL type to `ios/YourApp/Info.plist`: > > ```xml Info.plist theme={null} > CFBundleURLTypes > > > CFBundleURLName > myapp > CFBundleURLSchemes > > myapp > > > > ``` > > You can also add the URL type in Xcode under **Info → URL Types**. > [tab] Expo (both platforms) > > The package's config plugin registers the scheme for both platforms during `prebuild`. Pass the scheme as the plugin's `scheme` option in `app.json`: > > ```json app.json theme={null} > { > "expo": { > "scheme": "myapp", > "plugins": [ > [ > "@dodopayments/react-native-checkout", > { "scheme": "myappcheckout" } > ] > ] > } > } > ``` > > The plugin's `scheme` must match the scheme of the `returnUrl` you pass, for example `myappcheckout://return`. Use a scheme that differs from `expo.scheme`. Expo already registers `expo.scheme` on `MainActivity`, so reusing it can send the checkout return to the wrong activity on Android, and the plugin warns you. The plugin rejects `http`, `https`, and other system schemes. > > Rebuild the native project after you edit `app.json`: > > ```sh theme={null} > npx expo prebuild --clean > ``` > > The plugin works with development builds only, not Expo Go. On iOS, you still need the `Linking` listener in [Forwarding the Return URL](#forwarding-the-return-url). > > If `android/app/build.gradle` has no `defaultConfig { }` block, the plugin stops `prebuild` with an error. In that case, add the placeholder yourself, as shown in the Android tab. On every platform, set the same URL as the checkout session's `return_url` when your backend creates the session. The SDK matches the return URL on scheme, host, and path. The URL doesn't need to load a real page. ## Usage Call `DodoCheckout.start` with the `checkout_url` from your backend: ```typescript theme={null} import { Linking } from 'react-native'; import { DodoCheckout } from '@dodopayments/react-native-checkout'; // Required for iOS's return-URL handling. Linking.addEventListener('url', ({ url }) => DodoCheckout.handleOpenURL(url)); // showSuccess(), showFailure(), showExpired(), and reconcileAbandonedSession() // are your own functions. See Abandoned Sessions for what to reconcile. const result = await DodoCheckout.start({ checkoutUrl, // from your backend's checkout session returnUrl: 'myapp://checkout/return', // scheme must be registered (see Installation) onEvent: (e) => console.log(e.type), // logging only }); switch (result.status) { case 'succeeded': showSuccess(result.paymentId); break; case 'failed': showFailure(); break; case 'cancelled': await reconcileAbandonedSession(); break; // outcome unknown, not a failure case 'pending': await reconcileAbandonedSession(); break; case 'expired': showExpired(); break; } ``` `onEvent` receives events with a `type` of `checkout.opened`, `checkout.return_received`, or `checkout.closed`. Use them for logging only, never to decide the outcome. ## Forwarding the Return URL iOS needs the `Linking` listener to handle the return URL, because `SFSafariViewController` can't catch its own return URL. On Android, `handleOpenURL` does nothing and resolves `false`, because the Android SDK catches its redirect natively. You can register the listener on both platforms. ```typescript theme={null} import { Linking } from 'react-native'; import { DodoCheckout } from '@dodopayments/react-native-checkout'; Linking.addEventListener('url', ({ url }) => { DodoCheckout.handleOpenURL(url); }); ``` On iOS, `handleOpenURL` resolves `true` when the URL belongs to the checkout in progress, and `false` for any other URL. ## What the Result Means The SDK builds the result from the query parameters on the return URL. > [!WARNING] > > `result.status` is a UI hint, not proof of payment. Confirm every payment from your backend, with the `payment.succeeded` or `subscription.active` webhook. **status** `CheckoutStatus` *required* One of five values: * `succeeded`: the return URL has `status=succeeded` (one-time payment) or `status=active` (subscription). * `failed`: the payment was declined (`status=failed`). * `cancelled`: the customer closed the browser view before the return URL arrived. The SDK doesn't know the outcome, and the payment may have succeeded, so don't show a failure screen. Reconcile the [abandoned session](#abandoned-sessions) instead. * `pending`: the payment settles later (`status=processing` or any `requires_*` value), or the `status` parameter was missing or unrecognized. Reconcile it like `cancelled`. * `expired`: the checkout session expired (`status=expired`). **paymentId** `string` The `payment_id` query parameter, when the return URL includes one. Show it in your UI, but don't use it to grant access. See [Verify the Payment](#verify-the-payment). **subscriptionId** `string` The `subscription_id` query parameter. Set for subscription checkouts. **licenseKeys** `string[]` The `license_key` query parameter. Set when the checkout includes license key products. **customerEmail** `string` The `email` query parameter. Set when checkout captures an email address. **raw** `Record\` Every query parameter from the return URL, verbatim. ## Verify the Payment > [card] [Webhooks](/developer-resources/webhooks) > > Dodo Payments calls your backend when a payment succeeds or a subscription activates. > [card] [Get Payment Detail](/api-reference/payments/get-payments-1) > > Look up `paymentId` with your secret key to check its status. Grant access only after one of these confirms the payment. Don't rely on `result.status` alone. ## Appearance Customization To change the checkout browser's toolbar, buttons, and color scheme, pass `customization` to `start(...)`. Android Custom Tabs and iOS `SFSafariViewController` expose different native controls, so the options are grouped into an `android` object and an `ios` object. Each platform reads only its own object. Every field is optional. When you omit a field, the platform applies its own default. > [accordion] Android — Custom Tab > > **toolbarColor** `string` > > Toolbar background color, as a hex string: `"#RRGGBB"` or `"#AARRGGBB"`. > > **navigationBarColor** `string` > > Navigation bar color, as a hex string. > > **navigationBarDividerColor** `string` > > Color of the divider above the navigation bar, as a hex string. > > **closeButtonStyle** `'default' | 'back'` > > `default` shows the system "X" icon. `back` shows a back arrow that the SDK draws. > > **closeButtonPosition** `'start' | 'end'` > > The side of the toolbar where the close button appears. > > **shareButtonEnabled** `boolean` > > Shows the toolbar's share icon. `false` hides it. > > **showTitleEnabled** `boolean` > > Shows the page title under the URL in the toolbar. > > **urlBarHidingEnabled** `boolean` > > Hides the toolbar automatically as the page scrolls. > > **bookmarksButtonEnabled** `boolean` > > Shows "Bookmark this page" in the overflow menu. > > **downloadsButtonEnabled** `boolean` > > Shows "Download page" in the overflow menu. > > **colorScheme** `'system' | 'light' | 'dark'` > > `light` or `dark` forces that appearance regardless of the device's system setting. `system` follows the system setting. > [accordion] iOS — SFSafariViewController > > **dismissButtonStyle** `'done' | 'close' | 'cancel'` > > Style of the dismiss button. iOS decides whether it renders as a label or an icon. > > **presentationStyle** `'pageSheet' | 'fullScreen'` > > `pageSheet` (the default) presents a card that the customer can swipe down to dismiss. `fullScreen` covers the whole screen. > > **barCollapsingEnabled** `boolean` > > Lets the toolbar collapse as the page scrolls. It has a visible effect only when `presentationStyle` is `fullScreen`. With `pageSheet`, the bars stay pinned regardless of this setting. > > **colorScheme** `'system' | 'light' | 'dark'` > > `light` or `dark` forces that appearance regardless of the device's system setting. `system` follows the system setting. iOS has no toolbar color option, because the underlying `SFSafariViewController` tint properties are deprecated as of iOS 26. ```typescript theme={null} const result = await DodoCheckout.start({ checkoutUrl, returnUrl: 'myapp://checkout/return', customization: { android: { toolbarColor: '#6366F1', closeButtonStyle: 'back' }, ios: { presentationStyle: 'fullScreen', colorScheme: 'dark' }, }, }); ``` ## Errors `start` rejects with a `CheckoutError` only for misuse or a platform failure. Read the reason from `error.code`. A customer who cancels, or a declined payment, is always a result, never a rejection. * `INVALID_CHECKOUT_URL`: `checkoutUrl` isn't an `https` checkout session URL (path starting with `/session/`) on `checkout.dodopayments.com` or `test.checkout.dodopayments.com`. * `INVALID_RETURN_URL`: `returnUrl` isn't an absolute URL with a scheme and a host. * `ALREADY_IN_PROGRESS`: another checkout is running. Only one checkout can run at a time. * `PLATFORM_ERROR`: an unexpected platform failure. The SDK also reports any unrecognized native error with this code. ## Abandoned Sessions The native SDK records the checkout session when checkout starts, and clears the record only when checkout ends with `succeeded`, `failed`, or `expired`. The record stays when the app or the JavaScript bundle is killed during checkout, which loses the `start` promise, and after a `cancelled` or `pending` result. Check for it on the next mount and after every `cancelled` or `pending` result: ```typescript theme={null} import { DodoCheckout } from '@dodopayments/react-native-checkout'; const abandoned = await DodoCheckout.getAbandonedSession(); if (abandoned) { // Ask your backend for the outcome of abandoned.sessionId, and show it. // Clear the record only after the outcome is final: await DodoCheckout.clearAbandonedSession(); } ``` `abandoned.sessionId` is the checkout session ID, which starts with `cks_`. `abandoned.createdAt` is the `Date` checkout started. Your backend can look up the session with [Get Checkout Session](/api-reference/checkout-sessions/get-checkouts), which returns its `payment_id` and `payment_status`. Until the payment reaches a final status, treat it as pending, not failed. ## Related > [card] [Mobile Integration Guide](/developer-resources/mobile-integration) > > The same contract for Android, iOS, and Flutter. > [card] [Expo Boilerplate](/developer-resources/expo-boilerplate) > > A complete Expo example with checkout integration. # Rust Source: https://docs.dodopayments.com/developer-resources/sdks/rust Use the Dodo Payments Rust SDK, an async client built on Tokio and reqwest, to create checkout sessions, customers, subscriptions, and usage events. The Rust SDK gives async Rust applications typed access to the Dodo Payments REST API. It's built on Tokio and reqwest, uses typed request and response structs, streams paginated results, and retries failed requests. ## Installation Add the SDK to your project with Cargo: ```bash theme={null} cargo add dodopayments ``` Or add it to your `Cargo.toml` manually: ```toml theme={null} [dependencies] dodopayments = "1.119.0" tokio = { version = "1", features = ["full"] } serde_json = "1" futures = "0.3" # required for streaming paginated results ``` > [!NOTE] > > The SDK requires Rust 1.75 or later. ## Quick Start `Client::from_env()` reads your API key from the `DODO_PAYMENTS_API_KEY` environment variable. Create a client, then create a checkout session: ```rust theme={null} use dodopayments::Client; #[tokio::main] async fn main() -> dodopayments::Result<()> { let client = Client::from_env()?; let result = client .checkout_sessions() .create() .body(dodopayments::models::CheckoutSessionsCreateParams { product_cart: Some(vec![dodopayments::models::ProductItemReq { product_id: "pdt_123".to_string(), quantity: 1, addons: None, amount: None, credit_entitlements: None, }]), ..Default::default() }) .await?; println!("{result:?}"); Ok(()) } ``` If `DODO_PAYMENTS_API_KEY` isn't set, `Client::from_env()` returns an `Error::Config`. The client connects to live mode unless you choose another environment, as shown in [Environments](#environments). A test mode API key works only in test mode. > [!WARNING] > > Keep API keys in environment variables or a secrets manager. Never hardcode them in your source code. ## Core Features > [card] Async First > > Built on Tokio and reqwest, with `async`/`await` for every request. > [card] Strong Typing > > Typed request and response structs for compile-time checks. > [card] Auto-Pagination > > Stream every item across pages, or move one page at a time. > [card] Configurable > > Set the environment, base URL, timeout, and retry count for each client. ## Configuration ### Environment Variables `Client::from_env()` reads your API key from `DODO_PAYMENTS_API_KEY`. It uses the live mode URL unless you set `DODO_PAYMENTS_BASE_URL`: ```bash theme={null} export DODO_PAYMENTS_API_KEY="dodo_test_..." export DODO_PAYMENTS_BASE_URL="https://test.dodopayments.com" # optional ``` The Rust SDK doesn't read `DODO_PAYMENTS_WEBHOOK_KEY` and has no method that verifies webhook signatures. To verify them, follow [Webhooks](/developer-resources/webhooks). You can also configure the client explicitly. `Client::new` returns a `Result`, so unwrap it with `?` inside a function that returns `dodopayments::Result`: ```rust theme={null} use dodopayments::{Client, ClientConfig}; #[tokio::main] async fn main() -> dodopayments::Result<()> { let client = Client::new( ClientConfig::new("https://live.dodopayments.com").with_api_key("dodo_live_..."), )?; println!("{}", client.base_url()); Ok(()) } ``` ### Environments The SDK has two environments: | Name | Base URL | | - | - | | `live_mode` | `https://live.dodopayments.com` | | `test_mode` | `https://test.dodopayments.com` | The default base URL is `https://live.dodopayments.com`. To select another environment, use the `Environment` enum instead of a hard-coded URL: ```rust theme={null} use dodopayments::{Client, ClientConfig, Environment}; let client = Client::new( ClientConfig::from_environment(Environment::TestMode).with_api_key("dodo_test_..."), )?; ``` To keep reading the API key from `DODO_PAYMENTS_API_KEY` with `from_env()` but target another environment, override the environment on the config: ```rust theme={null} use dodopayments::{Client, ClientConfig, Environment}; let client = Client::new(ClientConfig::from_env()?.with_environment(Environment::TestMode))?; ``` ### Timeouts The default request timeout is 30 seconds. Override it for a client with `with_timeout`: ```rust theme={null} use std::time::Duration; use dodopayments::{Client, ClientConfig}; let client = Client::new( ClientConfig::new("https://live.dodopayments.com") .with_api_key("dodo_live_...") .with_timeout(Duration::from_secs(60)), )?; ``` The client retries connection errors and responses with status 408, 409, 429, or 500 and above. It retries twice by default, with exponential backoff, and waits for the `Retry-After` header when the API sends one. To change the retry count, call `with_max_retries` on the `ClientConfig`, for example `.with_max_retries(0)` to turn retries off. ## Workload Identity The SDK can use workload identity federation instead of an API key. The SDK exchanges an OIDC token from your CI or cloud platform for a short-lived Dodo Payments token. It refreshes the token before the token expires. This feature is available from version 1.125.0. Before you start, create an identity provider and a mapping in the dashboard. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup). This example uses the GitHub Actions helper, `workload_identity::github_actions(None)`: ```rust theme={null} use dodopayments::workload_identity; use dodopayments::{Client, ClientConfig, WorkloadIdentity}; let client = Client::new( ClientConfig::new("https://live.dodopayments.com").with_workload_identity( WorkloadIdentity::new(workload_identity::github_actions(None)) .with_identity_provider_id("wip_..."), ), )?; ``` If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the SDK uses workload identity. It finds the platform from the environment. To stop the token before it expires, for example at the end of a CI job, revoke it: ```rust theme={null} client.revoke_workload_identity().await?; ``` > [!WARNING] > > Do not set an API key and workload identity together. The SDK gives an error when you set the two options. For the other platform helpers and the refresh behavior, refer to [Use Workload Identity with the SDKs](/developer-resources/workload-identity/sdk-usage). ## Common Operations The examples in this section use the `client` from [Quick Start](#quick-start). ### Create a Checkout Session Create a checkout session with a return URL: ```rust theme={null} let session = client .checkout_sessions() .create() .body(dodopayments::models::CheckoutSessionsCreateParams { product_cart: Some(vec![dodopayments::models::ProductItemReq { product_id: "pdt_123".to_string(), quantity: 1, addons: None, amount: None, credit_entitlements: None, }]), return_url: Some("https://yourdomain.com/return".to_string()), ..Default::default() }) .await?; println!("{session:?}"); ``` Redirect the customer to `session.checkout_url`. Each checkout URL works once and expires after 24 hours. For every session option, see [Checkout Sessions](/developer-resources/checkout-session). ### Manage Customers Create a customer with an email address and name, then retrieve it by ID: ```rust theme={null} // Create a customer let customer = client .customers() .create() .body(dodopayments::models::CustomersCreateParams { email: Some("customer@example.com".to_string()), name: Some("John Doe".to_string()), ..Default::default() }) .await?; // Retrieve a customer let customer = client .customers() .retrieve() .customer_id("cus_123") .await?; println!("{customer:?}"); ``` ### Handle Subscriptions Start a subscription for an existing customer with a checkout session. Put a subscription product in `product_cart`: ```rust theme={null} let session = client .checkout_sessions() .create() .body(dodopayments::models::CheckoutSessionsCreateParams { product_cart: Some(vec![dodopayments::models::ProductItemReq { product_id: "pdt_456".to_string(), quantity: 1, addons: None, amount: None, credit_entitlements: None, }]), customer: Some(Box::new( dodopayments::models::CustomerRequest::AttachExistingCustomer(Box::new( dodopayments::models::AttachExistingCustomer { customer_id: "cus_123".to_string(), }, )), )), return_url: Some("https://yourdomain.com/return".to_string()), ..Default::default() }) .await?; println!("{session:?}"); ``` > [!NOTE] > > The subscription starts when the customer completes checkout. Read its `subscription_id` from the `subscription.active` webhook or from the `return_url` query parameters. `customer` is a `CustomerRequest` enum: pass `AttachExistingCustomer` for an existing customer or `NewCustomer` to create one. To charge an [on-demand subscription](/developer-resources/ondemand-subscriptions), call `client.subscriptions().charge().subscription_id(...)` with a `SubscriptionsChargeParams` body. Amount fields such as `product_price` are in the smallest currency unit (for example, `2500` is \$25.00). ## Usage-Based Billing ### Ingest Usage Events Send usage events for a customer: ```rust theme={null} let response = client .usage_events() .ingest() .body(dodopayments::models::UsageEventsIngestParams { events: Some(vec![dodopayments::models::EventInput { customer_id: "cus_abc123".to_string(), event_id: "api_call_12345".to_string(), event_name: "api_request".to_string(), metadata: None, timestamp: None, }]), ..Default::default() }) .await?; println!("{response:?}"); ``` The `event_id` is the idempotency key, so give each event a unique value. If `timestamp` is `None`, the event uses the current time. ### List Usage Events List events filtered by customer and event name. The filters go in a JSON query object: ```rust theme={null} let events = client .usage_events() .list() .query(serde_json::json!({ "customer_id": "cus_abc123", "event_name": "api_request", })) .await?; for event in &events.items { println!("{event:?}"); } ``` ## Pagination List endpoints return a typed page whose `items` field holds the current page of results. To stream every item across all pages, call `into_stream`: ```rust theme={null} use futures::StreamExt; let mut items = Box::pin( client .payments() .list() .query(serde_json::json!({})) .await? .into_stream(), ); while let Some(item) = items.next().await { let item = item?; println!("{item:?}"); } ``` To move one page at a time, call `get_next_page`. It returns `None` after the last page: ```rust theme={null} let mut page = client .payments() .list() .query(serde_json::json!({})) .await?; loop { for item in &page.items { println!("{item:?}"); } match page.get_next_page().await? { Some(next) => page = next, None => break, } } ``` ## Error Handling Every method returns a `dodopayments::Result`. Failures are variants of the `dodopayments::Error` enum: `Api` for an error status from the API, `Http` for transport errors, `Json` for serialization errors, `Config` for configuration errors, and `MissingPathParam` or `MissingBody` for incomplete requests. Match on it to handle API errors separately from transport errors: ```rust theme={null} let result = client .checkout_sessions() .create() .body(dodopayments::models::CheckoutSessionsCreateParams { product_cart: Some(vec![dodopayments::models::ProductItemReq { product_id: "pdt_123".to_string(), quantity: 1, addons: None, amount: None, credit_entitlements: None, }]), ..Default::default() }) .await; match result { Ok(value) => println!("{value:?}"), Err(dodopayments::Error::Api { status, message }) => { eprintln!("API returned {status}: {message}"); } Err(err) => eprintln!("request failed: {err}"), } ``` ## Undocumented Endpoints To call an endpoint that has no typed method, use the low-level `request` builder. It applies authentication and the base URL. To name `reqwest::Method`, add `reqwest` 0.12 to your dependencies: ```rust theme={null} let response = client .request(reqwest::Method::GET, "/some/path") .send() .await?; ``` ## Resources > [card] [GitHub Repository](https://github.com/dodopayments/dodopayments-rust) > > Source code, releases, and the full method list. > [card] [Crates.io](https://crates.io/crates/dodopayments) > > The published crate and its versions. > [card] [API Reference](/api-reference/introduction) > > Every endpoint, parameter, and response. > [card] [Discord Community](https://discord.gg/bYqAp4ayYh) > > Ask questions and talk with other developers. ## Support For help with the Rust SDK: * **Discord**: Join the [community server](https://discord.gg/bYqAp4ayYh) for real-time help. * **Email**: Contact [support@dodopayments.com](mailto:support@dodopayments.com). * **GitHub**: Open an issue on the [repository](https://github.com/dodopayments/dodopayments-rust/issues). ## Contributing To contribute, read the [contributing guidelines](https://github.com/dodopayments/dodopayments-rust/blob/main/CONTRIBUTING.md). # Seat-Based Pricing with Add-ons and Payment Links Source: https://docs.dodopayments.com/developer-resources/seat-based-pricing Learn how to create add-ons for seat-based pricing and generate payment links with custom add-on quantities using Dodo Payments This tutorial shows how to implement seat-based pricing using Dodo Payments add-ons. You'll create a subscription product with add-ons for additional seats and generate payment links with custom add-on quantities. > [!NOTE] > > This tutorial uses Node.js and Express. You can adapt the code for your framework (Next.js, React, Vue, etc.) and customize the UI to match your application. By the end of this tutorial, you'll know how to: * Create subscription products with seat-based pricing * Set up add-ons for additional seats * Generate payment links with custom add-on quantities * Handle checkout sessions with dynamic seat counts ## What We're Building Let's create a seat-based pricing model: * **Base Plan**: \$49/month for up to 5 team members * **Seat Add-on**: \$2/month per additional seat * **Payment Links**: Dynamic checkout with custom seat quantities > [!NOTE] > > Before we start, make sure you have: > > * A Dodo Payments account > * Basic familiarity with TypeScript/Node.js ## Step 1: Create Your Seat Add-On Create an add-on that represents additional seats. This add-on will be attached to your base subscription and allow customers to purchase additional seats. ![Creating seat add-on in the dashboard](https://mintcdn.com/dodopayments/ajOhO6Du1yNsg0hy/images/cookbooks/seat-based/seat-based-addons-creation.png?fit=max\&auto=format\&n=ajOhO6Du1yNsg0hy\&q=85\&s=d2c17b4a9f2f9a1b19f537f0507656a4) > [!TIP] > > **What we're building**: An add-on that costs \$2/month per seat and can be added to any base subscription. **1. Navigate to Add-Ons** 1. In your Dodo Payments dashboard, stay in the **Products** section 2. Click on the **Add-Ons** tab 3. Click **Create Add-On** This will open the add-on creation form. **2. Enter add-on details** Fill in these values for our seat add-on: **Add-On Name**: `Additional Team Seat` **Description**: `Add extra team members to your workspace with full access to all features` **Price**: Enter → `2.00` **Currency**: Must match your base subscription currency **Tax Category**: Select appropriate category for your product. **3. Save your add-on** 1. Review all your settings: * Name: Additional Team Seat * Price: \$2.00/month 2. Click **Create Add-On** > [!TIP] > > **Add-on created!** Your seat add-on is now available to attach to subscriptions. ## Step 2: Create Your Base Subscription Product Create a base subscription product that includes 5 team members. This will be the foundation of your seat-based pricing model. ![Creating base subscription product in the dashboard](https://mintcdn.com/dodopayments/ajOhO6Du1yNsg0hy/images/cookbooks/seat-based/seat-based-subscription.png?fit=max\&auto=format\&n=ajOhO6Du1yNsg0hy\&q=85\&s=f17e96f3d106b88b6dc32a00be535620) **1. Navigate to Products** 1. Log into your Dodo Payments dashboard 2. Click on **Products** in the left sidebar 3. Click the **Create Product** button 4. Select **Subscription** as the product type You should see a form where we'll configure our base subscription. **2. Fill in the subscription details** Now we'll enter the specific details for our base plan: **Product Name**: `Motion` **Description**: `Where your team's documentation lives.` **Recurring Price**: Enter → `49.00` **Billing Cycle**: Select → `Monthly` **Currency**: Select your preferred currency (e.g., `USD`) ## Step 3: Connect Add-On to Subscription Associate your seat add-on with the base subscription so customers can purchase additional seats during checkout. **1. Attach the seat add-on** ![Attaching add-on to subscription in the dashboard](https://mintcdn.com/dodopayments/ajOhO6Du1yNsg0hy/images/cookbooks/seat-based/seat-based-addons.png?fit=max\&auto=format\&n=ajOhO6Du1yNsg0hy\&q=85\&s=ea4ce0d437201c92590eea6c31a14e80) 1. Scroll down to the **Add-Ons** section 2. Click **Add Add-Ons** 3. From the dropdown, select your seat add-on 4. Confirm that it appears in your subscription configuration **2. Save subscription changes** 1. Review your complete subscription setup: * Base plan: \$49/month for 5 seats * Add-on: \$2/month per additional seat 2. Click **Save Changes** > [!TIP] > > **Seat-based pricing configured!** Customers can now purchase your base plan and add extra seats as needed. ## Step 4: Generate Payment Links with Custom Add-on Quantities Create an Express.js application that generates payment links with custom add-on quantities. This lets you dynamically create checkout sessions with any number of additional seats. **1. Set up your project** Create a new Node.js project and install the required dependencies: ```bash theme={null} mkdir seat-based-pricing cd seat-based-pricing npm init -y npm install dodopayments express dotenv npm install -D @types/node @types/express typescript ts-node ``` Create a `tsconfig.json` file: ```json theme={null} { "compilerOptions": { "target": "ES2020", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true } } ``` **2. Create your environment file** Create a `.env` file with your Dodo Payments API key: ```bash theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... ``` > [!WARNING] > > Never commit your API key to version control. Add `.env` to your `.gitignore` file. **3. Implement the checkout session creation** Create a `src/server.ts` file with the following code: ```typescript server.ts expandable theme={null} // Add this new endpoint for dynamic seat quantities import 'dotenv/config'; import DodoPayments from 'dodopayments'; import express, { Request, Response } from 'express'; const app = express(); // Initialize the Dodo Payments client const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: 'test_mode' }); async function createCheckoutSession(seatCount: number) { try { const session = await client.checkoutSessions.create({ // Products to sell - use IDs from your Dodo Payments dashboard product_cart: [ { product_id: 'pdt_7Rl9OWT2Mz4wwUTKz74iZ', // Replace with your actual product ID quantity: 1, addons: [ { addon_id: 'adn_eKQbNakKrivDpaxmI8wKI', // Replace with your actual addon ID quantity: seatCount } ] } ], // Pre-fill customer information to reduce friction customer: { email: 'steve@example.com', name: 'Steve Irwin', }, // Where to redirect after successful payment return_url: 'https://example.com/checkout/success', }); // Redirect your customer to this URL to complete payment console.log('Checkout URL:', session.checkout_url); console.log('Session ID:', session.session_id); return session; } catch (error) { console.error('Failed to create checkout session:', error); throw error; } } // Example usage in an Express.js route app.post('/create-checkout/:seatCount', async (req: Request, res: Response) => { try { const seatCount = parseInt(req.params.seatCount); const session = await createCheckoutSession(seatCount); // Demo pricing from this tutorial: $49 base + $2 per additional seat res.json({ checkout_url: session.checkout_url, total_cost: 49 + seatCount * 2 }); } catch (error) { res.status(500).json({ error: 'Failed to create checkout session' }); } }); // Add this line after your other middleware app.use(express.static('public')); // Add this route to serve the demo page app.get('/', (req, res) => { res.sendFile(__dirname + '/../public/index.html'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); ``` **4. Add a simple web interface** Create a `public/index.html` file for easy testing: ```html index.html expandable theme={null} Seat-Based Pricing Demo

Seat-Based Pricing Demo

Generate checkout links with custom seat quantities:

``` > [!TIP] > > **Web interface created!** You now have a simple UI to test different seat quantities. **5. Serve static files** Add this to your `src/server.ts` to serve the HTML file: ```typescript theme={null} // Add this line after your other middleware app.use(express.static('public')); // Add this route to serve the demo page app.get('/', (req, res) => { res.sendFile(__dirname + '/../public/index.html'); }); ``` > [!TIP] > > **Static files configured!** Visit `http://localhost:3000` to see your demo interface. ## Step 5: Test Your Implementation Let's test our seat-based pricing implementation to make sure everything works correctly. **1. Start your server** 1. Make sure you have your `.env` file with the correct API key 2. Update the product and add-on IDs in your code with the actual values from your Dodo Payments dashboard 3. Start your server: ```bash theme={null} npx ts-node src/server.ts ``` > [!TIP] > > Your server should start successfully and show "Server is running on port 3000" **2. Test the web interface** ![Seat-based pricing demo interface](https://mintcdn.com/dodopayments/ajOhO6Du1yNsg0hy/images/cookbooks/seat-based/seat-based-billing-ui.png?fit=max\&auto=format\&n=ajOhO6Du1yNsg0hy\&q=85\&s=37d166d8e76b0bfbb4959bc9a3eff1f8) 1. Open your browser and go to `http://localhost:3000` 2. You should see the seat-based pricing demo interface 3. Try different seat quantities (0, 3, 10, etc.) 4. Click "Generate Checkout Link" for each quantity 5. Verify that the checkout URLs are generated correctly **3. Test a checkout session** 1. Generate a checkout link with 3 additional seats 2. Click the checkout URL to open the Dodo Payments checkout 3. Verify that the checkout shows: * Base plan: \$49/month * Additional seats: 3 × 2 dollars = \$6/month 4. Complete the test purchase > [!TIP] > > The checkout should display the correct pricing breakdown and allow you to complete the purchase. **4. Listen for webhooks and update your database** Keep your database in sync with subscription and seat changes by listening for webhook events from Dodo Payments. Webhooks notify your backend when a customer completes checkout, updates their subscription, or changes seat counts. Follow the official Dodo Payments webhooks guide for step-by-step instructions on setting up webhook endpoints and handling events: > [card] [Dodo Payments Webhooks Documentation](/developer-resources/webhooks) > > Learn how to securely receive and process webhook events for subscription and seat management. ## Troubleshooting Common issues and their solutions: > [accordion] Checkout creation failing > > **Possible causes:** > > * Invalid product ID or add-on ID > * API key doesn't have sufficient permissions > * Add-on not properly associated with subscription > * Network connectivity issues > > **Solutions:** > > 1. Verify product and add-on IDs exist in your Dodo Payments dashboard > 2. Check that add-on is properly attached to the subscription > 3. Ensure API key has checkout session creation permissions > 4. Test API connectivity with a simple GET request ## Congratulations! You've Implemented Seat-Based Pricing You've successfully created a seat-based pricing system with Dodo Payments. Here's what you accomplished: > [card] Base Subscription > > Created a subscription product with 5 included seats at \$49/month > [card] Seat Add-ons > > Configured add-ons for additional seats at \$2/month per seat > [card] Checkout > > Built an API that generates checkout sessions with custom seat quantities > [card] Web Interface > > Created a simple web interface for testing different seat quantities > [!NOTE] > > This example demonstrates a minimal implementation of seat-based pricing. For production use, add error handling, authentication, data validation, security measures, and adapt the logic to fit your application's requirements. # Subscription Integration Guide Source: https://docs.dodopayments.com/developer-resources/subscription-integration-guide Dodo Payments subscriptions let you charge customers on a recurring schedule. Create subscriptions through checkout sessions, handle webhooks, change plans with proration, and recover failed renewals. ## Prerequisites Before you start, you need: * A Dodo Payments merchant account * An API key from **Developer → API Keys** in the dashboard, stored in `DODO_PAYMENTS_API_KEY` * A webhook secret from **Developer → Webhooks**, stored in `DODO_PAYMENTS_WEBHOOK_KEY` * At least one subscription product created under **Products** For more details, see [Integration Guide Prerequisites](/developer-resources/integration-guide#prerequisites). ## API Integration ### Checkout Sessions Create a subscription by building a checkout session with your subscription product. The customer authorizes a payment method and the subscription activates when they complete checkout. > [!TIP] > > You can combine a subscription product with one-time products in the same checkout session. This enables setup fees, hardware bundles with SaaS, and similar use cases. See [Checkout Sessions](/developer-resources/checkout-session) for examples. > > You can also sell two or more subscription products in one checkout. The customer pays once and gets one independent subscription per product, each with its own billing cycle. Such a cart can't hold one-time products. See [Multi-Subscription Cart](/developer-resources/checkout-session#multi-subscription-cart). > [!WARNING] > > If the subscription period equals the payment frequency, the subscription expires after one charge. Read [Key Things to Know About Subscription Billing](#key-things-to-know-about-subscription-billing) before writing any subscription code. > [tab] Node.js SDK > > ```javascript theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', // defaults to 'live_mode' > }); > > async function main() { > const session = await client.checkoutSessions.create({ > product_cart: [ > { product_id: 'pdt_subscription_monthly', quantity: 1 } > ], > // Optional: configure trials for subscription products > subscription_data: { trial_period_days: 14 }, > customer: { > email: 'subscriber@example.com', > name: 'Jane Doe', > }, > return_url: 'https://example.com/success', > }); > > console.log(session.checkout_url); > } > > main(); > ``` > [tab] Python SDK > > ```python theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), > environment="test_mode", # defaults to "live_mode" > ) > > session = client.checkout_sessions.create( > product_cart=[ > {"product_id": "pdt_subscription_monthly", "quantity": 1} > ], > subscription_data={"trial_period_days": 14}, # optional > customer={ > "email": "subscriber@example.com", > "name": "Jane Doe", > }, > return_url="https://example.com/success", > ) > > print(session.checkout_url) > ``` > [tab] REST API > > ```javascript theme={null} > const response = await fetch('https://test.dodopayments.com/checkouts', { > method: 'POST', > headers: { > 'Content-Type': 'application/json', > 'Authorization': `Bearer ${process.env.DODO_PAYMENTS_API_KEY}` > }, > body: JSON.stringify({ > product_cart: [ > { product_id: 'pdt_subscription_monthly', quantity: 1 } > ], > subscription_data: { trial_period_days: 14 }, // optional > customer: { > email: 'subscriber@example.com', > name: 'Jane Doe' > }, > return_url: 'https://example.com/success' > }) > }); > > if (!response.ok) { > throw new Error(`HTTP error! status: ${response.status}`); > } > > const session = await response.json(); > console.log(session.checkout_url); > ``` ### API Response The response includes a `checkout_url`: ```json theme={null} { "session_id": "cks_Gi6KGJ2zFJo9rq9Ukifwa", "checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa" } ``` Redirect the customer to this URL. They authorize the payment method and the subscription activates. ### Webhooks Webhooks notify your server when subscription events occur. Set up your endpoint under **Developer → Webhooks** in the dashboard. To set up your webhook endpoint, see [Webhooks](/developer-resources/integration-guide#webhooks). #### Subscription Event Types Track these events to manage the subscription lifecycle: 1. **`subscription.active`** — Subscription is activated 2. **`subscription.updated`** — A field on the subscription changed 3. **`subscription.on_hold`** — A renewal or plan-change charge failed 4. **`subscription.failed`** — Subscription creation failed (terminal; customer must resubscribe) 5. **`subscription.renewed`** — A recurring charge succeeded 6. **`subscription.past_due`** — A renewal failed and the grace period started; the customer keeps access until `past_due_ends_at` 7. **`subscription.plan_changed`** — The plan was upgraded, downgraded, or changed 8. **`subscription.cancelled`** — The subscription was cancelled 9. **`subscription.expired`** — The subscription reached the end of its term These are the core events. For the full list, including `paused`, `unpaused`, and `update_payment_method`, see [Subscription Webhooks](/developer-resources/webhooks/intents/subscription). > [!TIP] > > Use `subscription.updated` to get real-time notifications about any subscription changes, keeping your application state in sync without polling the API. #### Payment Scenarios **Successful Payment Flow** The webhook sequence depends on whether the subscription has a trial. *Immediate billing (0 trial days):* 1. `subscription.active`: the mandate is authorized and the subscription is activated. 2. `payment.succeeded`: confirms the first charge. Expect this within **2–10 minutes** of checkout. *With a trial period:* 1. **At trial start (checkout):** `subscription.active` fires once the payment method is authorized. **No recurring charge is taken yet.** The first real charge is deferred until the trial ends. 2. **At trial end:** the recurring amount is charged, and you receive `payment.succeeded` **together with** `subscription.renewed`. *Every subsequent renewal:* * `subscription.renewed`: fires on each billing cycle when the renewal payment is deducted, **always alongside** `payment.succeeded`. It also carries the updated `next_billing_date`, and `payment_id`, the ID of the payment that renewed the subscription. `payment_id` is `null` on every other subscription event, and in the rare case that the renewal payment can't be matched. To see what a payment pays for, read these fields on the payment (in `GET /payments/{payment_id}`, `GET /payments`, and the `payment.*` webhooks): | Field | Description | | - | - | | `charge_type` | The type of subscription charge: `new` (the first payment of one or more subscriptions, and its retries), `renewal` (a charge at the billing date, including dunning and manual retries), `plan_change` (a charge for a plan change, now or at the next billing date), or `on_demand` (an on-demand charge). It is set for each payment status, and it is `null` when the payment charges no subscription, for example a one-time purchase or a payment method update. | | `service_periods` | One entry for each subscription period that the payment pays for, with the `subscription_id`, `starts_at`, `ends_at`, and `proration_factor`. The list is set for `new`, `renewal`, and `plan_change` charges that succeeded. It can be empty for some zero-amount payments. | | `service_periods[].proration_factor` | The part of one full billing period that the plan charge pays for, as a string. `"1"` is a full period. A value less than 1 is a partial period, for example after a plan change that keeps the billing cycle. For a plan change, this is the value of the new plan; the credit for the old plan is not in this value. | | `includes_usage` | `true` when the payment also bills metered usage or credit overage. The usage is for the billing cycle before the service period, not for the service period. It is `false` when `charge_type` is `null`. | > [!WARNING] > > A `renewal` payment does not always extend access. For example, the usage settlement of a paused subscription is a `renewal` with `includes_usage` set to `true` and no entry in `service_periods`. Check `service_periods` before you extend access. > [!NOTE] > > Whenever money is actually deducted for a subscription product, you get `subscription.renewed` **and** `payment.succeeded`. Use `subscription.renewed` (rather than `payment.succeeded` alone) as your signal to extend access for the next cycle. **Payment Failure Scenarios** 1. Subscription Failure * `subscription.failed` - Subscription creation failed due to failure to create a mandate. * `payment.failed` - Indicates failed payment. 2. Subscription On Hold * `subscription.on_hold` - Subscription is put on hold due to failed renewal payment or failed plan change charge. If your business has a grace period, a failed renewal first moves the subscription to `past_due` (`subscription.past_due`), and it moves to `on_hold` (or `cancelled`, depending on your grace period settings) only when the grace period ends. See [Subscription States](/features/subscription). * When a subscription goes on hold, it will not renew automatically until the payment method is updated. > [!NOTE] > > **Best Practice**: To simplify implementation, we recommend primarily tracking subscription events for managing the subscription lifecycle. > [!TIP] > > For a complete walkthrough of reading `error_code`/`error_message`, deciding when to retry, and surfacing failures to customers, see [Handle Payment Failures](/developer-resources/handle-payment-failures). #### `subscription.failed` vs. `subscription.on_hold` These two events are easy to confuse, but they require very different handling: | Event | When it fires | Status | Recoverable? | What to do | | - | - | - | - | - | | `subscription.failed` | The **initial** mandate could not be created at subscription **creation** | `failed` | **No (terminal)** | Do not grant access. Ask the customer to start a **new** subscription with a different payment method. | | `subscription.on_hold` | A **renewal** payment (or plan-change charge) failed on an already-active subscription | `on_hold` | **Yes** | Recover by updating the payment method; see [Handling Subscription On Hold](#handling-subscription-on-hold) below. | > [!WARNING] > > `subscription.failed` is terminal. The subscription cannot be reactivated. The customer must create a new subscription. Never grant entitlements when this event fires. ### Handling Subscription On Hold When a subscription enters `on_hold` state, you need to update the payment method to reactivate it. This section explains when subscriptions go on hold and how to handle them. #### When Subscriptions Go On Hold A subscription is placed on hold when: * **Renewal payment fails**: The automatic renewal charge fails due to insufficient funds, expired card, or bank decline * **Plan change charge fails**: An immediate charge during plan upgrade/downgrade fails * **Payment method authorization fails**: The payment method cannot be authorized for recurring charges > [!WARNING] > > Subscriptions in `on_hold` state will not renew automatically. You must update the payment method to reactivate the subscription. #### Reactivating Subscriptions from On Hold To reactivate a subscription from `on_hold` state, use the Update Payment Method API. This automatically: 1. Creates a charge for remaining dues 2. Generates an invoice for the charge 3. Processes the payment using the new payment method 4. Reactivates the subscription to `active` state upon successful payment **1. Handle subscription.on\_hold webhook** When you receive a `subscription.on_hold` webhook, update your application state and notify the customer: ```javascript theme={null} // Webhook handler app.post('/webhooks/dodo', async (req, res) => { const event = req.body; if (event.type === 'subscription.on_hold') { const subscription = event.data; // Update subscription status in your database await updateSubscriptionStatus(subscription.subscription_id, 'on_hold'); // Notify customer to update payment method await sendEmailToCustomer(subscription.customer.customer_id, { subject: 'Payment Required - Subscription On Hold', message: 'Your subscription is on hold. Please update your payment method to continue service.' }); } res.json({ received: true }); }); ``` **2. Update payment method** When the customer is ready to update their payment method, call the Update Payment Method API: ```javascript Node.js theme={null} // Update with new payment method const response = await client.subscriptions.updatePaymentMethod(subscriptionId, { payment_method: { type: 'new', return_url: 'https://example.com/return' } }); // For on_hold subscriptions, a charge is automatically created if (response.payment_id) { console.log('Charge created for remaining dues:', response.payment_id); // Redirect customer to response.payment_link to complete payment } ``` ```python Python theme={null} # Update with new payment method response = client.subscriptions.update_payment_method( subscription_id=subscription_id, payment_method={"type": "new", "return_url": "https://example.com/return"}, ) # For on_hold subscriptions, a charge is automatically created if response.payment_id: print("Charge created for remaining dues:", response.payment_id) # Redirect customer to response.payment_link to complete payment ``` > [!NOTE] > > You can also use an existing payment method ID if the customer has saved payment methods: > > ```javascript theme={null} > await client.subscriptions.updatePaymentMethod(subscriptionId, { > payment_method: { type: 'existing', payment_method_id: 'pm_abc123' } > }); > ``` **3. Monitor webhook events** After updating the payment method, monitor for these webhook events: 1. **`payment.succeeded`** - The charge for remaining dues was successful 2. **`subscription.active`** - The subscription has been reactivated ```javascript theme={null} if (event.type === 'payment.succeeded') { const payment = event.data; // Check if this payment is for an on_hold subscription if (payment.subscription_id) { // Wait for subscription.active webhook to confirm reactivation } } if (event.type === 'subscription.active') { const subscription = event.data; // Update subscription status in your database await updateSubscriptionStatus(subscription.subscription_id, 'active'); // Restore customer access await restoreCustomerAccess(subscription.customer.customer_id); // Notify customer of successful reactivation await sendEmailToCustomer(subscription.customer.customer_id, { subject: 'Subscription Reactivated', message: 'Your subscription has been reactivated successfully.' }); } ``` ### Sample Subscription Event Payload *** | Property | Type | Required | Description | | - | - | - | - | | `business_id` | string | Yes | The unique identifier for the business | | `timestamp` | string | Yes | The timestamp of when the event occurred (not necessarily the same as when it was delivered) | | `type` | string | Yes | The type of event. See [Subscription Event Types](#subscription-event-types) | | `data` | object | Yes | The main data payload. See [Subscription webhook payloads](/developer-resources/webhooks/intents/subscription) | ## Changing Subscription Plans You can upgrade or downgrade a subscription plan using the change plan API endpoint. This allows you to modify the subscription's product, quantity, and handle proration. > [card] [Change Plan API Reference](/api-reference/subscriptions/change-plan) > > For detailed information about changing subscription plans, please refer to our Change Plan API documentation. ### Proration Options When changing subscription plans, you have five options for handling the immediate charge: #### 1. `prorated_immediately` * Credits the unused portion of the current billing cycle, prorated by the time remaining. The credit covers the base plan, quantity, and any add-ons * Then charges a **full** cycle at the new plan, quantity, and add-ons. The charge itself is never prorated * Net immediate charge = (full new cycle) minus (remaining fraction x full old cycle). If the credit is larger, the difference is held as subscription-scoped credit for future renewals * During a trial period, this will immediately switch the user to the new plan, charging the customer right away #### 2. `prorated_immediately_keep_cycle` * Charges the price difference between the new and old plan for the time left in the current billing cycle. The difference covers the base plan, quantity, and add-ons * The **billing date is preserved**. The new plan price applies from the next renewal * On a downgrade, the price difference for the time left goes to the [customer wallet](/features/customer-wallet) as credit * Needs `effective_at: immediately`. A change to a shorter billing interval returns `422`. A change to a longer billing interval runs as `prorated_immediately` * See the [Upgrade & Downgrade Guide](/developer-resources/subscription-upgrade-downgrade#prorated_immediately_keep_cycle) for trial behavior and all rules #### 3. `full_immediately` * Charges the customer the full subscription amount for the new plan with no credit for the previous cycle * On upgrade or downgrade alike, the customer pays the entire new plan price from scratch * Useful when you want to charge the full amount regardless of how much time was left on the old plan #### 4. `difference_immediately` * The customer pays only the gap between the old plan price and the new plan price * The amount does not depend on when in the cycle the change is made. The same upgrade costs the same on day 1 and on day 29 * When upgrading, the customer is immediately charged the difference. For example, \$30/month → \$80/month = \$50 charged instantly * When downgrading, the price difference is stored as subscription-scoped credit and applied automatically to future renewals. For example, \$50/month → \$20/month = \$30 stored as credit #### 5. `do_not_bill` * Applies the plan change immediately but does **not** charge anything at the time of the change. The new plan, quantity, and add-ons are usable straight away * Because nothing is charged now, an **upgrade** gives the customer the higher plan free for the remainder of the current cycle. A **downgrade** takes effect immediately with no credit for the unused portion of the cycle they have already paid for * Add-ons granted through `do_not_bill` are not credited on a later plan change, because they were never billed. A subsequent change bills the new add-on quantity in full * The updated plan (and quantity/add-ons) is billed at the **next scheduled renewal**, and the **original billing date is preserved** > [!WARNING] > > **Three "charge now" modes reset the billing cycle.** `prorated_immediately`, `difference_immediately`, and `full_immediately` move the subscription's `next_billing_date` to the change date. `prorated_immediately_keep_cycle` charges now and keeps the original renewal date. `do_not_bill` also keeps the original renewal date, but it applies no immediate charge. ### Behavior * When you invoke this API, Dodo Payments immediately initiates a charge based on your selected proration option * With `prorated_immediately`, a credit for the unused portion of the current cycle is calculated on every change, upgrade or downgrade alike. If that credit exceeds the new cycle charge, the remainder is added to the subscription's credit balance. These credits are specific to that subscription and will only be used to offset future recurring payments of the same subscription * With `difference_immediately`, the net is always the exact price difference. For downgrades, the excess is stored as subscription-scoped credit, the same as `prorated_immediately` * With `prorated_immediately_keep_cycle`, the charge is the price difference for the time left in the current cycle, and the renewal date is preserved. For downgrades, the credit goes to the [customer wallet](/features/customer-wallet) * The `full_immediately` option bypasses credit calculations and charges the complete new plan amount * The `do_not_bill` option applies the change immediately but defers billing to the next renewal date, which is preserved > [!TIP] > > **Choosing a proration mode:** > > * **`difference_immediately`** — customer pays the price difference. The most predictable option; the charge is the same regardless of when in the cycle the change is made. > * **`prorated_immediately`** — customer is credited only for unused time on the current cycle. The charge varies depending on when in the cycle the change happens. > * **`prorated_immediately_keep_cycle`** — customer pays the price difference for the time left in the current cycle. The original billing date is preserved. > * **`full_immediately`** — customer pays the full new plan amount. No credit for the previous cycle. > * **`do_not_bill`** — no charge now. The new plan is billed at the next renewal. The original billing date is preserved. ### Charge Processing * The immediate charge initiated upon plan change usually completes processing in less than 2 minutes * If this immediate charge fails for any reason, the subscription is automatically placed on hold until the issue is resolved ## On-Demand Subscriptions > [!NOTE] > > On-demand subscriptions let you charge customers flexibly, not just on a fixed schedule. This feature is available for all accounts. **To create an on-demand subscription:** To create an on-demand subscription, use the [POST /checkouts](/api-reference/checkout-sessions/create) API endpoint and include the `subscription_data.on_demand` field in your request body. This allows you to authorize a payment method without an immediate charge, or set a custom initial price. > [!WARNING] > > `POST /subscriptions` is **deprecated**. It still works for existing integrations, but new integrations should create on-demand subscriptions through a [Checkout Session](/developer-resources/checkout-session) (`POST /checkouts`) with `subscription_data.on_demand`. See the [On-Demand Subscriptions Guide](/developer-resources/ondemand-subscriptions) for the current flow. **To charge an on-demand subscription:** For subsequent charges, use the [POST /subscriptions//charge](/api-reference/subscriptions/create-charge) endpoint and specify the amount to charge the customer for that transaction. > [!NOTE] > > For a complete, step-by-step guide (including request/response examples, safe retry policies, and webhook handling), see the [On-Demand Subscriptions Guide](/developer-resources/ondemand-subscriptions). ## Key Things to Know About Subscription Billing > [!WARNING] > > **Set the subscription period longer than the payment frequency.** If the subscription period equals the payment frequency (e.g. period = 1 month, frequency = 1 month), the subscription is valid for a **single cycle** and then moves to `expired` instead of renewing. For an ongoing monthly plan, set a long subscription period (e.g. 20 years) with a monthly payment frequency. > [!WARNING] > > **Currency locks at the first successful charge.** Always pass `billing_currency` **and** `billing_address.country` explicitly when creating the checkout. If omitted, they're detected from the customer's IP (Adaptive Currency), and once the subscription takes its first charge the currency is fixed for its lifetime. A customer who later travels can't switch it. > [!NOTE] > > **Trials take a \$0 authorization, not a charge.** When a subscription has a trial, the trial start creates a **\$0 mandate authorization** to save the card; the first real charge happens when the trial ends. In the payments list, a subscription in a free trial shows exactly one payment with `total_amount` of 0. A paid trial charges its `trial_amount` upfront instead. > [!NOTE] > > **Subscription lifecycle:** `past_due` = a renewal failed and the grace period is running (the customer keeps access). `on_hold` = a renewal failed (recoverable: prompt the customer to update their payment method; dunning retries apply). `expired` = the term ended without renewal and **cannot be reactivated**. The customer must resubscribe. `cancelled` = ended by the customer or merchant. Most renewal failures are **issuer-side declines** (insufficient funds, card declined), not a Dodo error. > [!WARNING] > > **Indian cards run on an RBI e-mandate.** Off-session charges (renewals and plan-change charges) can take **up to \~48 hours** to settle, and recurring auto-debits **above ₹15,000** require fresh customer authentication (so an upgrade crossing that limit can't ride the existing mandate). While one charge is still `processing`, a second charge on the same subscription fails with *"Cannot create new charge as previous payment is not successful yet."* Non-Indian cards confirm near-instantly. > [!TIP] > > **Subscriptions have a \$1.00 minimum in USD.** Checkout rejects a lower total with `TOTAL_PAYMENT_AMOUNT_BELOW_MINIMUM_AMOUNT`. Currencies other than USD, EUR, and GBP must also be worth at least \$1.00; see [Minimum Amounts](/features/adaptive-currency#minimum-amounts). An on-demand charge `product_price` below `100` in the smallest currency unit is rejected with `product_price: value out of range`. A subscription product priced at exactly `$0` is allowed; see [Card-Optional at Zero Price](/features/subscription#card-optional-at-zero-price). To authorize a card without charging it, use an on-demand `mandate_only` setup. ## Related API Reference > [card] [Create Subscription (Deprecated)](/api-reference/subscriptions/post-subscriptions) > > Legacy API for creating a subscription directly. Use Checkout Sessions for new integrations > [card] [Change Subscription Plan](/api-reference/subscriptions/change-plan) > > API reference for upgrading, downgrading, or changing subscription plans with proration options > [card] [Update Payment Method](/api-reference/subscriptions/update-payment-method) > > API reference for updating payment methods and reactivating on-hold subscriptions > [card] [Patch Subscription](/api-reference/subscriptions/patch-subscriptions) > > API reference for updating subscription details and configuration # Subscription Upgrade & Downgrade Guide Source: https://docs.dodopayments.com/developer-resources/subscription-upgrade-downgrade Learn how to change a customer's subscription plan, handle proration, and process webhooks reliably. > [card] [Change Plan API](/api-reference/subscriptions/change-plan) > > Full API docs for updating subscriptions. > [card] [Plan Change Preview](/api-reference/subscriptions/preview-change-plan) > > See charge amounts before changing plans. > [card] [Integration Guide](/developer-resources/subscription-integration-guide) > > Step-by-step subscription setup. ## What Is a Subscription Upgrade or Downgrade? Change a customer's subscription plan to move them between tiers, adjust quantity for seat-based products, or migrate to a new product. The API automatically calculates prorations and charges based on your chosen billing mode. > [!NOTE] > > Plan changes can trigger an immediate charge depending on the proration mode you choose. ## When to Use Plan Changes * Upgrade when a customer needs more features, usage, or seats * Downgrade when usage decreases * Migrate users to a new product or price without cancelling their subscription ## Plan Change Flow ```mermaid theme={null} sequenceDiagram participant C as Customer participant A as Your App participant D as Dodo Payments C->>A: Request plan change A->>D: Preview change D-->>A: Charge breakdown A->>C: Show cost details C->>A: Confirm A->>D: Change plan API call D->>D: Prorate & charge D-->>A: Result + invoice D->>A: Webhooks (payment, plan_changed) A->>C: Plan updated ``` ## Prerequisites Before implementing subscription plan changes, ensure you have: * A Dodo Payments merchant account with active subscription products * API credentials (API key and webhook secret key) from the dashboard * An existing active subscription to modify * Webhook endpoint configured to handle subscription events > [!NOTE] > > For detailed setup instructions, see the [Integration Guide](/developer-resources/subscription-integration-guide). ## Step-by-Step Implementation Guide Follow this comprehensive guide to implement subscription plan changes in your application: **1. Understand Plan Change Requirements** Before implementing, determine: * Which subscription products can be changed to which others * What proration mode fits your business model * How to handle failed plan changes gracefully * Which webhook events to track for state management > [!TIP] > > Test plan changes thoroughly in test mode before implementing in production. **2. Choose Your Proration Strategy** Select the billing approach that aligns with your business needs: > [tab] prorated\_immediately > > Best for: SaaS applications that want to credit unused time on the old plan. > > * Credits the unused portion of the current cycle, prorated by time remaining > * Then charges a **full** cycle at the new plan — the new plan price is never prorated > * Net charge = full new cycle − (remaining fraction × full old cycle) > [tab] prorated\_immediately\_keep\_cycle > > Best for: Mid-cycle changes when all customers renew on a fixed billing date. > > * Charges the price difference for the time left in the current cycle > * Downgrade: Credits the price difference for the time left > * Billing date remains unchanged > [tab] difference\_immediately > > Best for: Clear upgrade/downgrade scenarios. > > * Upgrade: Charge immediate difference (e.g., \$30→\$80 = charge \$50) > * Downgrade: Credit remaining value for future renewals > * Simplifies billing logic and customer communication > [tab] full\_immediately > > Best for: When you want to reset the billing cycle. > > * Charges full amount of new plan immediately > * Ignores remaining time from old plan > * Useful for annual to monthly transitions > [tab] do\_not\_bill > > Best for: Free migrations, courtesy switches, or absorbing cost differences. > > * No charges or credits calculated > * Customer moves to the new plan immediately without any billing adjustment > * Billing cycle remains unchanged **3. Implement the Change Plan API** Use the Change Plan API to modify subscription details: **subscription\_id** `string` *required* The ID of the active subscription to modify. **product\_id** `string` *required* The new product ID to change the subscription to. **quantity** `integer` *required* Number of units for the new plan (for seat-based products). **proration\_billing\_mode** `string` *required* How to handle immediate billing: `prorated_immediately`, `prorated_immediately_keep_cycle`, `full_immediately`, `difference_immediately`, or `do_not_bill`. **addons** `array` Optional addons for the new plan. Omitting this field, sending `null`, or sending an empty array removes any existing addons, so include current addons to keep them. **on\_payment\_failure** `string` Controls behavior when the plan change payment fails: * `prevent_change`: Keep subscription on current plan until payment succeeds * `apply_change` (default): Apply plan change immediately regardless of payment outcome If not specified, uses the business-level default setting. **collect\_via\_payment\_link** `boolean` Collect the plan-change amount with a payment link instead of charging the subscription's saved payment method. The customer pays on a hosted checkout page. Requires the business's `allow_plan_change_via_payment_link` capability (**Settings → Subscriptions → Collect Plan Change Payments by Payment Link**), `effective_at: immediately`, and `on_payment_failure: prevent_change`. See [Collecting Payment via a Checkout Link](#collecting-payment-via-a-checkout-link). Ignored by the preview route. **return\_url** `string` The URL that receives the customer after they pay the payment link. The redirect adds `subscription_id`, `payment_id`, and `status`. Requires `collect_via_payment_link: true`; otherwise the request fails with `422`. See [Redirecting the Customer After Payment](#redirecting-the-customer-after-payment). **cancel\_older\_payment\_link** `boolean` (default: false) Cancel the unpaid payment link of a pending plan change, so that this request replaces it. A paid or in-progress payment returns `409`. See [Replacing a Pending Payment Link](#replacing-a-pending-payment-link). Ignored by the preview route. **discount\_codes** `array` Optional **stacked** discount codes to apply to the new plan (max 20, applied in array order). Behavior depends on what you pass: * **Not provided / `null`** — existing discounts with `preserve_on_plan_change=true` are preserved if applicable to the new product. * **`[]` (empty array)** — removes all existing discounts from the subscription. * **`["CODE_A", "CODE_B", ...]`** — replaces any existing discounts with this stacked set. **discount\_code** `string` *deprecated* **Deprecated** — prefer `discount_codes` for new integrations. This field still works for backward compatibility, but cannot be combined with `discount_codes` in the same request. **effective\_at** `string` (default: immediately) When to apply the plan change: * `immediately` (default): Apply the plan change right away * `next_billing_date`: Schedule the change for the next billing date. The customer retains their current plan until the billing period ends. Use this for downgrades so customers keep their current plan benefits until the end of the billing period. **cancel\_scheduled\_change\_plan** `boolean` Replace an existing scheduled plan change with this one. The scheduled change is cancelled by the transaction that applies this change, so a change that never applies leaves the schedule in place. With `effective_at: next_billing_date`, the new schedule replaces the old one immediately. **4. Handle Webhook Events** Set up webhook handling to track plan change outcomes: * `subscription.active`: Plan change successful, subscription updated * `subscription.plan_changed`: Subscription plan changed (upgrade/downgrade/addon update) * `subscription.on_hold`: Plan change charge failed, renewals stopped * `payment.succeeded`: Immediate charge for plan change succeeded * `payment.failed`: Immediate charge failed > [!WARNING] > > Always verify webhook signatures and implement idempotent event processing. **5. Update Your Application State** Based on webhook events, update your application: * Grant/revoke features based on new plan * Update customer dashboard with new plan details * Send confirmation emails about plan changes * Log billing changes for audit purposes **6. Test and Monitor** Thoroughly test your implementation: * Test all proration modes with different scenarios * Verify webhook handling works correctly * Monitor plan change success rates * Set up alerts for failed plan changes > [!TIP] > > Your subscription plan change implementation is now ready for production use. ## Preview Plan Changes Before committing to a plan change, use the Preview API to show customers exactly what they'll be charged: > [tab] Node.js SDK > > ```javascript theme={null} > const preview = await client.subscriptions.previewChangePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'prorated_immediately' > }); > > // Show customer the charge before confirming > console.log('Immediate charge:', preview.immediate_charge.summary.total_amount, preview.immediate_charge.summary.currency); > console.log('New plan details:', preview.new_plan); > ``` > [tab] Python SDK > > ```python theme={null} > preview = client.subscriptions.preview_change_plan( > subscription_id="sub_123", > product_id="pdt_pro", > quantity=1, > proration_billing_mode="prorated_immediately" > ) > > # Show customer the charge before confirming > print("Immediate charge:", preview.immediate_charge.summary.total_amount, preview.immediate_charge.summary.currency) > print("New plan details:", preview.new_plan) > ``` > [!TIP] > > Use the preview API to build confirmation dialogs that show customers the exact amount they'll be charged before they confirm a plan change. > [!NOTE] > > In `immediate_charge.summary`, `customer_credits` is the net change to the customer's credit balance, in the currency given by `customer_credits_currency`. This is the currency of the customer's credit wallet, which is the subscription currency. It can differ from the summary's `currency`, which applies to `total_amount` and `tax`. For example, a customer paying in INR on a USD subscription sees credits in USD. ## Change Plan API Use the Change Plan API to modify product, quantity, and proration behavior for an active subscription. ### Quick Start Examples > [tab] Node.js SDK > > ```javascript theme={null} > import DodoPayments from 'dodopayments'; > > const client = new DodoPayments({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: 'test_mode', // defaults to 'live_mode' > }); > > async function changePlan() { > // change-plan returns 200 with a ChangePlanResponse body (payment_id, payment_link, > // client_secret, expires_on) — all null for an ordinary off-session change. > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_new', > quantity: 3, > proration_billing_mode: 'prorated_immediately', > on_payment_failure: 'prevent_change', // Optional: control behavior on payment failure > }); > console.log('Plan change accepted; awaiting webhooks'); > } > > changePlan(); > ``` > [tab] Python SDK > > ```python theme={null} > import os > from dodopayments import DodoPayments > > client = DodoPayments( > bearer_token=os.environ.get("DODO_PAYMENTS_API_KEY"), > environment="test_mode", # defaults to "live_mode" > ) > > # change_plan returns 200 with a ChangePlanResponse body (payment_id, payment_link, > # client_secret, expires_on) — all None for an ordinary off-session change. > client.subscriptions.change_plan( > subscription_id="sub_123", > product_id="pdt_new", > quantity=3, > proration_billing_mode="prorated_immediately", > on_payment_failure="prevent_change", # Optional: control behavior on payment failure > ) > print("Plan change accepted; awaiting webhooks") > ``` > [tab] Go SDK > > ```go theme={null} > package main > > import ( > "context" > "fmt" > "github.com/dodopayments/dodopayments-go" > "github.com/dodopayments/dodopayments-go/option" > ) > > func main() { > client := dodopayments.NewClient(option.WithBearerToken("dodo_test_...")) > // ChangePlan returns a SubscriptionChangePlanResponse alongside the error. > _, err := client.Subscriptions.ChangePlan(context.TODO(), "sub_123", dodopayments.SubscriptionChangePlanParams{ > UpdateSubscriptionPlanReq: dodopayments.UpdateSubscriptionPlanReqParam{ > ProductID: dodopayments.F("pdt_new"), > Quantity: dodopayments.F(int64(3)), > ProrationBillingMode: dodopayments.F(dodopayments.UpdateSubscriptionPlanReqProrationBillingModeProratedImmediately), > OnPaymentFailure: dodopayments.F(dodopayments.UpdateSubscriptionPlanReqOnPaymentFailurePreventChange), // Optional > }, > }) > if err != nil { panic(err) } > fmt.Println("Plan change applied") > } > ``` > [tab] HTTP > > ```bash theme={null} > curl -X POST "$DODO_API_BASE/subscriptions/sub_123/change-plan" \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_id": "pdt_new", > "quantity": 3, > "proration_billing_mode": "prorated_immediately", > "on_payment_failure": "prevent_change" > }' > ``` A successful plan change returns `200 OK` immediately — before any charge has actually settled. What the body (`ChangePlanResponse`) contains depends on how the change was collected: | Case | `payment_id` / `payment_link` / `client_secret` / `expires_on` | | - | - | | Scheduled change (`effective_at: next_billing_date`) | All `null` — nothing is charged yet | | `proration_billing_mode: do_not_bill` | All `null` — nothing to charge | | Ordinary immediate charge (saved payment method) | All `null` | | `collect_via_payment_link: true` (link issued) | All **populated** — checkout handles for the customer | > [!NOTE] > > This response confirms the request was accepted, not that a charge succeeded. For an ordinary immediate charge, the outcome resolves off-session right after the call. For a `collect_via_payment_link` request, the subscription stays on its current plan until the customer completes payment. > > Confirm the outcome via webhook (`payment.succeeded`, `payment.failed`, `subscription.plan_changed`) or by re-reading the subscription with `GET /subscriptions/{subscription_id}` — see [What Happens While the Link Is Unpaid](#what-happens-while-the-link-is-unpaid) for the payment-link case. > [!WARNING] > > If the immediate charge fails, the subscription may move to `on_hold` (emitting `subscription.on_hold`) until payment succeeds. ## Collecting Payment via a Checkout Link By default, an immediate plan change charges the subscription's saved payment method directly. Set `collect_via_payment_link: true` to send the customer to a hosted checkout page instead — useful when there's no saved payment method or you want the customer to actively confirm the new price. > [!NOTE] > > This powers the **Collect Plan Change Payments by Payment Link** toggle in **Settings → Subscriptions**, which routes the [Customer Portal](/features/customer-portal#collecting-plan-change-payments-by-payment-link)'s plan-change flow through checkout. ### Requirements `collect_via_payment_link: true` only succeeds when **all** of the following hold — otherwise the request fails with `422`: * The business has the `allow_plan_change_via_payment_link` capability enabled (**Settings → Subscriptions → Collect Plan Change Payments by Payment Link**). * `effective_at` is `immediately` (the default). A scheduled change (`next_billing_date`) never needs a checkout page. * The request sets `on_payment_failure: prevent_change`. An explicit `apply_change` fails with `422`. > [!NOTE] > > `collect_via_payment_link` applies to any immediate change that results in a charge, downgrades included, as long as the requirements above are met. If the change nets to zero or a credit, no payment link is issued: `payment_link` and the other checkout fields come back `null`, and the change applies immediately. This is not a `422`. Call [Preview Plan Change](/api-reference/subscriptions/preview-change-plan) first to check the amount before requesting a link. > [tab] Node.js SDK > > ```javascript theme={null} > const response = await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'prorated_immediately', > effective_at: 'immediately', > on_payment_failure: 'prevent_change', > collect_via_payment_link: true, > }); > > // Hand response.payment_link to your frontend and send the customer there > console.log(response.payment_link); > ``` > [tab] Python SDK > > ```python theme={null} > response = client.subscriptions.change_plan( > subscription_id="sub_123", > product_id="pdt_pro", > quantity=1, > proration_billing_mode="prorated_immediately", > effective_at="immediately", > on_payment_failure="prevent_change", > collect_via_payment_link=True, > ) > > # Hand response.payment_link to your frontend and send the customer there > print(response.payment_link) > ``` > [tab] HTTP > > ```bash theme={null} > curl -X POST "$DODO_API_BASE/subscriptions/sub_123/change-plan" \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_id": "pdt_pro", > "quantity": 1, > "proration_billing_mode": "prorated_immediately", > "effective_at": "immediately", > "on_payment_failure": "prevent_change", > "collect_via_payment_link": true > }' > ``` A successful request returns the checkout handles: ```json theme={null} { "payment_id": "", "payment_link": "https://checkout.dodopayments.com/...", "client_secret": "", "expires_on": "" } ``` ### What Happens While the Link Is Unpaid * The subscription stays on its **current** plan — `product_id`, `recurring_pre_tax_amount`, and `next_billing_date` are all untouched until the link is paid. * A further `change-plan` request is rejected with `409` `PENDING_PLAN_CHANGE_EXISTS` while the link is pending. To replace the pending change, send the new request with `cancel_older_payment_link: true`. See [Replacing a Pending Payment Link](#replacing-a-pending-payment-link). * To retry after a declined payment, call `change-plan` again to get a new link. * If the link is never paid, it stops working after `expires_on` — the subscription automatically becomes free to accept a new plan-change request shortly after. * If a scheduled change already existed and you replace it with `cancel_scheduled_change_plan: true`, the original schedule stays in place while the link is unpaid and is only cancelled once the link is paid — in the same transaction that applies the new plan. > [!WARNING] > > Once an immediate payment-link change is issued, every further plan-change request on that subscription — including the side-effect-free preview — is blocked until the link resolves. A `change-plan` request can replace the link by setting `cancel_older_payment_link: true`. The preview ignores this field, so a preview stays blocked. ### Redirecting the Customer After Payment Set `return_url` to send the customer back to your site after they pay the link: ```json theme={null} { "product_id": "pdt_pro", "quantity": 1, "proration_billing_mode": "prorated_immediately", "on_payment_failure": "prevent_change", "collect_via_payment_link": true, "return_url": "https://example.com/billing/done" } ``` After checkout, the customer goes to `return_url` with these query parameters: | Parameter | Value | | - | - | | `subscription_id` | The subscription that the plan change is for. | | `payment_id` | The plan-change payment. | | `status` | The status of the plan-change payment, not of the subscription: `active` when paid, `failed` when declined, `pending` while in progress. | When the payment fails, the subscription stays active on its current plan. The new plan can apply shortly after the redirect, when the payment webhook arrives, so read the subscription again before you show the new plan. `return_url` needs `collect_via_payment_link: true`. Without it, the request fails with `422`. ### Replacing a Pending Payment Link If the customer leaves the checkout without paying, set `cancel_older_payment_link: true` on the next `change-plan` request. Dodo Payments cancels the unpaid link, and the new plan change replaces the pending one. The cancelled link no longer accepts a payment, even in a checkout page that is already open. ```json theme={null} { "product_id": "pdt_pro", "quantity": 1, "proration_billing_mode": "prorated_immediately", "on_payment_failure": "prevent_change", "collect_via_payment_link": true, "cancel_older_payment_link": true } ``` The request is validated before the link is cancelled, so an invalid request keeps the customer's link. The link is cancelled only if the customer has not started to pay: | Previous payment | Response | | - | - | | Not opened, opened but not paid, or declined | `200` with the new link. | | Customer is paying now, for example during 3D Secure | `409` `PLAN_CHANGE_PAYMENT_IN_PROGRESS`. Retry after the payment completes or fails. | | Already paid | `409` `PLAN_CHANGE_PAYMENT_ALREADY_COMPLETED`. Don't retry: the previous plan change applies. | | The link could not be cancelled | `503` `PLAN_CHANGE_LINK_CANCEL_FAILED`. Nothing changed, so you can retry. | Each `change-plan` request issues its own invoice. The replaced plan change and its invoice are cancelled. If no plan change is pending, `cancel_older_payment_link` has no effect. > [!NOTE] > > A check that runs after validation, for example the minimum charge amount, can still fail after the link is cancelled. The subscription then stays on its current plan with no open link. Send the request again to issue a new link. ## Managing Addons When changing subscription plans, you can also modify addons: ```javascript theme={null} // Add addons to the new plan await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_new', quantity: 1, proration_billing_mode: 'difference_immediately', addons: [ { addon_id: 'addon_123', quantity: 2 } ] }); // Remove all existing addons await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_new', quantity: 1, proration_billing_mode: 'difference_immediately', addons: [] // Empty array removes all existing addons }); ``` > [!NOTE] > > Addons are included in the proration calculation and will be charged according to the selected proration mode. ## Applying Discount Codes Apply one or more stacked discount codes when changing subscription plans (max 20, applied in array order): > [tab] Node.js SDK > > ```javascript theme={null} > // Apply stacked discount codes during plan change > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'prorated_immediately', > discount_codes: ['UPGRADE20'] > }); > ``` > [tab] Python SDK > > ```python theme={null} > # Apply stacked discount codes during plan change > client.subscriptions.change_plan( > subscription_id="sub_123", > product_id="pdt_pro", > quantity=1, > proration_billing_mode="prorated_immediately", > discount_codes=["UPGRADE20"] > ) > ``` > [tab] HTTP > > ```bash theme={null} > curl -X POST "$DODO_API_BASE/subscriptions/sub_123/change-plan" \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_id": "pdt_pro", > "quantity": 1, > "proration_billing_mode": "prorated_immediately", > "discount_codes": ["UPGRADE20"] > }' > ``` ### Discount Behavior on Plan Change | `discount_codes` value | Behavior | | - | - | | Not provided / `null` | Existing discounts with `preserve_on_plan_change=true` are automatically preserved if applicable to the new product. | | `[]` (empty array) | **All** existing discounts are removed from the subscription. | | `["CODE_A", "CODE_B", ...]` | Replaces any existing discounts with this stacked set, validated and applied in array order. | > [!NOTE] > > The singular `discount_code` field on this endpoint is **deprecated** but still works for backward compatibility — existing integrations don't need to change immediately. It cannot be combined with `discount_codes` in the same request. Migrate to the array form when convenient. > [!TIP] > > Use the [Preview Plan Change API](/api-reference/subscriptions/preview-change-plan) with `discount_codes` to show customers exactly how much they'll save before confirming the plan change. ## Proration Modes Choose how to bill the customer when changing plans: #### `prorated_immediately` * Credits the unused portion of the current cycle — base plan, quantity, and add-ons — prorated by time remaining * Then charges a **full** cycle at the new plan, quantity, and add-ons. The charge itself is never prorated * Net immediate charge = (full new cycle) − (remaining fraction × full old cycle) * If the credit exceeds the new cycle charge (common on downgrades), the difference is held as subscription-scoped credit for future renewals * If in trial, charges immediately and switches to the new plan now #### `prorated_immediately_keep_cycle` * Charges the price difference between the new and old plan for the time left in the current cycle. This includes quantity and add-ons * Net immediate charge = (full new cycle − full old cycle) × remaining fraction * Keeps `next_billing_date`. The new plan price applies from that date * A downgrade or a seat decrease gives a credit for the same amount. The credit goes to the [customer wallet](/features/customer-wallet) * The remaining fraction uses the length of the current billing period. A second change in the same period uses the same period length * Credit entitlements: a change to a product that grants more credits grants the increase for the time left. A quantity change grants no new credits Rules for this mode: | Situation | Result | | - | - | | `effective_at: next_billing_date` | `422`. This mode needs `effective_at: immediately`. | | New plan has a longer billing interval, for example monthly to yearly | Runs as `prorated_immediately`. The billing date resets to the change date. | | New plan has a shorter billing interval, for example yearly to monthly | `422`. Use `full_immediately` with `effective_at: next_billing_date`. | | Subscription is in a free trial and the new plan has a trial | No charge. The trial end date stays the same. | | Subscription is in a trial and the new plan has no trial | Runs as `full_immediately`. The trial ends and the customer pays the full new plan price. A paid trial fee is not credited. | | `next_billing_date` is in the past, for example after a missed renewal | `422`. | > [!NOTE] > > Intervals are compared by calendar length, so 12 months and 1 year are the same interval. #### `full_immediately` * Charges the full amount of the new plan immediately * Ignores remaining time from the old plan — no credit for the current cycle > [!NOTE] > > Credits created by `prorated_immediately` and by downgrades using `difference_immediately` are subscription-scoped and distinct from [Credit-Based Billing](/features/credit-based-billing) entitlements. They automatically apply to future renewals of the same subscription and are not transferable between subscriptions. #### `difference_immediately` * Upgrade: immediately charge the price difference between old and new plans * Downgrade: add remaining value as internal credit to the subscription and auto-apply on renewals #### `do_not_bill` * No charges or credits are calculated * Customer switches to the new plan immediately without any billing adjustment * Billing cycle remains unchanged * Best for courtesy migrations, free plan switches, or absorbing cost differences | Feature | `prorated_immediately` | `prorated_immediately_keep_cycle` | `difference_immediately` | `full_immediately` | `do_not_bill` | | - | - | - | - | - | - | | **Upgrade charge** | Full new cycle, minus credit for unused time | Price difference for the time left | Full price difference between plans | Full new plan price | No charge | | **Downgrade credit** | Credit for unused time, minus a full new cycle | Price difference for the time left | Full price difference as credit | No credit | No credit | | **Billing cycle** | Resets to today | Unchanged | Resets to today | Resets to today | Unchanged | | **Trial behavior** | Ends trial, charges immediately | No charge if the new plan has a trial, otherwise as `full_immediately` | Ends trial, charges immediately | Ends trial, charges full amount | Keeps the trial end date, no charge | | **Best for** | Crediting unused time | Fixed billing dates | Simple upgrade/downgrade math | Resetting billing cycles | Free migrations or courtesy switches | | **Complexity** | Medium (day calculation) | Medium (day calculation) | Low (simple subtraction) | Low (full charge) | None | > [!NOTE] > > When a plan change ends a trial and starts a new billing period, the subscription's `trial_period_days` becomes `0`, and the dashboard and the Customer Portal stop showing the trial. With `prevent_change`, this happens when the charge succeeds. A change that keeps `next_billing_date`, such as `do_not_bill`, keeps the trial. ```mermaid theme={null} flowchart TD K{Keep the billing date and charge for the time left?} -->|Yes| L[prorated_immediately_keep_cycle] K -->|No| A{Credit unused time on the old plan?} A -->|Yes| B[prorated_immediately] A -->|No| C{Need to reset billing cycle?} C -->|Yes| D[full_immediately] C -->|No| E{Skip billing entirely?} E -->|Yes| F[do_not_bill] E -->|No| G[difference_immediately] ``` ### Example Scenarios Use these canonical numbers consistently: * Current plan: **Basic** at **\$30/month** * Upgrade target: **Pro** at **\$80/month** * Downgrade target (from Pro): **Starter** at **\$20/month** * Billing cycle: **30 days**, started on **January 1** * Plan change happens on **January 16** (15 days remaining, 15 days used) > [accordion] Upgrade: Basic ($30) → Pro ($80) with prorated\_immediately > > ``` > Step 1: Credit the unused time on the current plan > Unused days = 15 out of 30 days > Credit = $30 × (15/30) = $15.00 > > Step 2: Charge a full cycle at the new plan > New plan cost = $80.00 (never prorated) > > Step 3: Calculate immediate charge > Charge = Full new cycle − Credit > Charge = $80.00 − $15.00 = $65.00 > > → Customer pays $65.00 now > → Customer starts a full month of Pro today > → Billing cycle resets to today (January 16) > → Next renewal (Feb 15): $80.00/month > ``` > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'prorated_immediately' > }) > ``` > [accordion] Downgrade: Pro ($80) → Starter ($20) with prorated\_immediately > > ``` > Step 1: Credit the unused time on the current plan > Unused days = 15 out of 30 days > Credit = $80 × (15/30) = $40.00 > > Step 2: Charge a full cycle at the new plan > New plan cost = $20.00 (never prorated) > > Step 3: Net the two > Net = $20.00 − $40.00 = −$20.00 > > → No charge — $20.00 credit added to subscription > → Billing cycle resets to today (January 16) > → Credit auto-applies to future renewals > → Next renewal (Feb 15): $20.00 − $20.00 (from credit) = $0.00 (credit exhausted) > → Following renewal (Mar 15): $20.00 > ``` > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_starter', > quantity: 1, > proration_billing_mode: 'prorated_immediately' > }) > ``` > [accordion] Upgrade: Basic ($30) → Pro ($80) with prorated\_immediately\_keep\_cycle > > ``` > Step 1: Find the price difference > Difference = $80.00 − $30.00 = $50.00 > > Step 2: Apply the time left in the current cycle > Remaining days = 15 out of 30 days > Charge = $50.00 × (15/30) = $25.00 > > → Customer pays $25.00 now > → Billing date stays the same (January 31) > → Next renewal (Jan 31): $80.00/month > ``` > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'prorated_immediately_keep_cycle' > }) > ``` > [accordion] Downgrade: Pro ($80) → Starter ($20) with prorated\_immediately\_keep\_cycle > > ``` > Step 1: Find the price difference > Difference = $20.00 − $80.00 = −$60.00 > > Step 2: Apply the time left in the current cycle > Remaining days = 15 out of 30 days > Credit = $60.00 × (15/30) = $30.00 > > → No charge — $30.00 credit added to the customer wallet > → Billing date stays the same (January 31) > → Next renewal (Jan 31): $20.00 − $20.00 (from credit) = $0.00 ($10.00 credit remaining) > ``` > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_starter', > quantity: 1, > proration_billing_mode: 'prorated_immediately_keep_cycle' > }) > ``` > [accordion] Upgrade: Basic ($30) → Pro ($80) with difference\_immediately > > ``` > Immediate charge = New plan price − Old plan price > = $80 − $30 > = $50.00 > > → Customer pays $50.00 now (regardless of cycle position) > → Billing cycle resets to today (January 16) > → Next renewal (Feb 15): $80.00/month > ``` > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'difference_immediately' > }) > ``` > [accordion] Downgrade: Pro ($80) → Starter ($20) with difference\_immediately > > ``` > Credit = Old plan price − New plan price > = $80 − $20 > = $60.00 > > → No charge — $60.00 credit added to subscription > → Credit auto-applies to future renewals > → Next renewal: $20.00 − $20.00 (from credit) = $0.00 > → Following renewal: $20.00 − $20.00 (from credit) = $0.00 > → Third renewal: $20.00 − $20.00 (from remaining credit) = $0.00 > ``` > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_starter', > quantity: 1, > proration_billing_mode: 'difference_immediately' > }) > ``` > [accordion] Upgrade: Basic ($30) → Pro ($80) with full\_immediately > > ``` > Immediate charge = Full new plan price = $80.00 > > → Customer pays $80.00 now > → No credit for unused time on old plan > → Billing cycle resets to today (January 16) > → Next renewal: February 16 at $80.00/month > ``` > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'full_immediately' > }) > ``` > [accordion] Mid-cycle upgrade with add-ons using prorated\_immediately > > ``` > Current: Basic plan ($30/month), no add-ons > New: Pro plan ($80/month) + Extra Seats add-on ($10/seat × 3 seats = $30/month) > Change on day 16 of 30 (15 days remaining) > > Step 1: Credit the unused time on the current plan > Credit = $30 × (15/30) = $15.00 > > Step 2: Charge a full cycle at the new plan + add-ons > New plan = $80.00 > Add-ons = $30.00 > Total new = $110.00 (never prorated) > > Step 3: Immediate charge > Charge = $110.00 − $15.00 = $95.00 > > → Customer pays $95.00 now > → Next renewal: $80.00 + $30.00 = $110.00/month > ``` > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'prorated_immediately', > addons: [ > { addon_id: 'addon_seats', quantity: 3 } > ] > }) > ``` ### How Each Mode Processes Billing ```mermaid theme={null} flowchart LR A[Plan Change] --> B{Proration Mode} B -->|prorated| C[Credit unused time] C --> D[Charge full new cycle] D --> E[Reset billing date] B -->|difference| F[Price difference] F -->|Upgrade| G[Charge diff] F -->|Downgrade| H[Add credit] G --> E H --> E B -->|full| I[Charge full price] I --> E B -->|do_not_bill| J[No charge / no credit] J --> K[Keep billing date] B -->|keep_cycle| L[Price difference × time left] L --> K ``` > [!TIP] > > Pick `prorated_immediately` to credit unused time on the old plan while charging a full cycle of the new one; use `prorated_immediately_keep_cycle` to charge the difference for the time left and keep the billing date; choose `full_immediately` to restart billing; use `difference_immediately` for simple upgrades and automatic credit on downgrades; or use `do_not_bill` to switch plans without any billing adjustment. ## Handling Payment Failures Control what happens when a plan change payment fails using the `on_payment_failure` parameter. ### Payment Failure Modes > [tab] prevent\_change (Recommended for critical upgrades) > > **Behavior**: Keep the subscription on its current plan until payment succeeds. > > * Plan change is marked as "pending" > * Customer retains access to their current plan > * Subscription moves to `active` state only after successful payment > * Useful when you want to ensure payment before granting upgraded features > * With `effective_at: next_billing_date`, the plan change payment replaces the renewal payment for that cycle. If it fails, Dodo Payments cancels the plan change and bills the renewal of the current plan instead, with the usual retries and dunning. If that renewal also fails, the subscription follows the usual failed-renewal flow (`past_due` or `on_hold`) > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'prorated_immediately', > on_payment_failure: 'prevent_change' > }); > ``` > [tab] apply\_change (Default) > > **Behavior**: Apply the plan change immediately regardless of payment outcome. > > * Plan change is applied even if payment fails > * Customer gets immediate access to the new plan > * Subscription may move to `on_hold` if payment fails > * Good for non-critical upgrades or when you trust the customer > > ```javascript theme={null} > await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_pro', > quantity: 1, > proration_billing_mode: 'prorated_immediately', > on_payment_failure: 'apply_change' // This is the default > }); > ``` > [!NOTE] > > If not specified, the `on_payment_failure` parameter uses your business-level default setting configured in the dashboard. ### When to Use Each Mode | Scenario | Recommended Mode | Reason | | - | - | - | | Upgrading to premium features | `prevent_change` | Ensure payment before granting access | | Quantity increase (more seats) | `prevent_change` | Prevent usage without payment | | Downgrading plans | `apply_change` | Customer is reducing spend | | Trusted enterprise customers | `apply_change` | Lower risk of non-payment | | Trial to paid conversion | `prevent_change` | Critical payment moment | ## Change Plan on an On-Hold Subscription You can move an `on_hold` subscription to a different plan and charge the new plan instead of the failed renewal. Use this to keep a customer whose renewal failed, often because of insufficient funds, on a cheaper plan instead of cancelling the subscription. This applies to a subscription that is `on_hold` because a renewal charge or a plan change charge failed. It does not apply to a subscription that is on hold during a pause. Only the merchant can make this change. The Customer Portal cannot change the plan of an `on_hold` subscription. ### Required Options Send a `change-plan` request with these values. Any other combination returns `422` `ON_HOLD_PLAN_CHANGE_OPTIONS_NOT_SUPPORTED`. | Field | Required value | | - | - | | `proration_billing_mode` | `full_immediately` | | `effective_at` | `immediately` | | `on_payment_failure` | `apply_change` | | `collect_via_payment_link` | `false` or not set | > [!WARNING] > > If your business default for `on_payment_failure` is `prevent_change`, send `on_payment_failure: apply_change` explicitly. Otherwise the request fails with `422`. The target plan can cost more or less than the current plan. The current plan and the target plan must both have a fixed price. Usage-based plans are not supported. ### From the Dashboard To change the plan of an `on_hold` subscription in the dashboard, open the subscription and click **Update**, then choose a different plan. The dashboard sends the required options for you. **Full immediately** is the only billing mode it offers, and a note explains that the unpaid invoice is voided. ### What Happens When the request succeeds, Dodo Payments does these steps: 1. Voids every unpaid invoice of the subscription (the failed renewal or the failed plan change) and removes its pending payment retries. 2. Applies the new plan to the subscription. 3. Opens a new invoice for the full price of the new plan. 4. Charges the invoice to the saved payment method, off-session, in a background job after the request returns. The charge is asynchronous, so the response returns `200` with `payment_id` and the other fields set to `null`. The subscription stays `on_hold` until the new invoice is paid. Then it becomes `active`, and you receive the `subscription.active` webhook. If the charge fails, [payment retries](/features/recovery/payment-retries) and [dunning](/features/recovery/subscription-dunning) continue on the new invoice. If the customer then uses [Update Payment Method](/api-reference/subscriptions/update-payment-method), Dodo Payments charges the new invoice, not the amount of the old renewal. If the change costs `0`, for example a \$0 plan or a 100% discount, the subscription becomes `active` immediately. > [!NOTE] > > The customer gets the entitlements of the new plan, such as license keys, files, and Discord access, only after the new invoice is paid. Credits of the new plan are also granted only after payment. [Customer wallet](/features/customer-wallet) credits are not applied to a plan change on an `on_hold` subscription. ### Example Call [Preview Plan Change](/api-reference/subscriptions/preview-change-plan) with the same body to show the amount before you apply the change. > [tab] Node.js SDK > > ```typescript expandable theme={null} > const response = await client.subscriptions.changePlan('sub_123', { > product_id: 'pdt_starter', > quantity: 1, > proration_billing_mode: 'full_immediately', > effective_at: 'immediately', > on_payment_failure: 'apply_change', > }); > > // payment_id is null: the charge runs asynchronously. > // Wait for subscription.active before you restore access. > ``` > [tab] Python SDK > > ```python expandable theme={null} > response = client.subscriptions.change_plan( > subscription_id="sub_123", > product_id="pdt_starter", > quantity=1, > proration_billing_mode="full_immediately", > effective_at="immediately", > on_payment_failure="apply_change", > ) > ``` > [tab] HTTP > > ```bash expandable theme={null} > curl -X POST "$DODO_API_BASE/subscriptions/sub_123/change-plan" \ > -H "Authorization: Bearer $DODO_PAYMENTS_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "product_id": "pdt_starter", > "quantity": 1, > "proration_billing_mode": "full_immediately", > "effective_at": "immediately", > "on_payment_failure": "apply_change" > }' > ``` ### Limits and Errors You can change the plan of an `on_hold` subscription once per 24 hours. The preview has no limit. The `change-plan` endpoint has no idempotency key. If you retry a request after the subscription becomes `active`, Dodo Payments processes it as a normal plan change on an active subscription. These errors apply to a plan change on an `on_hold` subscription: | Status | Code | Cause | | - | - | - | | `422` | `ON_HOLD_PLAN_CHANGE_OPTIONS_NOT_SUPPORTED` | The request does not use the [required options](#required-options). | | `422` | `INACTIVE_SUBSCRIPTION_PLAN_CHANGE_NOT_SUPPORTED` | The current or target plan is usage-based, the subscription went on hold while it was paused, or the request came from the Customer Portal. | | `409` | `ON_HOLD_PLAN_CHANGE_RATE_LIMITED` | The subscription already had a plan change on hold in the last 24 hours. | | `409` | `PREVIOUS_PAYMENT_PENDING` | A payment for an unpaid invoice of the subscription is in progress. Retry after it completes or fails. | Subscriptions that are `past_due`, `paused`, or `cancelled` still return `422` `INACTIVE_SUBSCRIPTION_PLAN_CHANGE_NOT_SUPPORTED`. ## Business & Collection Defaults Set default upgrade and downgrade behavior at the business level under **Settings → Subscriptions**. These defaults apply to all customer-portal plan changes and can be overridden per product collection. Separate defaults exist for upgrades and downgrades: | Setting | Field (upgrade / downgrade) | Default (upgrade) | Default (downgrade) | | - | - | - | - | | When the new plan starts | `effective_at_on_upgrade` / `effective_at_on_downgrade` | `immediately` | `next_billing_date` | | How the customer is charged | `proration_billing_mode_on_upgrade` / `proration_billing_mode_on_downgrade` | `difference_immediately` | `difference_immediately` | | If the customer's payment fails | `on_payment_failure` | `apply_change` | `apply_change` | Configure business defaults under **Settings → Subscriptions**, and collection overrides on each product collection. Each collection field is independent — leave it unset to inherit from the business default, or set a value to override it. > [!WARNING] > > `prorated_immediately_keep_cycle` (**Prorated, keep billing date** in the dashboard) needs **When the new plan starts** set to **Immediately**. The dashboard disables a pair of `prorated_immediately_keep_cycle` and `next_billing_date`, and the API rejects it with `422`. An inherited value counts. For example, a collection that sets this mode and inherits `next_billing_date` from the business is rejected. > [!NOTE] > > When a Customer Portal plan change resolves to **When the new plan starts** = `next_billing_date`, the portal schedules it with `full_immediately`, whatever **How the customer is charged** is set to. The new plan is billed in full from the start of the next billing cycle, so no proration applies. ### Resolution Order For any given plan change, each setting resolves in this order: ``` per-request value (Change Plan API) → collection field (if set) → business field → system default ``` > [!NOTE] > > A value passed explicitly to the [Change Plan API](/api-reference/subscriptions/change-plan) always wins. The business and collection defaults only take effect when no explicit value is supplied — which is the case for all plan changes initiated from the customer portal. > [!TIP] > > A common setup: keep upgrades `immediately` + `difference_immediately` so customers pay the difference and get access right away, and keep downgrades on `next_billing_date` so customers keep their current plan until the cycle ends. ## Handling Webhooks Track subscription state through webhooks to confirm plan changes and payments. ### Event Types to Handle * `subscription.active`: subscription activated * `subscription.plan_changed`: subscription plan changed (upgrade/downgrade/addon changes) * `subscription.on_hold`: charge failed, renewals stopped * `subscription.renewed`: renewal succeeded * `payment.succeeded`: payment for plan change or renewal succeeded * `payment.failed`: payment failed > [!NOTE] > > Drive business logic from subscription events and use payment events for confirmation and reconciliation. ### Verify Signatures and Handle Intents > [tab] Next.js Route Handler > > ```javascript theme={null} > import { NextRequest, NextResponse } from 'next/server'; > > export async function POST(req) { > const webhookId = req.headers.get('webhook-id'); > const webhookSignature = req.headers.get('webhook-signature'); > const webhookTimestamp = req.headers.get('webhook-timestamp'); > const secret = process.env.DODO_PAYMENTS_WEBHOOK_KEY; > > const payload = await req.text(); > // verifySignature is a placeholder – in production, use a Standard Webhooks library > const { valid, event } = await verifySignature( > payload, > { id: webhookId, signature: webhookSignature, timestamp: webhookTimestamp }, > secret > ); > if (!valid) return NextResponse.json({ error: 'Invalid signature' }, { status: 400 }); > > switch (event.type) { > case 'subscription.active': > // mark subscription active in your DB > break; > case 'subscription.plan_changed': > // refresh entitlements and reflect the new plan in your UI > break; > case 'subscription.on_hold': > // notify user to update payment method > break; > case 'subscription.renewed': > // extend access window > break; > case 'payment.succeeded': > // reconcile payment for plan change > break; > case 'payment.failed': > // log and alert > break; > default: > // ignore unknown events > break; > } > > return NextResponse.json({ received: true }); > } > ``` > [tab] Express.js > > ```javascript theme={null} > import express from 'express'; > > const app = express(); > app.post('/webhooks/dodo', express.raw({ type: 'application/json' }), async (req, res) => { > const webhookId = req.header('webhook-id'); > const webhookSignature = req.header('webhook-signature'); > const webhookTimestamp = req.header('webhook-timestamp'); > const secret = process.env.DODO_PAYMENTS_WEBHOOK_KEY; > const payload = req.body.toString('utf8'); > > const { valid, event } = await verifySignature( > payload, > { id: webhookId, signature: webhookSignature, timestamp: webhookTimestamp }, > secret > ); > if (!valid) return res.status(400).send('Invalid signature'); > > // handle events like above > res.json({ received: true }); > }); > > app.listen(3000); > ``` > [!NOTE] > > For detailed payload schemas, see the [Subscription webhook payloads](/developer-resources/webhooks/intents/subscription) and [Payment webhook payloads](/developer-resources/webhooks/intents/payment). ## Best Practices ### Plan Change Strategy * **Test thoroughly**: Always test plan changes in test mode before production * **Choose proration carefully**: Select the proration mode that aligns with your business model * **Handle failures gracefully**: Implement proper error handling and retry logic * **Monitor success rates**: Track plan change success/failure rates and investigate issues ### Webhook Implementation * **Verify signatures**: Always validate webhook signatures to ensure authenticity * **Implement idempotency**: Handle duplicate webhook events gracefully * **Process asynchronously**: Don't block webhook responses with heavy operations * **Log everything**: Maintain detailed logs for debugging and audit purposes ### User Experience * **Communicate clearly**: Inform customers about billing changes and timing * **Provide confirmations**: Send email confirmations for successful plan changes * **Handle edge cases**: Consider trial periods, prorations, and failed payments * **Update UI immediately**: Reflect plan changes in your application interface ## Common Issues and Solutions Resolve typical problems encountered during subscription plan changes: > [accordion] Charge created but subscription not updated > > **Symptoms**: API call succeeds but subscription remains on old plan > > **Common causes**: > > * Webhook processing failed or was delayed > * Application state not updated after receiving webhooks > * Database transaction issues during state update > > **Solutions**: > > * Implement webhook handling with retry logic > * Use idempotent operations for state updates > * Add monitoring to detect and alert on missed webhook events > * Verify webhook endpoint is accessible and responding correctly > [accordion] Credits not applied after downgrade > > **Symptoms**: Customer downgrades but doesn't see credit balance > > **Common causes**: > > * Proration mode expectations: downgrades credit the full plan price difference with `difference_immediately`, while `prorated_immediately` credits the unused time on the old cycle and then charges a full cycle at the new plan — so a credit balance only remains when that credit exceeds the new plan price > * Credits are subscription-specific and don't transfer between subscriptions. Exception: `prorated_immediately_keep_cycle` puts downgrade credit in the [customer wallet](/features/customer-wallet) > * Credit balance not visible in customer dashboard > > **Solutions**: > > * Use `difference_immediately` for downgrades when you want automatic credits > * Explain to customers that credits apply to future renewals of the same subscription. With `prorated_immediately_keep_cycle`, check the customer wallet balance instead > * Implement customer portal to show credit balances > * Check next invoice preview to see applied credits > [accordion] Webhook signature verification fails > > **Symptoms**: Webhook events rejected due to invalid signature > > **Common causes**: > > * Incorrect webhook secret key > * Raw request body modified before signature verification > * Wrong signature verification algorithm > > **Solutions**: > > * Verify you're using the correct `DODO_PAYMENTS_WEBHOOK_KEY` from dashboard > * Read raw request body before any JSON parsing middleware > * Use the standard webhook verification library for your platform > * Test webhook signature verification in development environment > [accordion] Plan change fails with 422 error > > **Symptoms**: API returns 422 Unprocessable Entity error > > **Common causes**: > > * Invalid subscription ID or product ID > * Subscription not in active state. An `on_hold` subscription can change plan only with the options in [Change Plan on an On-Hold Subscription](#change-plan-on-an-on-hold-subscription) > * Missing required parameters > * Product not available for plan changes > > **Solutions**: > > * Verify subscription exists and is active, or follow [Change Plan on an On-Hold Subscription](#change-plan-on-an-on-hold-subscription) for an `on_hold` subscription > * Check product ID is valid and available > * Ensure all required parameters are provided > * Review API documentation for parameter requirements > [accordion] Immediate charge fails during plan change > > **Symptoms**: Plan change initiated but immediate charge fails > > **Common causes**: > > * Insufficient funds on customer's payment method > * Payment method expired or invalid > * Bank declined the transaction > * Fraud detection blocked the charge > > **Solutions**: > > * Handle `payment.failed` webhook events appropriately > * Notify customer to update payment method > * Implement retry logic for temporary failures > * Consider allowing plan changes with failed immediate charges > [accordion] Subscription on hold after plan change > > **Symptoms**: Plan change charge fails and subscription moves to `on_hold` state > > **What happens**: > When a plan change charge fails, the subscription is automatically placed in `on_hold` state. The subscription will not renew automatically until the payment method is updated. > > **Solution**: Update the payment method to reactivate the subscription > > To reactivate a subscription from `on_hold` state after a failed plan change: > > 1. **Update the payment method** using the Update Payment Method API > 2. **Automatic charge creation**: The API automatically creates a charge for remaining dues > 3. **Invoice generation**: An invoice is generated for the charge > 4. **Payment processing**: The payment is processed using the new payment method > 5. **Reactivation**: Upon successful payment, the subscription is reactivated to `active` state > > ```javascript Node.js theme={null} > // Reactivate subscription from on_hold after failed plan change > async function reactivateAfterFailedPlanChange(subscriptionId) { > // Update payment method - automatically creates charge for remaining dues > const response = await client.subscriptions.updatePaymentMethod(subscriptionId, { > payment_method: { type: 'new', return_url: 'https://example.com/return' } > }); > > if (response.payment_id) { > console.log('Charge created for remaining dues:', response.payment_id); > console.log('Payment link:', response.payment_link); > > // Redirect customer to payment_link to complete payment > // Monitor webhooks for: > // 1. payment.succeeded - charge succeeded > // 2. subscription.active - subscription reactivated > } > > return response; > } > > // Or use existing payment method if available > async function reactivateWithExistingPaymentMethod(subscriptionId, paymentMethodId) { > const response = await client.subscriptions.updatePaymentMethod(subscriptionId, { > payment_method: { type: 'existing', payment_method_id: paymentMethodId } > }); > > // Monitor webhooks for payment.succeeded and subscription.active > return response; > } > ``` > > ```python Python theme={null} > # Reactivate subscription from on_hold after failed plan change > def reactivate_after_failed_plan_change(subscription_id): > # Update payment method - automatically creates charge for remaining dues > response = client.subscriptions.update_payment_method( > subscription_id=subscription_id, > payment_method={"type": "new", "return_url": "https://example.com/return"}, > ) > > if response.payment_id: > print("Charge created for remaining dues:", response.payment_id) > print("Payment link:", response.payment_link) > > # Redirect customer to payment_link to complete payment > # Monitor webhooks for: > # 1. payment.succeeded - charge succeeded > # 2. subscription.active - subscription reactivated > > return response > > # Or use existing payment method if available > def reactivate_with_existing_payment_method(subscription_id, payment_method_id): > response = client.subscriptions.update_payment_method( > subscription_id=subscription_id, > payment_method={"type": "existing", "payment_method_id": payment_method_id}, > ) > > # Monitor webhooks for payment.succeeded and subscription.active > return response > ``` > > > [!TIP] > > > > If the customer cannot pay the current price, change the plan of the `on_hold` subscription instead. Dodo Payments voids the unpaid invoice and charges the new plan to the saved payment method. See [Change Plan on an On-Hold Subscription](#change-plan-on-an-on-hold-subscription). > > **Webhook events to monitor**: > > * `subscription.on_hold`: Subscription placed on hold (received when plan change charge fails) > * `payment.succeeded`: Payment for remaining dues succeeded (after updating payment method) > * `subscription.active`: Subscription reactivated after successful payment > > **Best practices**: > > * Notify customers immediately when a plan change charge fails > > * Provide clear instructions on how to update their payment method > > * Monitor webhook events to track reactivation status > > * Consider implementing automatic retry logic for temporary payment failures > > > [card] [Update Payment Method API Reference](/api-reference/subscriptions/update-payment-method) > > > > View the complete API documentation for updating payment methods and reactivating subscriptions. ## Testing Your Implementation Thoroughly test your subscription plan change implementation: **1. Set up test environment** * Use test API keys and test products * Create test subscriptions with different plan types * Configure test webhook endpoint * Set up monitoring and logging **2. Test different proration modes** * Test `prorated_immediately` with various billing cycle positions * Test `difference_immediately` for upgrades and downgrades * Test `full_immediately` to reset billing cycles * Test `do_not_bill` for no-charge/no-credit plan switches * Verify credit calculations are correct **3. Test webhook handling** * Verify all relevant webhook events are received * Test webhook signature verification * Handle duplicate webhook events gracefully * Test webhook processing failure scenarios **4. Test error scenarios** * Test with invalid subscription IDs * Test with expired payment methods * Test network failures and timeouts * Test with insufficient funds **5. Monitor in production** * Set up alerts for failed plan changes * Monitor webhook processing times * Track plan change success rates * Review customer support tickets for plan change issues ## Error Handling Handle common API errors gracefully in your implementation: ### HTTP Status Codes > [accordion] 200 OK > > Plan change request processed successfully. The response body is a `ChangePlanResponse` with `payment_id`, `payment_link`, `client_secret`, `expires_on`, `invoice_id`, and `refund_id`. All of them are nullable, so the body serializes as `{}` for an ordinary off-session change. `invoice_id` is set only for an invoice-led subscription, and `refund_id` only for a downgrade refunded with `credit: refund`. The checkout fields are populated for a successful `collect_via_payment_link` request, which returns checkout handles — see [Collecting Payment via a Checkout Link](#collecting-payment-via-a-checkout-link). If `on_payment_failure=prevent_change`, the plan change stays pending until payment succeeds. > [accordion] 400 Bad Request > > Invalid request parameters. Check that all required fields are provided and properly formatted. > [accordion] 401 Unauthorized > > Invalid or missing API key. Verify your `DODO_PAYMENTS_API_KEY` is correct and has proper permissions. > [accordion] 409 Conflict > > A pending plan change already exists for this subscription (`PENDING_PLAN_CHANGE_EXISTS`). For a *scheduled* change, cancel it with `DELETE /subscriptions/{subscription_id}/change-plan/scheduled` before submitting a new one, or send the new request with `cancel_scheduled_change_plan: true` to replace it. For a pending *payment-link* change, send the new request with `cancel_older_payment_link: true` to replace it. See [Replacing a Pending Payment Link](#replacing-a-pending-payment-link). > > With `cancel_older_payment_link: true`, a `409` means the customer is paying the previous link now (`PLAN_CHANGE_PAYMENT_IN_PROGRESS`) or has already paid it (`PLAN_CHANGE_PAYMENT_ALREADY_COMPLETED`). > > On an `on_hold` subscription, a `409` means the subscription already had an on-hold plan change in the last 24 hours (`ON_HOLD_PLAN_CHANGE_RATE_LIMITED`), or a payment for an unpaid invoice is in progress (`PREVIOUS_PAYMENT_PENDING`). See [Change Plan on an On-Hold Subscription](#change-plan-on-an-on-hold-subscription). > [accordion] 503 Service Unavailable > > With `cancel_older_payment_link: true`, the previous payment link could not be cancelled (`PLAN_CHANGE_LINK_CANCEL_FAILED`). Nothing changed, so you can retry the request. > [accordion] 422 Unprocessable Entity > > The subscription is inactive or on-demand, or the request is not eligible for `collect_via_payment_link` — the business doesn't have the capability enabled, `effective_at` isn't `immediately`, or `on_payment_failure` isn't `prevent_change`. See [Requirements](#requirements). A subscription ID that doesn't exist or doesn't belong to your account returns `404` with the `NOT_FOUND` code. > > On an `on_hold` subscription, a `422` means the request does not use `full_immediately`, `immediately` and `apply_change` (`ON_HOLD_PLAN_CHANGE_OPTIONS_NOT_SUPPORTED`). It also means the current or target plan is usage-based, the subscription is on hold during a pause, or the request came from the Customer Portal (`INACTIVE_SUBSCRIPTION_PLAN_CHANGE_NOT_SUPPORTED`). See [Change Plan on an On-Hold Subscription](#change-plan-on-an-on-hold-subscription). > [accordion] 500 Internal Server Error > > Server error occurred. Retry the request after a brief delay. ### Error Response Format Errors return a JSON body with a `code` and a human-readable `message`: ```json theme={null} { "code": "INACTIVE_SUBSCRIPTION_PLAN_CHANGE_NOT_SUPPORTED", "message": "Changing plans is not supported for inactive subscriptions" } ``` See [Error Codes](/api-reference/error-codes) for the full list. ## Next Steps * Review the [Change Plan API](/api-reference/subscriptions/change-plan) * Explore [Credit-Based Billing](/features/credit-based-billing) * Implement alerts for `subscription.on_hold` * Check out the [Webhook Integration Guide](/developer-resources/webhooks) # Supabase Boilerplate Source: https://docs.dodopayments.com/developer-resources/supabase-boilerplate Clone the Next.js, Supabase, and Dodo Payments subscription starter, with Google sign-in, a Drizzle schema, a webhook Edge Function, and a billing dashboard. > [card] [GitHub Repository](https://github.com/dodopayments/dodo-supabase-subscription-starter) > > Minimal Next.js, Supabase, and Dodo Payments subscription boilerplate. > [card] [Live Demo](https://dodopayments-supabase-nextjs.vercel.app) > > Explore the deployed demo. ## Overview The Supabase subscription starter is a Next.js 15 and React 19 app that sells subscriptions with Dodo Payments. Supabase provides Google OAuth sign-in and the Postgres database, and Drizzle ORM defines the schema. A Supabase Edge Function receives Dodo Payments webhooks and stores payments and subscriptions, and a basic dashboard shows each user's plan and invoices. If you need only checkout, Customer Portal, and webhook route handlers for an existing app, use a framework adaptor instead: > [card] [Next.js Adaptor](/developer-resources/nextjs-adaptor) > [card] [Express Adaptor](/developer-resources/express-adaptor) ## Prerequisites Before you begin, you need: * Node.js 18 or later, or Bun 1.0 or later. * A Supabase project. You need its URL, anon key, service role key, and database connection string. * A Dodo Payments account, for an API key and a webhook signing secret. * A Google Cloud OAuth client, for its Client ID and Client Secret. ## Quickstart **1. Clone and Install** Clone the repository, then install dependencies with Bun, npm, or pnpm: ```bash theme={null} git clone https://github.com/dodopayments/dodo-supabase-subscription-starter.git cd dodo-supabase-subscription-starter # choose one bun install # or npm install # or pnpm install ``` **2. Create a Supabase Project** Create a Supabase project. Later steps use its project reference, the subdomain in `https://[your-project-ref].supabase.co`. Copy these values: * `NEXT_PUBLIC_SUPABASE_URL`, the project URL * `NEXT_PUBLIC_SUPABASE_ANON_KEY`, the anon key * `SUPABASE_SERVICE_ROLE_KEY`, the service role key * `DATABASE_URL`, the database connection string **3. Configure Google OAuth** In Google Cloud, add this authorized redirect URI to your OAuth client: `https://[your-project-ref].supabase.co/auth/v1/callback`. Then, in Supabase Auth, enable the Google provider with your Client ID and Client Secret. **4. Configure Dodo Payments** With the **Live Mode** switch in the sidebar off, create an API key under **Developer → API Keys** in the Dodo Payments dashboard. Keep `DODO_PAYMENTS_ENVIRONMENT` set to `test_mode` while you develop. **5. Add the Webhook in Dodo Payments** Under **Developer → Webhooks**, add an endpoint with this URL. You deploy the function that serves it in a later step. ```text theme={null} https://[your-project-ref].supabase.co/functions/v1/dodo-webhook ``` Select the payment and subscription events that the function handles: * Payment events: `payment.succeeded`, `payment.failed`, `payment.processing`, and `payment.cancelled` * Subscription events: `subscription.active`, `subscription.plan_changed`, `subscription.renewed`, `subscription.on_hold`, `subscription.cancelled`, `subscription.expired`, and `subscription.failed` Copy the endpoint's signing secret. It's the value of `DODO_WEBHOOK_SECRET`. **6. Create .env.local** Create a `.env.local` file in the root directory: ```env theme={null} # Supabase NEXT_PUBLIC_SUPABASE_URL=https://your-project-ref.supabase.co NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key SUPABASE_SERVICE_ROLE_KEY=your-service-role # Database DATABASE_URL=postgresql://postgres:[password]@db.[project-ref].supabase.co:5432/postgres # Dodo Payments DODO_PAYMENTS_API_KEY=dodo_test_... DODO_WEBHOOK_SECRET=your-webhook-secret DODO_PAYMENTS_ENVIRONMENT=test_mode ``` The Next.js app reads every variable in this file except `DODO_WEBHOOK_SECRET`. The Edge Function reads `DODO_WEBHOOK_SECRET` from its Supabase secrets, which you set when you deploy it. > [!WARNING] > > Don't commit secrets. In deployed environments, set them as environment variables. **7. Provision the Database Schema** Push the Drizzle schema to your Supabase database: ```bash theme={null} bun run db:push # or npm run db:push # or pnpm run db:push ``` > [!TIP] > > Tables created: `users`, `subscriptions`, `payments`. **8. Deploy the Webhook Function** Log in to Supabase, store the signing secret as a function secret, and deploy the `dodo-webhook` Edge Function. Replace `[your-project-ref]` with your project reference: ```bash theme={null} # login (one-time) bunx supabase login # or npx supabase login # store the Dodo Payments signing secret for the function npx supabase secrets set DODO_WEBHOOK_SECRET=your-webhook-secret --project-ref [your-project-ref] # deploy the edge function bun run deploy:webhook --project-ref [your-project-ref] # or npm run deploy:webhook -- --project-ref [your-project-ref] # or pnpm run deploy:webhook --project-ref [your-project-ref] ``` The `deploy:webhook` script runs `supabase functions deploy dodo-webhook --no-verify-jwt`, so Dodo Payments can call the function without a Supabase auth token. Supabase provides `SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` to the function by default. To check the deployment, send an unsigned request: ```bash cURL theme={null} curl -X POST \ 'https://[your-project-ref].supabase.co/functions/v1/dodo-webhook' \ -H 'Content-Type: application/json' \ -d '{"type":"payment.succeeded","data":{}}' ``` A `400` response with `Invalid webhook signature` means the function is running and has its secret. A `500` response with `Server configuration error` means `DODO_WEBHOOK_SECRET` isn't set. To send a signed test event, open the endpoint in **Developer → Webhooks** and use its **Testing** tab. **9. Create Products and Features** Under **Products** in the Dodo Payments dashboard, click **Add Product** to create a subscription product for each plan. Optionally, to list plan features in the app, add a metadata entry with the key `features` and a JSON array of strings as its value. The product's metadata then looks like this: ```json theme={null} { "features": "[\"Feature 1\", \"Feature 2\", \"Feature 3\"]" } ``` Metadata values are strings, numbers, or booleans, so store the array as a JSON string. The pricing UI parses the `features` value and renders each item. **10. Run the Dev Server** ```bash theme={null} bun run dev # or npm run dev # or pnpm run dev ``` Open [http://localhost:3000](http://localhost:3000) and sign in with Google. > [!TIP] > > You now have a working subscription SaaS scaffolded with Supabase and Dodo Payments. To confirm it end to end, subscribe to a plan with a [test card](/miscellaneous/testing-process). After the webhook arrives, the dashboard shows your new plan. ## What’s Included * Authentication through Supabase, with Google OAuth configured * Subscription checkout through Dodo Payments * A Supabase Edge Function for webhooks (`dodo-webhook`) * A Drizzle ORM schema, with `db:generate` and `db:migrate` scripts for migrations * A dashboard with invoices, subscription status, and plan features * Server actions to change plans, cancel a subscription, and restore a cancelled subscription > [!TIP] > > Keep `DODO_PAYMENTS_ENVIRONMENT` set to `test_mode` until you complete end-to-end tests. To go live, set it to `live_mode` and use a live mode API key. ## Key Files and Paths The webhook handler, app routes, and database schema live in these files: > [tab] Edge Function > > ```text theme={null} > supabase/functions/dodo-webhook/ > index.ts # verifies signatures, stores payments and subscriptions > deno.json # Deno configuration > ``` > [tab] Next.js Routes > > ```text theme={null} > app/page.tsx # redirects to /login or /dashboard > app/login/page.tsx # Google sign-in page > app/dashboard/page.tsx # plans, subscription, and invoices > app/checkout/route.ts # checkout handler > app/api/auth/callback/route.ts # OAuth callback > actions/* # server actions > ``` > [tab] Database (Drizzle) > > ```text theme={null} > lib/drizzle/schema.ts # users, subscriptions, payments > lib/drizzle/client.ts # client > ``` ## Environment Variables The Next.js app and the Edge Function read these variables: > [accordion] Supabase > > ```env theme={null} > NEXT_PUBLIC_SUPABASE_URL= > NEXT_PUBLIC_SUPABASE_ANON_KEY= > SUPABASE_SERVICE_ROLE_KEY= > DATABASE_URL= > ``` > > `.env.example` doesn't list `SUPABASE_SERVICE_ROLE_KEY`, but the app's admin client in `lib/supabase/admin.ts` needs it. Add it yourself. > [accordion] Dodo Payments > > ```env theme={null} > DODO_PAYMENTS_API_KEY= > DODO_WEBHOOK_SECRET= > DODO_PAYMENTS_ENVIRONMENT=test_mode|live_mode > ``` > [accordion] Google OAuth > > The app doesn't read Google credentials from environment variables. Enter the Client ID and Client Secret in the Google provider settings of Supabase Auth, and add this redirect URI to the OAuth client in Google Cloud: > > ```text theme={null} > https://[your-project-ref].supabase.co/auth/v1/callback > ``` ## Verification and Troubleshooting > [accordion] Webhook signature invalid (400) > > * Make sure the function's `DODO_WEBHOOK_SECRET` secret matches the endpoint's signing secret in the Dodo Payments dashboard. > * Confirm you deployed the latest `dodo-webhook` function. > * The function verifies the [Standard Webhooks](https://standardwebhooks.com/) headers `webhook-id`, `webhook-signature`, and `webhook-timestamp`. Make sure a proxy doesn't strip them. > [accordion] Database push fails > > * Check the `DATABASE_URL` syntax. > * The direct connection (`db.[project-ref].supabase.co:5432`) uses IPv6 unless your project has the IPv4 add-on. On an IPv4-only network, use the session pooler connection string instead ([Supabase connection docs](https://supabase.com/docs/guides/database/connecting-to-postgres)). > * Wait 2–3 minutes after you create the project before the first push. > [accordion] OAuth redirect mismatch > > * The redirect URI must be `https://[ref].supabase.co/auth/v1/callback`. > * Use the same URI in Google Cloud and in the Supabase Auth provider. > [!NOTE] > > For the original repository and detailed steps, see [dodo-supabase-subscription-starter](https://github.com/dodopayments/dodo-supabase-subscription-starter). # SvelteKit Adaptor Source: https://docs.dodopayments.com/developer-resources/sveltekit-adaptor Add Dodo Payments checkout, Customer Portal, and webhook route handlers to a SvelteKit app with the @dodopayments/sveltekit package and +server.ts routes. The `@dodopayments/sveltekit` package gives your SvelteKit app three route handlers. `Checkout` returns checkout URLs, `CustomerPortal` sends a customer to the Customer Portal, and `Webhooks` verifies webhook events and routes them to your code. > [card] [Checkout Handler](#checkout-route-handler) > > Create checkout URLs from your SvelteKit app. > [card] [Customer Portal](#customer-portal-route-handler) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-route-handler) > > Receive and verify Dodo Payments webhook events. ## Installation **1. Install the Package** Run this command in your project root: ```bash theme={null} npm install @dodopayments/sveltekit ``` The package lists SvelteKit 2 (`@sveltejs/kit` 2.20.3 or later) and `zod` 3.25 or later as peer dependencies. **2. Set Up Environment Variables** Create a `.env` file in your project root: ```env expandable theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret # test_mode or live_mode DODO_PAYMENTS_ENVIRONMENT=test_mode DODO_PAYMENTS_RETURN_URL=https://yourdomain.com/checkout/success ``` Create the API key under **Developer → API Keys**. Add your webhook endpoint under **Developer → Webhooks** and copy its signing secret into `DODO_PAYMENTS_WEBHOOK_KEY`. `DODO_PAYMENTS_RETURN_URL` is where customers land after checkout. If you don't pass an environment, the handlers use `live_mode`. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## Route Handler Examples > [!NOTE] > > The examples are SvelteKit `+server.ts` endpoints under `src/routes/api/`. They import your credentials from `$env/static/private`, which SvelteKit keeps out of client-side code. > [tab] Checkout Handler > > > [!NOTE] > > > > Use this handler to add Dodo Payments checkout to your SvelteKit app. `Checkout` returns a `GET` handler for static checkout and a `POST` handler for checkout sessions. Export `GET` from a handler created with `type: "static"` or no `type`, because the `GET` handler of a `session` handler returns 400. > > ```typescript SvelteKit Route Handler expandable theme={null} > // src/routes/api/checkout/+server.ts > import { Checkout } from "@dodopayments/sveltekit"; > import { DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_RETURN_URL, DODO_PAYMENTS_ENVIRONMENT } from '$env/static/private'; > > const checkoutGetHandler = Checkout({ > bearerToken: DODO_PAYMENTS_API_KEY, > returnUrl: DODO_PAYMENTS_RETURN_URL, > environment: DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > type: "static", > }); > > const checkoutPostHandler = Checkout({ > bearerToken: DODO_PAYMENTS_API_KEY, > returnUrl: DODO_PAYMENTS_RETURN_URL, > environment: DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > type: "session", // for checkout sessions > }); > > export const GET = checkoutGetHandler.GET; > export const POST = checkoutPostHandler.POST; > ``` > > ```bash Static Checkout cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/checkout?productId=pdt_fqJhl7pxKWiLhwQR042rh' > ``` > > ```bash Checkout Session cURL Example expandable theme={null} > curl --request POST \ > --url https://example.com/api/checkout \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_QMDuvLkbVzCRWRQjLNcs", > "quantity": 1 > } > ], > "customer": { > "email": "customer@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal Handler > > > [!NOTE] > > > > Use this handler to send customers to the Dodo Payments Customer Portal, where they manage their subscriptions and details. > > ```typescript SvelteKit Route Handler expandable theme={null} > // src/routes/api/customer-portal/+server.ts > import { CustomerPortal } from "@dodopayments/sveltekit"; > import { DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_ENVIRONMENT } from '$env/static/private'; > > const customerPortalHandler = CustomerPortal({ > bearerToken: DODO_PAYMENTS_API_KEY, > environment: DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > }); > > export const GET = customerPortalHandler.GET; > ``` > [tab] Webhook Handler > > > [!NOTE] > > > > Use this handler to receive Dodo Payments webhook events in your SvelteKit app and verify their signatures. > > ```typescript SvelteKit Route Handler expandable theme={null} > // src/routes/api/webhook/+server.ts > import { Webhooks } from "@dodopayments/sveltekit"; > import { DODO_PAYMENTS_WEBHOOK_KEY } from '$env/static/private'; > > export const POST = Webhooks({ > webhookKey: DODO_PAYMENTS_WEBHOOK_KEY, > onPayload: async (payload) => { > console.log(payload); > } > }); > ``` ## Checkout Route Handler The checkout handler supports all three ways to take payments with Dodo Payments: * **Static Payment Links:** Shareable URLs that collect payments without code. * **Dynamic Payment Links (deprecated):** Payment links you generate with custom details. They use deprecated endpoints. * **Checkout Sessions:** Hosted checkout with a product cart, customer details, and customization options. This is the recommended flow. `Checkout` takes these options: | Option | Type | Description | | - | - | - | | `bearerToken` | `string` | Your Dodo Payments API key. | | `environment` | `string` | `test_mode` or `live_mode`. Defaults to `live_mode`. | | `returnUrl` | `string` | Optional. The URL that checkout redirects the customer to after payment. A `return_url` in a POST body takes precedence. | | `type` | `string` | Optional. `static` (the default) for the `GET` handler. For the `POST` handler, `dynamic` selects dynamic checkout, and any other value, or none, selects checkout sessions. | > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_nZuwz45WAs64n3l07zpQR`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's address line. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's ZIP or postal code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > Payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed as metadata. > > The handler adds `returnUrl` from its config to the link as `redirect_url`. > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters and product IDs that don't exist also return 400. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL. In test mode, the URL uses `test.checkout.dodopayments.com`. > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/..." > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send the parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. > * `billing` and `customer` are required. > * For every supported body field, see: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic checkout proxies the deprecated `POST /payments` and `POST /subscriptions` endpoints. It keeps working for existing integrations, but new integrations should use checkout sessions. > > ### Response Format > > Dynamic checkout returns a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/..." > } > ``` > [accordion] Checkout Sessions (POST) > > Checkout sessions create a hosted checkout for one-time purchases and subscriptions, with full control over customization. `product_cart` is the only required field, and it needs at least one product. If the body has no `return_url`, the handler uses `returnUrl` from its config. > > For more details and every supported field, see the [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session). > > A session created with `payment_method_id` returns no checkout URL, so the handler responds with 400. To charge a saved payment method, create the session with the SDK instead. > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://checkout.dodopayments.com/session/..." > } > ``` ## Customer Portal Route Handler The Customer Portal route handler creates a Customer Portal session for the customer you pass and redirects the browser to it with a 302 response. > [!WARNING] > > The handler doesn't check who is calling it. Anyone who requests it with a customer ID gets that customer's portal. Protect the route with your own authentication, and pass only the signed-in user's customer ID. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, Dodo Payments also emails the portal link to the customer. > [!WARNING] > > Returns 400 if `customer_id` is missing, and 500 if the portal session can't be created. ## Webhook Route Handler The webhook route handler verifies each request before it runs your code: * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the raw request body and the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`, following the [Standard Webhooks](https://standardwebhooks.com/) specification. Returns 401 if verification fails. * **Payload Validation:** Validates the payload with Zod. Returns 400 for an invalid payload. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Internal error during verification * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200. The adaptor doesn't catch errors thrown in your handlers. They propagate to SvelteKit, and the request fails. ### Supported Webhook Event Handlers Each handler receives the verified payload for its event type: ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` For what each event means, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). *** ## Prompt for LLM Copy this prompt into your AI coding assistant to have it add the adaptor to your project. To give your agent the Dodo Payments docs and skills as well, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ```text expandable theme={null} You are an expert SvelteKit developer assistant. Your task is to guide a user through integrating the @dodopayments/sveltekit adapter into their existing SvelteKit project. The @dodopayments/sveltekit adapter provides route handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities, designed for SvelteKit server routes (+server.ts files). First, install the necessary packages. Use the package manager appropriate for your project (npm, yarn, or bun) based on the presence of lock files (e.g., package-lock.json for npm, yarn.lock for yarn, bun.lockb for bun): npm install @dodopayments/sveltekit Here's how you should structure your response: Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/sveltekit adapter would you like to integrate into your project? You can choose one or more of the following: Checkout Route Handler (for handling product checkouts) Customer Portal Route Handler (for managing customer subscriptions/details) Webhook Route Handler (for receiving Dodo Payments webhook events) All (integrate all three)" Based on the user's selection, provide detailed integration steps for each chosen functionality. If Checkout Route Handler is selected: Purpose: This handler manages static checkout and checkout sessions. Both return JSON responses with checkout URLs for programmatic handling. File Creation: Create a new file at src/routes/api/checkout/+server.ts in your SvelteKit project. Code Snippet: // src/routes/api/checkout/+server.ts import { Checkout } from "@dodopayments/sveltekit"; import { DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_RETURN_URL, DODO_PAYMENTS_ENVIRONMENT } from '$env/static/private'; const checkoutGetHandler = Checkout({ bearerToken: DODO_PAYMENTS_API_KEY, returnUrl: DODO_PAYMENTS_RETURN_URL, environment: DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", type: "static", }); const checkoutPostHandler = Checkout({ bearerToken: DODO_PAYMENTS_API_KEY, returnUrl: DODO_PAYMENTS_RETURN_URL, environment: DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", type: "session", // for checkout sessions }); export const GET = checkoutGetHandler.GET; export const POST = checkoutPostHandler.POST; Configuration & Usage: bearerToken: Your Dodo Payments API key. It's recommended to set this via the DODO_PAYMENTS_API_KEY environment variable. returnUrl: (Optional) The URL to redirect the user to after a successful checkout. environment: (Optional) Set to "test_mode" for testing, or omit/set to "live_mode" for production. type: (Optional) Set to "static" for GET/static checkout or "session" for POST/checkout sessions. Defaults to "static". Export GET only from a handler created with type "static". Static Checkout (GET) Query Parameters: productId (required): Product identifier (e.g., ?productId=pdt_nZuwz45WAs64n3l07zpQR) quantity (optional): Quantity of the product Customer Fields (optional): fullName, firstName, lastName, email, country, addressLine, city, state, zipCode Disable Flags (optional, set to true to disable): disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode Advanced Controls (optional): paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts Metadata (optional): Any query parameter starting with metadata_ (e.g., ?metadata_userId=abc123) Returns: {"checkout_url": "https://checkout.dodopayments.com/..."} Checkout Sessions (POST) - (Recommended) A more customizable checkout experience. Returns JSON with checkout_url: Parameters are sent as a JSON body, and product_cart is required. Supports both one-time and recurring payments. Returns: {"checkout_url": "https://checkout.dodopayments.com/session/..."}. For a complete list of supported fields, refer to: Checkout Sessions Integration Guide: https://docs.dodopayments.com/developer-resources/checkout-session Error Handling: If productId is missing or other parameters are invalid, the handler will return a 400 response. If Customer Portal Route Handler is selected: Purpose: This handler redirects a customer to their Dodo Payments customer portal. It does not authenticate the caller, so protect the route and pass only the signed-in user's customer ID. File Creation: Create a new file at src/routes/api/customer-portal/+server.ts in your SvelteKit project. Code Snippet: // src/routes/api/customer-portal/+server.ts import { CustomerPortal } from "@dodopayments/sveltekit"; import { DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_ENVIRONMENT } from '$env/static/private'; const customerPortalHandler = CustomerPortal({ bearerToken: DODO_PAYMENTS_API_KEY, environment: DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", }); export const GET = customerPortalHandler.GET; Query Parameters: customer_id (required): The customer ID for the portal session (e.g., ?customer_id=cus_123) send_email (optional, boolean): If set to true, sends an email to the customer with the portal link. Returns 400 if customer_id is missing. If Webhook Route Handler is selected: Purpose: This handler processes incoming webhook events from Dodo Payments, allowing your application to react to events like successful payments, refunds, or subscription changes. File Creation: Create a new file at src/routes/api/webhook/+server.ts in your SvelteKit project. Code Snippet: // src/routes/api/webhook/+server.ts import { Webhooks } from "@dodopayments/sveltekit"; import { DODO_PAYMENTS_WEBHOOK_KEY } from '$env/static/private'; export const POST = Webhooks({ webhookKey: DODO_PAYMENTS_WEBHOOK_KEY, onPayload: async (payload) => { console.log(payload); } }); Handler Details: Method: Only POST requests are supported. Other methods return 405. Signature Verification: The handler verifies the webhook signature using the webhookKey and returns 401 if verification fails. Payload Validation: The payload is validated with Zod. Returns 400 for invalid payloads. Error Handling: 401: Invalid signature 400: Invalid payload 500: Internal error during verification Event Routing: Calls onPayload for every event, then the handler for the event's type. Supported Webhook Event Handlers: onPayload?: (payload: WebhookPayload) => Promise onPaymentSucceeded?: (payload: WebhookPayload) => Promise onPaymentFailed?: (payload: WebhookPayload) => Promise onPaymentProcessing?: (payload: WebhookPayload) => Promise onPaymentCancelled?: (payload: WebhookPayload) => Promise onRefundSucceeded?: (payload: WebhookPayload) => Promise onRefundFailed?: (payload: WebhookPayload) => Promise onDisputeOpened?: (payload: WebhookPayload) => Promise onDisputeExpired?: (payload: WebhookPayload) => Promise onDisputeAccepted?: (payload: WebhookPayload) => Promise onDisputeCancelled?: (payload: WebhookPayload) => Promise onDisputeChallenged?: (payload: WebhookPayload) => Promise onDisputeWon?: (payload: WebhookPayload) => Promise onDisputeLost?: (payload: WebhookPayload) => Promise onSubscriptionActive?: (payload: WebhookPayload) => Promise onSubscriptionOnHold?: (payload: WebhookPayload) => Promise onSubscriptionRenewed?: (payload: WebhookPayload) => Promise onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise onSubscriptionCancelled?: (payload: WebhookPayload) => Promise onSubscriptionFailed?: (payload: WebhookPayload) => Promise onSubscriptionExpired?: (payload: WebhookPayload) => Promise onSubscriptionUpdated?: (payload: WebhookPayload) => Promise onSubscriptionPaused?: (payload: WebhookPayload) => Promise onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise onLicenseKeyCreated?: (payload: WebhookPayload) => Promise onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise onDunningStarted?: (payload: WebhookPayload) => Promise onDunningRecovered?: (payload: WebhookPayload) => Promise onCreditAdded?: (payload: WebhookPayload) => Promise onCreditDeducted?: (payload: WebhookPayload) => Promise onCreditExpired?: (payload: WebhookPayload) => Promise onCreditRolledOver?: (payload: WebhookPayload) => Promise onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise onCreditOverageCharged?: (payload: WebhookPayload) => Promise onCreditOverageReset?: (payload: WebhookPayload) => Promise onCreditManualAdjustment?: (payload: WebhookPayload) => Promise onCreditBalanceLow?: (payload: WebhookPayload) => Promise onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise onPayoutCreated?: (payload: WebhookPayload) => Promise onPayoutOnHold?: (payload: WebhookPayload) => Promise onPayoutInProgress?: (payload: WebhookPayload) => Promise onPayoutFailed?: (payload: WebhookPayload) => Promise onPayoutSuccess?: (payload: WebhookPayload) => Promise Environment Variable Setup: To ensure the adapter functions correctly, you will need to manually set up the following environment variables in your SvelteKit project's deployment environment (e.g., Vercel, Netlify, AWS, etc.): DODO_PAYMENTS_API_KEY: Your Dodo Payments API Key (required for Checkout and Customer Portal). DODO_PAYMENTS_RETURN_URL: (Optional) The URL to redirect to after a successful checkout (for Checkout handler). DODO_PAYMENTS_ENVIRONMENT: (Optional) "test_mode" or "live_mode". Defaults to "live_mode". DODO_PAYMENTS_WEBHOOK_KEY: Your Dodo Payments Webhook Secret (required for Webhook handler). Example .env file: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_RETURN_URL=your-return-url DODO_PAYMENTS_ENVIRONMENT=test_mode Usage in your code (SvelteKit server routes import these from $env/static/private): import { DODO_PAYMENTS_API_KEY, DODO_PAYMENTS_WEBHOOK_KEY } from '$env/static/private'; bearerToken: DODO_PAYMENTS_API_KEY webhookKey: DODO_PAYMENTS_WEBHOOK_KEY Important: Never commit sensitive environment variables directly into your version control. Use environment variables for all sensitive information. If the user needs assistance setting up environment variables for their specific deployment environment, ask them what platform they are using (e.g., Vercel, Netlify, AWS, etc.), and provide guidance. You can also add comments to their PR or chat depending on the context ``` # TanStack Adaptor Source: https://docs.dodopayments.com/developer-resources/tanstack-adaptor Add Dodo Payments checkout, Customer Portal, and webhook server routes to a TanStack Start project with the @dodopayments/tanstack package. The `@dodopayments/tanstack` package gives your TanStack Start project three request handlers. `Checkout` returns checkout URLs, `CustomerPortal` sends a customer to the Customer Portal, and `Webhooks` verifies webhook events and routes them to your code. Each handler takes a standard `Request` and returns a `Response`, so you call it from a server route handler. > [card] [Checkout Handler](#checkout-route-handler) > > Create checkout URLs with static and checkout session flows. > [card] [Customer Portal](#customer-portal-route-handler) > > Let customers manage their subscriptions and details. > [card] [Webhooks](#webhook-route-handler) > > Receive and process Dodo Payments webhook events. ## Installation **1. Install the Package** Run this command in your project root: ```bash theme={null} npm install @dodopayments/tanstack ``` The package also needs `zod` 3.25 or later, which it lists as a peer dependency. **2. Set Up Environment Variables** Create a `.env` file in your project root. Create the API key under **Developer → API Keys**. Add your webhook endpoint under **Developer → Webhooks**, and copy its **Signing secret** into `DODO_PAYMENTS_WEBHOOK_KEY`: ```env expandable theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_RETURN_URL=https://yourdomain.com/checkout/success # test_mode or live_mode DODO_PAYMENTS_ENVIRONMENT=test_mode ``` TanStack Start loads `.env` files, and server routes read the values from `process.env`. `DODO_PAYMENTS_RETURN_URL` is where customers land after checkout. If you don't pass an environment, the handlers use `live_mode`. A test mode API key works only with `test_mode`. > [!WARNING] > > Never commit your `.env` file or secrets to version control. ## Route Handler Examples > [!NOTE] > > The examples are TanStack Start server routes in `src/routes/api/`. Each one defines its handlers under `server.handlers` in `createFileRoute`. Older TanStack Start releases, such as 1.129, define server routes with `createServerFileRoute` from `@tanstack/react-start/server` and a `.methods()` call instead. The Dodo Payments handlers work the same way with both APIs: pass them the `request`. > [tab] Checkout Handler > > > [!NOTE] > > > > Use this handler to add Dodo Payments checkout to your app. The `GET` handler serves static checkout. The `POST` handler serves checkout sessions. > > ```typescript TanStack Route Handler expandable theme={null} > // src/routes/api/checkout.ts > import { Checkout } from "@dodopayments/tanstack"; > import { createFileRoute } from "@tanstack/react-router"; > > export const Route = createFileRoute("/api/checkout")({ > server: { > handlers: { > GET: async ({ request }) => { > return Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > type: "static", // optional, defaults to 'static' > })(request); > }, > POST: async ({ request }) => { > return Checkout({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > type: "session", // for checkout sessions > })(request); > }, > }, > }, > }); > ``` > > ```bash Static Checkout cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/checkout?productId=pdt_fqJhl7pxKWiLhwQR042rh' > ``` > > ```bash Checkout Session cURL Example expandable theme={null} > curl --request POST \ > --url https://example.com/api/checkout \ > --header 'Content-Type: application/json' \ > --data '{ > "product_cart": [ > { > "product_id": "pdt_QMDuvLkbVzCRWRQjLNcs", > "quantity": 1 > } > ], > "customer": { > "email": "customer@example.com", > "name": "John Doe" > }, > "return_url": "https://example.com/success" > }' > ``` > [tab] Customer Portal Handler > > > [!NOTE] > > > > Use this handler to send customers to the Dodo Payments Customer Portal, where they manage their subscriptions and details. > > ```typescript TanStack Route Handler expandable theme={null} > // src/routes/api/customer-portal.ts > import { CustomerPortal } from "@dodopayments/tanstack"; > import { createFileRoute } from "@tanstack/react-router"; > > export const Route = createFileRoute("/api/customer-portal")({ > server: { > handlers: { > GET: async ({ request }) => { > return CustomerPortal({ > bearerToken: process.env.DODO_PAYMENTS_API_KEY, > environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", > })(request); > }, > }, > }, > }); > ``` > > ```bash Customer Portal cURL Example theme={null} > curl --request GET \ > --url 'https://example.com/api/customer-portal?customer_id=cus_9VuW4K7O3GHwasENg31m&send_email=true' > ``` > [tab] Webhook Handler > > > [!NOTE] > > > > Use this handler to receive Dodo Payments webhook events in your TanStack Start app and verify their signatures. > > ```typescript TanStack Route Handler expandable theme={null} > // src/routes/api/webhook.ts > import { Webhooks } from "@dodopayments/tanstack"; > import { createFileRoute } from "@tanstack/react-router"; > > export const Route = createFileRoute("/api/webhook")({ > server: { > handlers: { > POST: async ({ request }) => { > return Webhooks({ > webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, > onPayload: async (payload) => { > console.log(payload); > }, > })(request); > }, > }, > }, > }); > ``` ## Checkout Route Handler The checkout handler supports all three ways to take payments with Dodo Payments: * **Static Payment Links:** Shareable URLs that collect payments without code. * **Dynamic Payment Links (deprecated):** Payment links you generate with custom details. They use deprecated endpoints. * **Checkout Sessions:** Hosted checkout with a product cart, customer details, and customization options. This is the recommended flow. `Checkout` takes these options: | Option | Type | Description | | - | - | - | | `bearerToken` | `string` | Your Dodo Payments API key. | | `environment` | `string` | `test_mode` or `live_mode`. Defaults to `live_mode`. | | `returnUrl` | `string` | Optional. The URL that checkout redirects the customer to after payment. A `return_url` in a POST body takes precedence. | | `type` | `string` | The checkout flow: `static`, `dynamic`, or `session`. Defaults to `static`. | The handler serves static checkout for `GET` requests. For `POST` requests, it creates a dynamic payment link when `type` is `dynamic`, and a checkout session otherwise. > [accordion] Static Checkout (GET) > > ### Supported Query Parameters > > **productId** `string` *required* > > Product identifier, for example `?productId=pdt_nZuwz45WAs64n3l07zpQR`. > > **quantity** `integer` (default: 1) > > Quantity of the product. > > **fullName** `string` > > Customer's full name. Ignored if `firstName` or `lastName` is provided. > > **firstName** `string` > > Customer's first name. > > **lastName** `string` > > Customer's last name. > > **email** `string` > > Customer's email address. > > **country** `string` > > Customer's country, as an ISO 3166-1 alpha-2 code. > > **addressLine** `string` > > Customer's street address. > > **city** `string` > > Customer's city. > > **state** `string` > > Customer's state or province. > > **zipCode** `string` > > Customer's ZIP or postal code. > > **disableFullName** `boolean` > > Set to `true` to disable the full name field. > > **disableFirstName** `boolean` > > Set to `true` to disable the first name field. > > **disableLastName** `boolean` > > Set to `true` to disable the last name field. > > **disableEmail** `boolean` > > Set to `true` to disable the email field. > > **disableCountry** `boolean` > > Set to `true` to disable the country field. > > **disableAddressLine** `boolean` > > Set to `true` to disable the address line field. > > **disableCity** `boolean` > > Set to `true` to disable the city field. > > **disableState** `boolean` > > Set to `true` to disable the state field. > > **disableZipCode** `boolean` > > Set to `true` to disable the ZIP code field. > > **paymentCurrency** `string` > > Payment currency, for example `USD`. > > **showCurrencySelector** `boolean` (default: true) > > Show or hide the currency selector. > > **paymentAmount** `number` > > Fixes the amount charged, in major currency units, for example `12.5` for \$12.50. Works with Pay What You Want products only, and is ignored if it's below the product's minimum price. > > **showDiscounts** `boolean` (default: true) > > Show or hide the discounts section. > > **metadata\_**\* `string` > > Any query parameter that starts with `metadata_` is passed to checkout as metadata, for example `metadata_orderId=123`. > > A disable flag takes effect only when the matching field has a value, for example `email` with `disableEmail=true`. The handler adds `returnUrl` from its config to the link as `redirect_url`. > > > [!WARNING] > > > > If `productId` is missing, the handler returns a 400 response. Invalid query parameters, or a product that doesn't exist in your account, also return 400. > > ### Response Format > > Static checkout returns a JSON response with the checkout URL. In test mode, the URL uses `test.checkout.dodopayments.com`: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_fqJhl7pxKWiLhwQR042rh?quantity=1&redirect_url=https%3A%2F%2Fyourdomain.com%2Fcheckout%2Fsuccess" > } > ``` > [accordion] Dynamic Checkout (POST) > > * Send the parameters as a JSON body in a POST request. > * Supports both one-time and recurring payments. The handler retrieves the product, then creates a subscription if the product is recurring and a one-time payment otherwise. > * The body needs `billing` (with `street`, `city`, `state`, `country`, and `zipcode`) and `customer`, plus `product_id` or `product_cart`. Subscriptions need `product_id`. > * For every supported body field, see: > * [Request body for a One Time Payment Product](https://docs.dodopayments.com/api-reference/payments/post-payments) > > * [Request body for a Subscription Product](https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions) > > > [!WARNING] > > > > Dynamic checkout proxies the deprecated `POST /payments` and `POST /subscriptions` endpoints. It keeps working for existing integrations, but new integrations should use checkout sessions. > > ### Response Format > > Dynamic checkout returns a JSON response with the payment link as the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/cbq" > } > ``` > [accordion] Checkout Sessions (POST) > > Checkout sessions create a hosted checkout for one-time purchases and subscriptions, with full control over customization. `product_cart` is the only required field, and it needs at least one product. If the body has no `return_url`, the handler uses `returnUrl` from its config. > > Each `checkout_url` works once and expires after 24 hours, or after 15 minutes when you pass `confirm: true`. A session created with `payment_method_id` returns no `checkout_url`, so the handler responds with 400. > > For more details and every supported field, see the [Checkout Sessions Integration Guide](https://docs.dodopayments.com/developer-resources/checkout-session). > > ### Response Format > > Checkout sessions return a JSON response with the checkout URL: > > ```json theme={null} > { > "checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa" > } > ``` ## Customer Portal Route Handler The Customer Portal route handler creates a Customer Portal session for the customer you pass and redirects the browser to it. `CustomerPortal` takes the same `bearerToken` and `environment` options as `Checkout`. > [!WARNING] > > The handler doesn't check who is calling it. Anyone who requests it with a customer ID gets that customer's portal. Protect the route with your own authentication, and pass only the signed-in user's customer ID. ### Query Parameters **customer\_id** `string` *required* The customer ID for the portal session, for example `?customer_id=cus_123`. **send\_email** `boolean` If set to `true`, Dodo Payments also emails the portal link to the customer. The handler returns 400 if `customer_id` is missing, and 500 if the portal session can't be created. ## Webhook Route Handler The webhook route handler verifies each request with your webhook secret, passed as `webhookKey`, before it runs your code: * **Method:** Only POST requests are supported. Other methods return 405. * **Signature Verification:** Verifies the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with `webhookKey`, following the Standard Webhooks specification. Returns 401 if verification fails. * **Payload Validation:** Validates the payload with Zod. Returns 400 for an invalid payload. * **Error Handling:** * 401: Invalid signature * 400: Invalid payload * 500: Internal error during verification * **Event Routing:** Calls `onPayload` for every event, then the handler for the event's type, and returns 200. The adaptor doesn't catch errors thrown in your handlers. They propagate to TanStack Start, and the request fails. ### Supported Webhook Event Handlers Every handler is optional and async, and receives the verified payload for its event type: ```typescript TypeScript expandable theme={null} onPayload?: (payload: WebhookPayload) => Promise; onPaymentSucceeded?: (payload: WebhookPayload) => Promise; onPaymentFailed?: (payload: WebhookPayload) => Promise; onPaymentProcessing?: (payload: WebhookPayload) => Promise; onPaymentCancelled?: (payload: WebhookPayload) => Promise; onRefundSucceeded?: (payload: WebhookPayload) => Promise; onRefundFailed?: (payload: WebhookPayload) => Promise; onDisputeOpened?: (payload: WebhookPayload) => Promise; onDisputeExpired?: (payload: WebhookPayload) => Promise; onDisputeAccepted?: (payload: WebhookPayload) => Promise; onDisputeCancelled?: (payload: WebhookPayload) => Promise; onDisputeChallenged?: (payload: WebhookPayload) => Promise; onDisputeWon?: (payload: WebhookPayload) => Promise; onDisputeLost?: (payload: WebhookPayload) => Promise; onSubscriptionActive?: (payload: WebhookPayload) => Promise; onSubscriptionOnHold?: (payload: WebhookPayload) => Promise; onSubscriptionRenewed?: (payload: WebhookPayload) => Promise; onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise; onSubscriptionCancelled?: (payload: WebhookPayload) => Promise; onSubscriptionFailed?: (payload: WebhookPayload) => Promise; onSubscriptionExpired?: (payload: WebhookPayload) => Promise; onSubscriptionUpdated?: (payload: WebhookPayload) => Promise; onSubscriptionPaused?: (payload: WebhookPayload) => Promise; onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise; onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise; onLicenseKeyCreated?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise; onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise; onDunningStarted?: (payload: WebhookPayload) => Promise; onDunningRecovered?: (payload: WebhookPayload) => Promise; onCreditAdded?: (payload: WebhookPayload) => Promise; onCreditDeducted?: (payload: WebhookPayload) => Promise; onCreditExpired?: (payload: WebhookPayload) => Promise; onCreditRolledOver?: (payload: WebhookPayload) => Promise; onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise; onCreditOverageCharged?: (payload: WebhookPayload) => Promise; onCreditOverageReset?: (payload: WebhookPayload) => Promise; onCreditManualAdjustment?: (payload: WebhookPayload) => Promise; onCreditBalanceLow?: (payload: WebhookPayload) => Promise; onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise; onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise; onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise; onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise; onPayoutCreated?: (payload: WebhookPayload) => Promise; onPayoutOnHold?: (payload: WebhookPayload) => Promise; onPayoutInProgress?: (payload: WebhookPayload) => Promise; onPayoutFailed?: (payload: WebhookPayload) => Promise; onPayoutSuccess?: (payload: WebhookPayload) => Promise; ``` For what each event means, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). ## Prompt for LLM Copy this prompt into your AI coding assistant to have it add the adaptor to your project. To give your agent the Dodo Payments docs and skills as well, install the [Agent Plugin](/developer-resources/build-with-ai-coding-agents). ```text expandable theme={null} You are an expert TanStack developer assistant. Your task is to guide a user through integrating the @dodopayments/tanstack adapter into their existing TanStack Start project. The @dodopayments/tanstack adapter provides request handlers for Dodo Payments' Checkout, Customer Portal, and Webhook functionalities. Each handler takes a Request and returns a Response, so call it from a TanStack Start server route. First, install the necessary packages. Use the package manager appropriate for your project (npm, yarn, or bun) based on the presence of lock files (e.g., package-lock.json for npm, yarn.lock for yarn, bun.lockb for bun): npm install @dodopayments/tanstack The examples below define server routes with createFileRoute and server.handlers. If the project uses an older TanStack Start release that exports createServerFileRoute from @tanstack/react-start/server instead, use createServerFileRoute("/api/checkout").methods({ GET, POST }) with the same handler bodies. Here's how you should structure your response: Ask the user which functionalities they want to integrate. "Which parts of the @dodopayments/tanstack adapter would you like to integrate into your project? You can choose one or more of the following: Checkout Route Handler (for handling product checkouts) Customer Portal Route Handler (for managing customer subscriptions/details) Webhook Route Handler (for receiving Dodo Payments webhook events) All (integrate all three)" Based on the user's selection, provide detailed integration steps for each chosen functionality. If Checkout Route Handler is selected: Purpose: This handler manages static checkout and checkout sessions. Both return JSON responses with checkout URLs for programmatic handling. File Creation: Create a new file at src/routes/api/checkout.ts in your TanStack Start project. Code Snippet: // src/routes/api/checkout.ts import { Checkout } from "@dodopayments/tanstack"; import { createFileRoute } from "@tanstack/react-router"; export const Route = createFileRoute("/api/checkout")({ server: { handlers: { GET: async ({ request }) => { return Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", type: "static", // optional, defaults to 'static' })(request); }, POST: async ({ request }) => { return Checkout({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, returnUrl: process.env.DODO_PAYMENTS_RETURN_URL, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", type: "session", // for checkout sessions })(request); }, }, }, }); Configuration & Usage: bearerToken: Your Dodo Payments API key. It's recommended to set this via the DODO_PAYMENTS_API_KEY environment variable. returnUrl: (Optional) The URL to redirect the user to after a successful checkout. A return_url in the POST body takes precedence. environment: (Optional) Set to "test_mode" for testing, or omit/set to "live_mode" for production. type: (Optional) Set to "static" for GET/static checkout or "session" for POST/checkout sessions. Static Checkout (GET) Query Parameters: productId (required): Product identifier (e.g., ?productId=pdt_nZuwz45WAs64n3l07zpQR) quantity (optional): Quantity of the product Customer Fields (optional): fullName, firstName, lastName, email, country, addressLine, city, state, zipCode Disable Flags (optional, set to true to disable): disableFullName, disableFirstName, disableLastName, disableEmail, disableCountry, disableAddressLine, disableCity, disableState, disableZipCode Advanced Controls (optional): paymentCurrency, showCurrencySelector, paymentAmount, showDiscounts Metadata (optional): Any query parameter starting with metadata_ (e.g., ?metadata_userId=abc123) Returns: {"checkout_url": "https://test.checkout.dodopayments.com/buy/pdt_nZuwz45WAs64n3l07zpQR?quantity=1"} Checkout Sessions (POST) - (Recommended) A more customizable checkout experience. Returns JSON with checkout_url: Parameters are sent as a JSON body, and product_cart is required. Supports both one-time and recurring payments. Returns: {"checkout_url": "https://test.checkout.dodopayments.com/session/cks_Gi6KGJ2zFJo9rq9Ukifwa"}. For a complete list of supported fields, refer to: Checkout Sessions Integration Guide: https://docs.dodopayments.com/developer-resources/checkout-session Error Handling: If productId is missing or other query parameters are invalid, the handler will return a 400 response. If Customer Portal Route Handler is selected: Purpose: This handler redirects a customer to their Dodo Payments customer portal. It does not authenticate the caller, so protect the route and pass only the signed-in user's customer ID. File Creation: Create a new file at src/routes/api/customer-portal.ts in your TanStack Start project. Code Snippet: // src/routes/api/customer-portal.ts import { CustomerPortal } from "@dodopayments/tanstack"; import { createFileRoute } from "@tanstack/react-router"; export const Route = createFileRoute("/api/customer-portal")({ server: { handlers: { GET: async ({ request }) => { return CustomerPortal({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, environment: process.env.DODO_PAYMENTS_ENVIRONMENT as "test_mode" | "live_mode", })(request); }, }, }, }); Query Parameters: customer_id (required): The customer ID for the portal session (e.g., ?customer_id=cus_123) send_email (optional, boolean): If set to true, sends an email to the customer with the portal link. Returns 400 if customer_id is missing. If Webhook Route Handler is selected: Purpose: This handler processes incoming webhook events from Dodo Payments, allowing your application to react to events like successful payments, refunds, or subscription changes. File Creation: Create a new file at src/routes/api/webhook.ts in your TanStack Start project. Code Snippet: // src/routes/api/webhook.ts import { Webhooks } from "@dodopayments/tanstack"; import { createFileRoute } from "@tanstack/react-router"; export const Route = createFileRoute("/api/webhook")({ server: { handlers: { POST: async ({ request }) => { return Webhooks({ webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, onPayload: async (payload) => { console.log(payload); }, })(request); }, }, }, }); Handler Details: Method: Only POST requests are supported. Other methods return 405. Signature Verification: The handler verifies the webhook signature using the webhookKey and returns 401 if verification fails. Payload Validation: The payload is validated with Zod. Returns 400 for invalid payloads. Error Handling: 401: Invalid signature 400: Invalid payload 500: Internal error during verification Event Routing: Calls onPayload for every event, then the event handler that matches the payload type. Supported Webhook Event Handlers: onPayload?: (payload: WebhookPayload) => Promise onPaymentSucceeded?: (payload: WebhookPayload) => Promise onPaymentFailed?: (payload: WebhookPayload) => Promise onPaymentProcessing?: (payload: WebhookPayload) => Promise onPaymentCancelled?: (payload: WebhookPayload) => Promise onRefundSucceeded?: (payload: WebhookPayload) => Promise onRefundFailed?: (payload: WebhookPayload) => Promise onDisputeOpened?: (payload: WebhookPayload) => Promise onDisputeExpired?: (payload: WebhookPayload) => Promise onDisputeAccepted?: (payload: WebhookPayload) => Promise onDisputeCancelled?: (payload: WebhookPayload) => Promise onDisputeChallenged?: (payload: WebhookPayload) => Promise onDisputeWon?: (payload: WebhookPayload) => Promise onDisputeLost?: (payload: WebhookPayload) => Promise onSubscriptionActive?: (payload: WebhookPayload) => Promise onSubscriptionOnHold?: (payload: WebhookPayload) => Promise onSubscriptionRenewed?: (payload: WebhookPayload) => Promise onSubscriptionPlanChanged?: (payload: WebhookPayload) => Promise onSubscriptionCancelled?: (payload: WebhookPayload) => Promise onSubscriptionFailed?: (payload: WebhookPayload) => Promise onSubscriptionExpired?: (payload: WebhookPayload) => Promise onSubscriptionUpdated?: (payload: WebhookPayload) => Promise onSubscriptionPaused?: (payload: WebhookPayload) => Promise onSubscriptionUnpaused?: (payload: WebhookPayload) => Promise onSubscriptionUpdatePaymentMethod?: (payload: WebhookPayload) => Promise onLicenseKeyCreated?: (payload: WebhookPayload) => Promise onAbandonedCheckoutDetected?: (payload: WebhookPayload) => Promise onAbandonedCheckoutRecovered?: (payload: WebhookPayload) => Promise onDunningStarted?: (payload: WebhookPayload) => Promise onDunningRecovered?: (payload: WebhookPayload) => Promise onCreditAdded?: (payload: WebhookPayload) => Promise onCreditDeducted?: (payload: WebhookPayload) => Promise onCreditExpired?: (payload: WebhookPayload) => Promise onCreditRolledOver?: (payload: WebhookPayload) => Promise onCreditRolloverForfeited?: (payload: WebhookPayload) => Promise onCreditOverageCharged?: (payload: WebhookPayload) => Promise onCreditOverageReset?: (payload: WebhookPayload) => Promise onCreditManualAdjustment?: (payload: WebhookPayload) => Promise onCreditBalanceLow?: (payload: WebhookPayload) => Promise onEntitlementGrantCreated?: (payload: WebhookPayload) => Promise onEntitlementGrantDelivered?: (payload: WebhookPayload) => Promise onEntitlementGrantFailed?: (payload: WebhookPayload) => Promise onEntitlementGrantRevoked?: (payload: WebhookPayload) => Promise onPayoutCreated?: (payload: WebhookPayload) => Promise onPayoutOnHold?: (payload: WebhookPayload) => Promise onPayoutInProgress?: (payload: WebhookPayload) => Promise onPayoutFailed?: (payload: WebhookPayload) => Promise onPayoutSuccess?: (payload: WebhookPayload) => Promise Environment Variable Setup: To ensure the adapter functions correctly, you will need to manually set up the following environment variables in your TanStack project's deployment environment (e.g., Vercel, Netlify, AWS, etc.): DODO_PAYMENTS_API_KEY: Your Dodo Payments API Key (required for Checkout and Customer Portal). DODO_PAYMENTS_RETURN_URL: (Optional) The URL to redirect to after a successful checkout (for Checkout handler). DODO_PAYMENTS_WEBHOOK_KEY: Your Dodo Payments Webhook Secret (required for Webhook handler). DODO_PAYMENTS_ENVIRONMENT: test_mode or live_mode. The handlers default to live_mode. Example .env file: DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-secret DODO_PAYMENTS_RETURN_URL=your-return-url DODO_PAYMENTS_ENVIRONMENT=test_mode Usage in your code: bearerToken: process.env.DODO_PAYMENTS_API_KEY webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY! Important: Never commit sensitive environment variables directly into your version control. Use environment variables for all sensitive information. If the user needs assistance setting up environment variables for their specific deployment environment, ask them what platform they are using (e.g., Vercel, Netlify, AWS, etc.), and provide guidance. You can also add comments to their PR or chat depending on the context ``` # Pricing as Code with Terraform Source: https://docs.dodopayments.com/developer-resources/terraform-provider Manage products, prices, meters, credits, discounts, and webhooks as code with the Dodo Payments Terraform provider, on Terraform or OpenTofu. Review each pricing change in a pull request and apply it from CI. > [card] [Terraform Registry](https://registry.terraform.io/providers/dodopayments/dodopayments/latest) > > Provider documentation for each resource, data source, and action. > [card] [OpenTofu Registry](https://search.opentofu.org/provider/dodopayments/dodopayments/latest) > > The same provider, signed and published for OpenTofu. > [card] [Example Repository](https://github.com/dodopayments/terraform-dodopayments-example) > > A complete AI SaaS catalog with plan, apply, drift, and end-to-end workflows. ## Overview The Dodo Payments Terraform provider keeps your pricing in configuration files in your Git repository. You define products, prices, meters, credits, discounts, entitlements, and webhook endpoints in code. A pricing change then goes through the same steps as a code change: a pull request, a reviewed plan, and an apply from CI. This gives your pricing four properties that dashboard edits do not have: * **Review before release.** `terraform plan` shows each product, price, and discount that a change creates, updates, or archives. A teammate approves the plan before customers see the new price. * **Version history.** Each pricing change is a commit with an author, a reviewer, and a reason. To undo a change, revert the commit and apply again. * **One catalog in each mode.** The same configuration builds your catalog in test mode and in live mode. You test a pricing change end to end in test mode, then apply the same commit to live mode. * **Drift detection.** A scheduled `terraform plan` finds changes that someone made in the dashboard, so the repository stays the source of truth. The provider works with Terraform and with [OpenTofu](#using-opentofu). This page uses `terraform` in its commands. With OpenTofu, run `tofu` instead. The provider manages the catalog: the objects that define what you sell and at what price. Customers, subscriptions, payments, and refunds are not in the provider. Your application creates them at runtime with the [API or an SDK](/developer-resources/dodo-payments-sdks). ## What You Can Manage Each catalog object has a resource. Each resource also has a data source for one object, a data source for a list of objects, and a list resource for `terraform query`. | Catalog Object | Terraform Resource | Feature Page | | - | - | - | | Products with one-time, subscription, or usage-based prices | `dodopayments_product` | [Products](/features/products) | | Fixed prices in other currencies | `dodopayments_product_localized_price` | [Localized Pricing](/features/localized-pricing) | | Product collections with plan change rules | `dodopayments_product_collection` | [Product Collections](/features/product-collections) | | Add-ons | `dodopayments_addon` | [Add-ons](/features/addons) | | Meters | `dodopayments_meter` | [Meters](/features/usage-based-billing/meters) | | Credit entitlements | `dodopayments_credit_entitlement` | [Credit-Based Billing](/features/credit-based-billing) | | Entitlements, such as feature flags and license keys | `dodopayments_entitlement` | [Entitlements](/features/entitlements/introduction) | | Discount codes | `dodopayments_discount` | [Discounts](/features/discount-codes) | | Brands | `dodopayments_brand` | [Multi-Brand Setup](/features/multi-brands) | | Webhook endpoints | `dodopayments_webhook` | [Webhooks](/developer-resources/webhooks) | The provider also has these Terraform objects: * The ephemeral resource `dodopayments_webhook_secret` reads the signing secret of a webhook endpoint without a copy in the state. * The actions `dodopayments_product_unarchive`, `dodopayments_addon_unarchive`, `dodopayments_meter_unarchive`, `dodopayments_product_collection_unarchive`, and `dodopayments_credit_entitlement_undelete` restore an archived or deleted object. Actions need Terraform 1.14 or later. OpenTofu does not support actions. ## Getting Started You need Terraform 1.12 or later, or OpenTofu 1.12 or later, and a test mode API key. Create the key in the dashboard under **Developer → API Keys** while test mode is on. > [!WARNING] > > The provider connects to live mode when you do not set `environment`. Set `environment = "test_mode"` until you are ready to change your live catalog. **1. Configure the Provider** Create a file named `versions.tf`: ```hcl versions.tf theme={null} terraform { required_version = ">= 1.12" required_providers { dodopayments = { source = "dodopayments/dodopayments" version = "~> 0.2" } } } provider "dodopayments" { environment = "test_mode" } ``` **2. Set the API Key** The provider reads the API key from the `DODO_PAYMENTS_API_KEY` environment variable: ```bash theme={null} export DODO_PAYMENTS_API_KEY="dodo_test_..." ``` **3. Define a Product** Create a file named `products.tf`. Prices are in the smallest currency unit, so `4900` is \$49.00: ```hcl products.tf expandable theme={null} resource "dodopayments_product" "pro_monthly" { name = "Pro (Monthly)" description = "Pro plan, billed monthly." tax_category = "saas" price = { type = "recurring_price" currency = "USD" price = 4900 tax_inclusive = false payment_frequency_count = 1 payment_frequency_interval = "Month" subscription_period_count = 20 subscription_period_interval = "Year" trial_period_days = 14 } metadata = { managed_by = "terraform" } } output "pro_monthly_product_id" { value = dodopayments_product.pro_monthly.id } ``` For the meaning of the subscription period, see [Subscriptions](/features/subscription). **4. Plan and Apply** Download the provider, review the plan, and create the product: ```bash theme={null} terraform init terraform plan terraform apply ``` `terraform apply` prints the new product ID. The product is also in the dashboard, in test mode. ## Modeling a Pricing Catalog A real catalog has tiers, billing cycles, and rules between them. In Terraform, you write the pricing model once as data and generate the objects from it. To change a price, you change one number, and the plan shows each object that the change affects. This example builds three tiers in two billing cycles, puts them in one product collection, and adds a launch discount for the annual plans: ```hcl catalog.tf expandable theme={null} locals { # Prices are in cents. tiers = { starter = { title = "Starter", monthly = 1900, annual = 19000 } pro = { title = "Pro", monthly = 4900, annual = 49000 } scale = { title = "Scale", monthly = 14900, annual = 149000 } } tier_order = ["starter", "pro", "scale"] cycles = { monthly = { interval = "Month", label = "Monthly" } annual = { interval = "Year", label = "Annual" } } # 3 tiers x 2 cycles = 6 plans, keyed "pro_annual" and so on. plans = { for pair in setproduct(keys(local.tiers), keys(local.cycles)) : "${pair[0]}_${pair[1]}" => { tier = pair[0] cycle = pair[1] title = local.tiers[pair[0]].title monthly = local.tiers[pair[0]].monthly price = pair[1] == "monthly" ? local.tiers[pair[0]].monthly : local.tiers[pair[0]].annual interval = local.cycles[pair[1]].interval label = local.cycles[pair[1]].label } } } resource "dodopayments_product" "plan" { for_each = local.plans name = "${each.value.title} (${each.value.label})" tax_category = "saas" price = { type = "recurring_price" currency = "USD" price = each.value.price tax_inclusive = false payment_frequency_count = 1 payment_frequency_interval = each.value.interval subscription_period_count = 20 subscription_period_interval = "Year" } lifecycle { precondition { condition = each.value.cycle == "monthly" || each.value.price <= floor(each.value.monthly * 12 * 0.9) error_message = "An annual plan must cost at least 10% less than 12 monthly payments." } } } resource "dodopayments_product_collection" "plans" { name = "Plans" groups = [ for cycle in ["monthly", "annual"] : { group_name = local.cycles[cycle].label products = [ for tier in local.tier_order : { product_id = dodopayments_product.plan["${tier}_${cycle}"].id } ] } ] effective_at_on_upgrade = "immediately" proration_billing_mode_on_upgrade = "prorated_immediately" effective_at_on_downgrade = "next_billing_date" proration_billing_mode_on_downgrade = "do_not_bill" } resource "dodopayments_discount" "launch" { name = "Launch: 20% off annual plans" code = "LAUNCH20" type = "percentage" amount = 2000 # basis points restricted_to = [for tier in local.tier_order : dodopayments_product.plan["${tier}_annual"].id] expires_at = "2027-06-30T23:59:59Z" subscription_cycles = 1 } ``` This configuration shows patterns that the dashboard cannot give you: * **One source for each price.** The discount and the collection refer to the products, not to product IDs. When you add a tier, the collection and the discount get the new plan in the same apply. * **Pricing rules as checks.** The `precondition` stops the plan when an annual price does not save at least 10%. Use `precondition` blocks and `check` blocks for each rule that your pricing must keep. * **Reviewable changes.** When you change `pro.monthly` from `4900` to `5900`, the plan shows one change to `dodopayments_product.plan["pro_monthly"]` before anything changes. The [example repository](https://github.com/dodopayments/terraform-dodopayments-example) extends this model with meters, a shared credit balance with rollover and overage, a usage-based Enterprise plan, localized EUR and INR prices, add-ons, credit packs, and three discount types. ## Reviewing Pricing Changes With GitOps With GitOps, the main branch of your repository is the record of your live catalog. Nobody edits pricing in the dashboard. Each change is a pull request, and CI applies the change after the merge. ```mermaid theme={null} %%{init: {"sequence": {"mirrorActors": false}}}%% sequenceDiagram autonumber actor Dev as You participant Git as Git repository participant CI participant Dodo as Dodo Payments rect rgba(120, 120, 140, 0.12) Note over Dev,Dodo: Pull request Dev->>Git: Open a pull request with a pricing change Git->>CI: Run terraform plan CI->>Dodo: Read the current catalog CI-->>Git: Post the plan summary end rect rgba(120, 120, 140, 0.12) Note over Dev,Dodo: Merge to main Dev->>Git: Approve the plan and merge Git->>CI: Run terraform apply CI->>Dodo: Create, update, or archive objects end rect rgba(120, 120, 140, 0.12) Note over Dev,Dodo: Each night CI->>Dodo: Compare the catalog with main alt Drift found CI-->>Git: Open a drift issue else No drift CI-->>Git: Close the open drift issue end end ``` A GitOps setup for the provider has these parts: | Part | What It Does | | - | - | | Remote state | Keeps the Terraform state in a shared backend with locking, such as Google Cloud Storage, Amazon S3, or HCP Terraform. Never commit the state file. | | Plan on pull request | Runs `terraform plan` for each pull request and posts the summary as a comment. Reviewers approve the plan, not only the code. | | Apply on merge | Runs `terraform apply` on the main branch only. The job plans again, saves the plan to a file, and applies that file, so the apply does what the job summary shows. | | Drift check | Runs `terraform plan -detailed-exitcode` on a schedule. Exit code `2` means that the dashboard differs from the main branch. | | API key in CI secrets | Stores `DODO_PAYMENTS_API_KEY` in the secret store of your CI system. Never write the key in the configuration. | This GitHub Actions job applies the catalog after a merge to the main branch: ```yaml .github/workflows/apply.yml expandable theme={null} name: apply on: push: branches: [main] concurrency: group: apply-catalog cancel-in-progress: false jobs: apply: runs-on: ubuntu-latest env: DODO_PAYMENTS_API_KEY: ${{ secrets.DODO_PAYMENTS_API_KEY }} TF_IN_AUTOMATION: "1" steps: - uses: actions/checkout@v6 - uses: hashicorp/setup-terraform@v4 - run: terraform init -input=false - run: terraform plan -input=false -out=tfplan - run: terraform apply -input=false tfplan ``` The job plans again after the merge, so its plan can differ from the plan in the pull request. This occurs when the dashboard or another merge changed the catalog after the review. Compare the job summary with the reviewed plan, and use the drift check to find dashboard changes early. The `concurrency` group makes a second apply wait for the first one. The job also needs credentials for your state backend. The example repository uses Workload Identity Federation, so CI has no long-lived cloud key. It also has the plan, drift, and end-to-end workflows. > [!TIP] > > Give the plan job read-only access to the state, and run its plan with `-lock=false`, because a state lock needs write access on most backends. Give write access only to the main branch. Then a pull request can show a plan, but only a merge can change your catalog. ## Promoting Changes From Test Mode to Live Mode Each API key works in one mode, and object IDs are different in each mode. Keep one state for each mode, and refer to resources instead of writing IDs in the configuration. Then the same configuration builds the same catalog in both modes. Set the mode with a variable or with the `DODO_PAYMENTS_ENVIRONMENT` environment variable: ```hcl theme={null} variable "environment" { type = string validation { condition = contains(["test_mode", "live_mode"], var.environment) error_message = "Set environment to test_mode or live_mode." } } provider "dodopayments" { environment = var.environment } ``` To release a pricing change: **1. Apply in Test Mode** Apply the commit with the test mode API key and the test mode state. **2. Test the Change** Create a checkout for the changed products in test mode. Use the [test cards](/miscellaneous/testing-process) to complete a purchase. **3. Apply in Live Mode** Apply the same commit with the live mode API key and the live mode state. ## Detecting Dashboard Changes A change in the dashboard does not update your configuration. The next `terraform apply` reverts each dashboard change to an argument that your configuration sets. To find these changes before an apply does, run a plan on a schedule: ```bash theme={null} terraform plan -input=false -lock=false -detailed-exitcode ``` The command returns `0` when the catalog matches the configuration and `2` when it does not. The example repository runs this command each night. When the result is `2`, it opens an issue with the summary of the plan. When a later run returns `0`, it closes the issue. To keep a dashboard change, copy it into the configuration in a pull request. To discard it, run the apply workflow again. ## Importing Existing Products You can bring objects that you created in the dashboard under Terraform management. Import an object with an `import` block and its ID: ```hcl theme={null} import { to = dodopayments_product.pro_monthly identity = { id = "pdt_0NXyZ1aBcD2eFgH3iJkLm" } } ``` With Terraform 1.14 or later, `terraform query` lists the objects in your account and writes the configuration for you. Create a file with the `.tfquery.hcl` extension: ```hcl catalog.tfquery.hcl theme={null} list "dodopayments_product" "all" { provider = dodopayments include_resource = true } ``` Then generate a `resource` block and an `import` block for each product: ```bash theme={null} terraform query -generate-config-out=generated.tf ``` Move the blocks that you want into your configuration, run `terraform plan`, and confirm that the plan imports the objects with no other changes. > [!NOTE] > > OpenTofu does not have `terraform query`. With OpenTofu, write an `import` block for each object, then run `tofu plan -generate-config-out=generated.tf` to write the configuration. ## Keeping the Webhook Secret Out of State The ephemeral resource `dodopayments_webhook_secret` reads the signing secret of a webhook endpoint during a run. Terraform does not write an ephemeral value to the plan or the state. Pass the secret to a write-only argument, such as the secret data of a secret manager: ```hcl theme={null} resource "dodopayments_webhook" "billing" { url = "https://example.com/webhooks/dodo" filter_types = ["payment.succeeded", "subscription.active", "subscription.cancelled"] } ephemeral "dodopayments_webhook_secret" "billing" { webhook_id = dodopayments_webhook.billing.id } resource "google_secret_manager_secret_version" "webhook_signing" { secret = google_secret_manager_secret.webhook_signing.id secret_data_wo = ephemeral.dodopayments_webhook_secret.billing.secret secret_data_wo_version = 1 } ``` Your webhook receiver reads the secret from the secret manager. To verify webhook signatures, see [Webhooks](/developer-resources/webhooks). ## Using OpenTofu The provider is in the [OpenTofu Registry](https://search.opentofu.org/provider/dodopayments/dodopayments/latest) with the same source address, `dodopayments/dodopayments`. The configuration on this page works without changes: ```bash theme={null} tofu init tofu plan tofu apply ``` OpenTofu 1.12 and later support the resources, the data sources, the ephemeral `dodopayments_webhook_secret` resource, and write-only arguments. Two features need Terraform: * `terraform query`. With OpenTofu, [import objects](#importing-existing-products) with `import` blocks. * The actions that restore archived or deleted objects. With OpenTofu, [restore an object](#deleting-a-resource) with the API. The [example repository](https://github.com/dodopayments/terraform-dodopayments-example) catalog applies, plans with no changes, and destroys on OpenTofu 1.12. ## Deleting a Resource When you remove a resource from the configuration, Terraform destroys it. The provider archives some objects and deletes others. An action can restore some of them. The table shows what happens to each object. > [!NOTE] > > OpenTofu does not support actions. With OpenTofu, restore an object with the API endpoint that the action calls, for a [product](/api-reference/products/unarchive-product), a [meter](/api-reference/meters/unarchive-meter), a [product collection](/api-reference/product-collections/unarchive-product-collection), or a [credit entitlement](/api-reference/credit-entitlements/undelete-credit-entitlement). To restore an add-on, call `POST /addons/{id}/unarchive`. | Resource | When Terraform Destroys the Resource | Action That Restores the Object | | - | - | - | | `dodopayments_product` | The provider archives the product. | `dodopayments_product_unarchive` | | `dodopayments_product_localized_price` | The provider archives the localized price. | None | | `dodopayments_product_collection` | The provider deletes the collection. | `dodopayments_product_collection_unarchive` | | `dodopayments_addon` | The provider deletes the add-on. | `dodopayments_addon_unarchive` | | `dodopayments_meter` | The provider archives the meter. | `dodopayments_meter_unarchive` | | `dodopayments_credit_entitlement` | The provider deletes the credit entitlement. | `dodopayments_credit_entitlement_undelete` | | `dodopayments_entitlement` | The provider deletes the entitlement. | None | | `dodopayments_discount` | The provider deletes the discount. | None | | `dodopayments_webhook` | The provider deletes the webhook endpoint. | None | | `dodopayments_brand` | The provider archives the brand. | None | > [!WARNING] > > The API cannot restore an archived brand. Before you remove a `dodopayments_brand` resource, make sure that you do not need the brand again. To prevent an accidental destroy of a product that customers subscribe to, add `prevent_destroy` to its `lifecycle` block. ## Workload Identity From version 0.3.0, the provider can use workload identity federation instead of an API key. Add a `workload_identity` block to the provider configuration. The provider exchanges an OIDC token from your CI platform or HCP Terraform for a short-lived Dodo Payments token. ```hcl theme={null} provider "dodopayments" { environment = "live_mode" workload_identity { identity_provider_id = "wip_..." token_source = "github_actions" } } ``` For the token sources and the HCP Terraform setup, refer to [Workload Identity with Terraform](/developer-resources/workload-identity/terraform). ## Related > [card] [Products](/features/products) > > Product types, prices, and settings that the provider manages. > [card] [Product Collections](/features/product-collections) > > Group plans and set the rules for upgrades and downgrades. > [card] [Credit-Based Billing](/features/credit-based-billing) > > Credit balances with rollover, expiry, and overage. > [card] [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode) > > How the two modes keep their objects and API keys apart. # Build an AI Image Generator with Usage-Based Billing Source: https://docs.dodopayments.com/developer-resources/usage-based-billing-build-ai-image-generator Build PixelGen AI, a terminal-based AI image generator that sends a usage event for each image and bills customers per image with Dodo Payments. > [!TIP] > > To have your coding agent write the integration, install the [Dodo Agent Plugin](/developer-resources/build-with-ai-coding-agents). It adds the Dodo Payments skills and MCP servers to Claude Code, Codex CLI, Cursor, VS Code / GitHub Copilot, Kiro, and OpenCode. You'll build **PixelGen AI**, a sample AI image generation service that bills customers per image with usage-based billing. You create the billing meter, the product, and sample application code that generates images and reports each one to Dodo Payments as it happens. > [!NOTE] > > This tutorial provides sample code for a terminal application. You can adapt the code to your framework, such as React, Vue, or Angular, and to the way your application collects user input. When you finish, you'll have a working sample service that: * Generates images with OpenAI's `gpt-image-2.5-flare` model. * Tracks every image generation for billing. * Charges customers for the images they generate. * Handles two quality tiers, `medium` and `high`. ## What We're Building PixelGen AI works like this: * **Service**: AI image generation with the OpenAI Image API * **Pricing Model**: Pay per image (\$0.05 per image) * **Free Tier**: 10 free images per customer per month * **Quality Options**: `medium` and `high` quality images, at the same price Before you start, you need: * A Dodo Payments account. * Access to the OpenAI API. OpenAI may require API Organization Verification before you use GPT Image models. * Node.js 22 or later, and working knowledge of TypeScript and Node.js. ## Step 1: Create Your Usage Meter Create a meter in the Dodo Payments dashboard that tracks every image the service generates. The meter counts the billable events. ![Create Meter form in the Dodo Payments dashboard](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-2.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=f9d85a463fba231437151db3d4a2052a) > [!TIP] > > **What you're building**: A meter named "Image Generation Meter" that counts every image generation. **1. Open the Meters Section** 1. Log in to the Dodo Payments dashboard. 2. Go to **Products → Meters** in the sidebar. 3. Click **Create Meter**. The meter form opens. **2. Enter the Meter Details** Enter the details for PixelGen AI: **Meter Name**: `Image Generation Meter` **Description**: `Tracks each AI image generation request made by customers using our OpenAI image service` **Event Name**: `image.generated` > [!WARNING] > > The event name `image.generated` must match the event name the application code sends. Event names are case-sensitive. **3. Configure How Images Are Counted** Set the aggregation, which controls how the meter combines events: **Aggregation Type**: **Count** **Measurement Unit**: `images` > [!NOTE] > > **Count** bills per image generated, not by size or generation time. Each successful image is one billable unit. **4. Add Quality Filtering** ![Event filtering on the meter form with two quality conditions joined by OR](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-3.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=ce231b0559d31723bc12c22cd9ff9d64) Count only real images, not test runs or malformed events: 1. Turn on **Enable Event Filtering**. 2. Set the match logic to **OR**, so an event counts when any condition matches. 3. Add the first condition: * Key: `quality` * Operator: `equals` * Value: `medium` 4. Click **Add condition** and add the second one: * Key: `quality` * Operator: `equals` * Value: `high` > [!TIP] > > With this filter, the meter counts only events whose quality is `medium` or `high`, and ignores test or malformed events. **5. Create Your Meter** 1. Check that every setting matches the values above. After you create a meter, you can't change its event name, aggregation, or filter. 2. Click **Create Meter**. > [!TIP] > > **Meter created.** The "Image Generation Meter" is ready to count image generations. Next, connect it to a billing product. ## Step 2: Create Your Billing Product Create a product that defines the pricing: \$0.05 per image, with 10 free images. The product connects the meter to billing. > [!TIP] > > **What you're building**: A product called "PixelGen AI - Image Generation" that charges \$0.05 per image after the first 10 free images each month. **1. Navigate to Products** 1. In the Dodo Payments dashboard, click **Products** in the sidebar. 2. Click **Add Product**. 3. Under **Pricing Type**, select **Usage Based Billing**. With this pricing type, Dodo Payments bills from meter usage instead of a fixed subscription price. **2. Enter Product Details** Enter these values: **Product Name**: `PixelGen AI - Image Generation` **Description**: `AI-powered image generation service with pay-per-use billing` **Product Image**: Upload a clear, relevant image. > [!NOTE] > > The name and description appear on customer invoices. **3. Connect Your Meter** ![Usage Based Billing pricing on the product form with the Associated Meters section](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-5.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=fd3851a1a070714baf0aec01cff717b8) Check that the product's pricing type is **Usage Based Billing**. Set the **Price** to `0`, so customers pay only for usage, with no base fee. Then link the meter you created: 1. Scroll to the **Associated Meters** section. 2. Click **Add meters**. 3. Select **"Image Generation Meter"** from the dropdown. 4. Confirm that the meter appears in the product configuration. > [!TIP] > > The meter is connected to the product. **4. Set Your Pricing** Define the per-image price and the free tier: ![Meter pricing with price per unit and free threshold fields](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-4.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=b2d07bb408fd79e1b788c1b7092b8bca) **Price per unit**: `0.05`, which is \$0.05 per image. **Free Threshold**: `10`. Each customer gets 10 free images per month. > [!TIP] > > **How billing works**: A customer who generates 25 images in a month pays for 15 images (25 − 10 free). 15 × \$0.05 = \$0.75. **5. Save Your Product** 1. Review the settings: * Name: PixelGen AI - Image Generation * Meter: Image Generation Meter * Price: \$0.05 per image * Free tier: 10 images 2. Click **Save Changes**. > [!TIP] > > **Product created.** Billing is configured, and customers are charged for the images they generate. ## Step 3: Make a Test Purchase Buy the product once in test mode. The purchase creates the customer that the app sends usage events for. **1. Get Your Payment Link** 1. In the Dodo Payments dashboard, go to **Products**. 2. Find the "PixelGen AI - Image Generation" product. 3. Click **Share** next to the product. 4. Copy the payment link. The payment link looks like `https://test.checkout.dodopayments.com/buy/pdt_IgPWlRsfpbPd5jQKezzW1?quantity=1`. **2. Complete a Test Purchase** 1. Open the payment link in a new browser tab. 2. Enter [test payment details](/miscellaneous/testing-process) and complete the purchase. > [!TIP] > > After the payment succeeds, the purchase creates a customer. The application code uses that customer's ID. **3. Find Your Customer ID** 1. Go back to the Dodo Payments dashboard. 2. Go to **Sales → Customers** in the sidebar. 3. Find the customer you created, by its test email address. 4. Copy the customer ID. It looks like `cus_abc123def456`. > [!NOTE] > > Save this customer ID. The sample application sets it in the code, so every event is recorded for this customer. ## Step 4: Build the Sample Application With billing set up and a test customer created, build the sample PixelGen AI application. It generates an image and reports it to Dodo Payments for billing. > [!NOTE] > > The sample calls OpenAI's `gpt-image-2.5-flare` model through the Image API. The Image API returns base64-encoded image data, so the sample saves each image as a PNG file. The Dodo Payments part (the meter, the product, and the `image.generated` usage event) doesn't depend on the model. **1. Set Up Your Project** Create a directory and initialize the project: ```bash theme={null} mkdir pixelgen-ai cd pixelgen-ai npm init -y ``` **2. Install Dependencies** Install the packages: ```bash theme={null} npm install openai dotenv npm install -D typescript @types/node ts-node ``` **3. Create the Main Application** Create a file called `index.ts` and paste in the application code below. The complete PixelGen AI application with billing, plus the matching `.env` and `package.json`: ```typescript index.ts expandable theme={null} import 'dotenv/config'; import OpenAI from 'openai'; import * as readline from 'readline'; import { randomUUID } from 'crypto'; import { writeFileSync } from 'fs'; // Initialize OpenAI client const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); // Dodo Payments configuration const DODO_PAYMENTS_CONFIG = { apiKey: process.env.DODO_PAYMENTS_API_KEY, baseUrl: 'https://test.dodopayments.com', customerId: 'cus_FX5FAB43aShGyiHJGIqjB', // Replace with your actual customer ID from Step 3 }; // OpenAI image model used by the sample const IMAGE_MODEL = 'gpt-image-2.5-flare'; interface ImageGenerationOptions { prompt: string; quality?: 'medium' | 'high'; size?: '1024x1024' | '1536x1024' | '1024x1536'; } interface UsageEvent { event_id: string; customer_id: string; event_name: string; timestamp: string; metadata: { quality: string; }; } /** * Send usage event to Dodo Payments for billing tracking */ async function sendUsageEvent(event: UsageEvent): Promise { try { console.log('Sending usage event to Dodo Payments...'); console.log(`URL: ${DODO_PAYMENTS_CONFIG.baseUrl}/events/ingest`); console.log(`API Key present: ${!!DODO_PAYMENTS_CONFIG.apiKey}`); console.log(`API Key length: ${DODO_PAYMENTS_CONFIG.apiKey?.length || 0}`); console.log(`Customer ID: ${DODO_PAYMENTS_CONFIG.customerId}`); const requestBody = { events: [event] }; console.log('Request body:', JSON.stringify(requestBody, null, 2)); const headers = { 'Authorization': `Bearer ${DODO_PAYMENTS_CONFIG.apiKey}`, 'Content-Type': 'application/json', } const response = await fetch(`${DODO_PAYMENTS_CONFIG.baseUrl}/events/ingest`, { method: 'POST', headers: headers, body: JSON.stringify(requestBody), }); console.log(`Response status: ${response.status}`); console.log(`Response headers:`, Object.fromEntries(response.headers.entries())); if (!response.ok) { const errorData = await response.text(); console.log(`Error response body: ${errorData}`); throw new Error(`HTTP ${response.status}: ${errorData}`); } const result = await response.json(); console.log('Usage event sent successfully'); console.log(` • Event ID: ${event.event_id}`); console.log(` • Customer: ${event.customer_id}`); console.log(` • Quality: ${event.metadata.quality}`); } catch (error) { console.error('Failed to send usage event:', error); // In production, you might want to queue failed events for retry throw error; } } async function generateImage(options: ImageGenerationOptions) { const startTime = Date.now(); const eventId = randomUUID(); try { console.log('Generating image...'); console.log(`Prompt: "${options.prompt}"`); console.log(`Quality: ${options.quality || 'medium'}`); console.log(`Size: ${options.size || '1024x1024'}`); const response = await openai.images.generate({ model: IMAGE_MODEL, prompt: options.prompt, n: 1, size: options.size || '1024x1024', quality: options.quality || 'medium', }); const endTime = Date.now(); const duration = (endTime - startTime) / 1000; // The Image API returns base64-encoded image data, so save it as a PNG file const imageBase64 = response.data?.[0]?.b64_json; if (!imageBase64) { throw new Error('OpenAI returned no image data'); } const imagePath = `image-${eventId}.png`; writeFileSync(imagePath, Buffer.from(imageBase64, 'base64')); // Create usage event for Dodo Payments const usageEvent: UsageEvent = { event_id: eventId, customer_id: DODO_PAYMENTS_CONFIG.customerId!, event_name: 'image.generated', timestamp: new Date().toISOString(), metadata: { quality: options.quality || 'medium', } }; // Send usage event to Dodo Payments for billing await sendUsageEvent(usageEvent); console.log('\nImage generated successfully!'); console.log(`Generation Stats:`); console.log(` • Duration: ${duration.toFixed(2)} seconds`); console.log(` • Quality: ${options.quality || 'medium'}`); console.log(` • Image file: ${imagePath}`); return { imagePath: imagePath, duration: duration, eventId: eventId, }; } catch (error) { console.error('Error generating image:', error); // Send failure event for monitoring (optional) try { const failureEvent: UsageEvent = { event_id: eventId, customer_id: DODO_PAYMENTS_CONFIG.customerId!, event_name: 'image.generation.failed', timestamp: new Date().toISOString(), metadata: { quality: options.quality || 'medium', } }; // Note: You might want to create a separate meter for failed attempts // await sendUsageEvent(failureEvent); } catch (eventError) { console.error('Failed to send failure event:', eventError); } throw error; } } async function getUserInput(): Promise { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); return new Promise((resolve) => { rl.question('Enter your image prompt: ', (answer) => { rl.close(); resolve(answer); }); }); } async function main() { console.log('PixelGen AI - Image Generator with Usage Billing\n'); // Validate environment variables const requiredEnvVars = [ 'OPENAI_API_KEY', 'DODO_PAYMENTS_API_KEY' ]; for (const envVar of requiredEnvVars) { if (!process.env[envVar]) { console.error(`Error: ${envVar} environment variable is not set.`); console.log('Please set all required environment variables:'); console.log('export OPENAI_API_KEY="your-openai-key"'); console.log('export DODO_PAYMENTS_API_KEY="dodo_test_..."'); console.log('Note: Customer ID is hardcoded in the application'); process.exit(1); } } try { const prompt = await getUserInput(); if (!prompt.trim()) { console.log('No prompt provided. Exiting...'); return; } const result = await generateImage({ prompt: prompt.trim(), quality: 'medium', // Change to 'high' for higher quality size: '1024x1024', }); console.log('\nProcess completed successfully!'); console.log(`Billing Information:`); console.log(` • Event ID: ${result.eventId}`); console.log(` • Billing will be processed automatically via Dodo Payments`); } catch (error) { console.error('Application error:', error); process.exit(1); } } // Run the application if (require.main === module) { main().catch(console.error); } ``` ```bash .env theme={null} # Create .env file with your API keys OPENAI_API_KEY=your_openai_api_key_here DODO_PAYMENTS_API_KEY=dodo_test_... # Note: Customer ID is hardcoded in the application code ``` ```json package.json theme={null} { "name": "pixelgen-ai", "version": "1.0.0", "description": "AI Image Generation with Usage-Based Billing", "main": "index.js", "scripts": { "start": "ts-node index.ts", "build": "tsc", "dev": "ts-node --watch index.ts" }, "dependencies": { "openai": "^4.0.0", "dotenv": "^16.0.0" }, "devDependencies": { "@types/node": "^20.0.0", "typescript": "^5.0.0", "ts-node": "^10.0.0" } } ``` ## Step 5: Test Your Sample Application Test PixelGen AI end to end and watch the usage reach Dodo Payments. > [!TIP] > > **What you're testing**: You generate a few images, confirm that the events reach Dodo Payments, and check the billing calculation. **1. Set Up Your Environment** 1. Create a `.env` file in the `pixelgen-ai` directory. 2. Add your API keys: ```bash theme={null} OPENAI_API_KEY=sk-your-actual-openai-key DODO_PAYMENTS_API_KEY=dodo_test_... # Customer ID is hardcoded in the application ``` 3. Install the dependencies and run the app: ```bash theme={null} npm install npm start ``` > [!WARNING] > > Use real API keys, and replace the hardcoded customer ID in `index.ts` with the customer ID from Step 3. **2. Generate Your First Test Image** When the app starts, it prints: ```text theme={null} PixelGen AI - Image Generator with Usage Billing Enter your image prompt: ``` Enter this prompt: **"A cute robot painting a landscape"** The output looks like this. The request debug lines that `sendUsageEvent` prints are left out: ```text theme={null} Generating image... Prompt: "A cute robot painting a landscape" Quality: medium Size: 1024x1024 Sending usage event to Dodo Payments... Usage event sent successfully • Event ID: 550e8400-e29b-41d4-a716-446655440000 • Customer: cus_atXa1lklCRRzMicTqfiw2 • Quality: medium Image generated successfully! Generation Stats: • Duration: 8.45 seconds • Quality: medium • Image file: image-550e8400-e29b-41d4-a716-446655440000.png ``` > [!TIP] > > If the output includes "Usage event sent successfully", the billing integration works. **3. Generate a Few More Images** Generate two or three more images to test multiple events. Run `npm start` once per image, with these prompts: 1. **"A sunset over mountains with purple clouds"** 2. **"A steampunk coffee machine in a Victorian kitchen"** 3. **"A friendly dragon reading a book in a library"** Each time, check for the "Usage event sent successfully" message. **4. Check Your Dodo Payments Dashboard** Confirm that Dodo Payments receives the events: 1. Open the Dodo Payments dashboard. 2. Go to **Products → Meters** and open **Image Generation Meter**. 3. Select the **Events** tab. 4. Find your image generation events in the list. **What to look for**: * Event name: `image.generated` * Customer ID: your test customer ID > [!TIP] > > The list has one event for each image you generated. **5. Verify Billing Calculations** Check the usage count: ![Customers tab of the meter showing consumed units per customer](https://mintcdn.com/dodopayments/w9oVTi6CzZMAOQA3/images/usage-based/UBB-1.png?fit=max\&auto=format\&n=w9oVTi6CzZMAOQA3\&q=85\&s=7fb86a266b5aa84f281b680601bd998e) 1. In the meter, select the **Customers** tab. 2. Find your test customer. 3. Check the **Consumed Units** column. **6. Test the Billing Threshold** Go past the free tier to see billing: 1. Generate 8 more images, for 12 in total. 2. Open the meter's **Customers** tab again. 3. Check the values: * **Consumed Units**: 12 * **Chargeable Units**: 2 (12 − 10 free) * **Total Price**: \$0.10 > [!TIP] > > **Usage-based billing works.** Customers are charged for the images they generate. ## Troubleshooting Common problems and their fixes: > [accordion] Events not appearing in dashboard > > **Possible causes:** > > * Event name doesn't match meter configuration exactly > * Customer ID doesn't exist in your account > * API key is invalid or expired > * Network connectivity issues > > **Solutions:** > > 1. Check that the event name matches the meter exactly. It's case-sensitive. > 2. Check that the customer ID exists in Dodo Payments. > 3. Test the API key with a simple API call. > 4. Check network connectivity and firewall settings. ## Congratulations! You Built PixelGen AI You built a sample AI image generator with usage-based billing: > [card] Usage Meter > > An "Image Generation Meter" that counts every image generation event. > [card] Billing Product > > Pricing at \$0.05 per image, with 10 free images per month. > [card] AI Application > > A TypeScript app that generates images with the OpenAI image API. > [card] Automated Billing > > Event tracking that reports each image as it's generated, so customers are billed for usage. # Usage-Based Billing Integration Guide Source: https://docs.dodopayments.com/developer-resources/usage-based-billing-guide Learn how to set up meters and send usage events to enable accurate usage-based billing with Dodo Payments. > [card] [API Reference — Events Ingestion](/api-reference/usage-events/ingest-events) > > Access the complete API documentation for ingesting usage events and test event ingestion requests and responses interactively. > [card] [API Reference — Meters Creation](/api-reference/meters/create-meter) > > Explore the full API documentation for creating meters and interactively test meter creation requests and responses. ## Creating a Meter Meters define how your usage events are aggregated and measured for billing purposes. Before creating a meter, plan your usage tracking strategy: * Identify what usage events you want to track * Determine how events should be aggregated (count, sum, etc.) * Define any filtering requirements for specific use cases ### Step-by-Step Meter Creation Follow this guide to set up your usage meter: **1. Configure Basic Information** Set up the fundamental details for your meter. **Meter Name** `string` *required* A clear, descriptive name that identifies what this meter tracks. Examples: "Tokens", "API Calls", "Storage Usage", "Compute Hours" **Description** `string` A detailed explanation of what this meter measures. Example: "Counts each POST /v1/orders request made by the customer" **Event Name** `string` *required* The event identifier that will trigger this meter. Examples: "token", "api.call", "storage.usage", "compute.session" > [!NOTE] > > The event name must match exactly what you send in your usage events. Event names are case-sensitive. **2. Configure Aggregation Settings** Define how the meter calculates usage from your events. **Aggregation Type** `string` *required* Select how events should be aggregated: > [tab] Count > > Counts the number of events received. > > Use case: API calls, page views, file uploads > > Calculation: Total number of events > [tab] Sum > > Adds up values from a specific property in your events. > > Use case: Data transfer, storage consumption, processing time > > Calculation: Sum of all property values > [tab] Max > > Records the highest value of a specific property during the billing period. > > Use case: Peak concurrent users, maximum storage used, highest bandwidth > > Calculation: Maximum property value observed > [tab] Last > > Uses the most recent value of a specific property. > > Use case: Current plan tier, latest configuration setting > > Calculation: Last recorded property value **Over Property** `string` The property name from event metadata to aggregate over. > [!WARNING] > > This field is required when using Sum, Max, or Last aggregation types. **Measurement Unit** `string` *required* The unit label for display purposes in reports and billing. Examples: "calls", "GB", "hours", "tokens" **3. Configure Event Filtering (Optional)** Set up criteria to control which events are included in the meter. > [!NOTE] > > Event filtering allows you to create sophisticated rules that determine which events contribute to your usage calculations. This is useful for excluding test events, filtering by user tiers, or focusing on specific actions. **Enable Event Filtering** Toggle **Enable Event Filtering** to activate conditional event processing. **Choose Filter Logic** Select how multiple conditions are evaluated: > [tab] AND Logic > > All conditions must be true for an event to be counted. Use this when you need events to meet multiple strict criteria simultaneously. > > **Example:** Count API calls where `user_tier = "premium"` AND `endpoint = "/api/v2/users"` > [tab] OR Logic > > At least one condition must be true for an event to be counted. Use this when you want to include events that meet any of several criteria. > > **Example:** Count events where `method = "POST"` OR `method = "PUT"` OR `method = "DELETE"` **Setting Up Filter Conditions** **1. Add Condition** Click **Add condition** to create a new filter rule. **2. Configure Property Key** Specify the property name from your event metadata. **3. Select Comparator** Choose from available operators: * `equals` — Exact match * `not_equals` — Exclusion filter * `greater_than` — Numeric comparison * `greater_than_or_equals` — Numeric comparison (inclusive) * `less_than` — Numeric comparison * `less_than_or_equals` — Numeric comparison (inclusive) * `contains` — String contains substring * `does_not_contain` — String exclusion filter **4. Set Comparison Value** Set the target value for comparison. **5. Add Groups** Use **Add Group** to create additional condition groups for complex logic. > [!WARNING] > > Filtered properties must be included in your event metadata for the conditions to work properly. Events missing required properties will be excluded from counting. **4. Create Meter** Review your meter configuration and click **Create Meter**. > [!TIP] > > Your meter is now ready to receive and aggregate usage events. ## Linking Meter in a Product Once you have created your meter, you need to link it to a product to enable usage-based billing. This process connects your meter's usage data to pricing rules for customer billing. Linking meters to products establishes the connection between usage tracking and billing: * Products define pricing rules and billing behavior * Meters provide usage data for billing calculations * Multiple meters can be linked to a single product for complex billing scenarios ### Product Configuration Process Transform your usage data into billable charges by properly configuring your product settings: **1. Choose Usage-Based Billing Product Type** Navigate to your product creation or editing page and select **Usage Based Billing** as the pricing type. **2. Select Associated Meter** Click on **Associated Meters** to open the meter selection panel. This panel allows you to configure which meters will track usage for this product. **3. Add Your Meter** In the meter selection panel: 1. Click **Add Meters** to view available meters 2. Select the meter you created from the dropdown list 3. The selected meter will appear in your product configuration **4. Configure Price Per Unit** Set the pricing for each unit of usage tracked by your meter. **Price Per Unit** `number` *required* Define how much to charge for each unit measured by your meter. **Example**: Setting \$0.50 per unit means: * 1,000 units consumed = 1,000 × \$0.50 = \$500.00 charged * 500 units consumed = 500 × \$0.50 = \$250.00 charged * 100 units consumed = 100 × \$0.50 = \$50.00 charged **5. Set Free Threshold (Optional)** Configure a free usage allowance before billing begins. **Free Threshold** `number` Number of units customers can consume at no charge before paid usage calculation starts. **How it works**: * Free threshold: 100 units * Price per unit: \$0.50 * Customer usage: 250 units * **Calculation**: (250 - 100) × \$0.50 = **\$75.00** charged > [!NOTE] > > Free thresholds are ideal for freemium models, trial periods, or providing customers with a base allowance included in their plan. > [!TIP] > > The free threshold applies to each billing cycle, giving customers fresh allowances monthly or according to your billing schedule. **6. Save Configuration** Review your meter and pricing configuration, then click **Save Changes** to finalize the setup. > [!TIP] > > Your product is now configured for usage-based billing and will automatically charge customers based on their measured consumption. **What happens next**: * Usage events sent to your meter will be tracked and aggregated * Billing calculations will apply your pricing rules automatically * Customers will be charged based on actual consumption during each billing cycle > [!NOTE] > > You can add up to 50 meters per product, enabling sophisticated usage tracking across multiple dimensions like API calls, storage, compute time, and custom metrics. ## Sending Usage Events Once your meter is configured, you can start sending usage events from your application to track customer usage. ### Event Structure Each usage event must include these required fields: **event\_id** `string` *required* A unique identifier for this specific event. Must be unique across all events. **customer\_id** `string` *required* The Dodo Payments customer ID this usage should be attributed to. **event\_name** `string` *required* The event name that matches your meter configuration. Event names trigger the appropriate meter. **timestamp** `string` ISO 8601 timestamp when the event occurred. Defaults to the current UTC timestamp if not provided. Must fall within 1 hour in the past and 5 minutes in the future — timestamps outside that window are rejected. **metadata** `object` Additional properties for filtering and aggregation. Include any values referenced in your meter's "Over Property" or filtering conditions. ### Usage Events API Examples Send usage events to your configured meters using the Events API: ```javascript Node.js theme={null} const response = await fetch('https://test.dodopayments.com/events/ingest', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.DODO_PAYMENTS_API_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ events: [ { event_id: "api_call_1234", customer_id: "cus_atXa1lklCRRzMicTqfiw2", event_name: "api.call", timestamp: new Date().toISOString(), metadata: { endpoint: "/v1/orders", method: "POST", response_size: 1024 } } ] }) }); ``` ```python Python theme={null} import os import requests from datetime import datetime, timezone response = requests.post( 'https://test.dodopayments.com/events/ingest', headers={ 'Authorization': f"Bearer {os.environ['DODO_PAYMENTS_API_KEY']}", 'Content-Type': 'application/json' }, json={ 'events': [ { 'event_id': 'api_call_1234', 'customer_id': 'cus_atXa1lklCRRzMicTqfiw2', 'event_name': 'api.call', 'timestamp': datetime.now(timezone.utc).isoformat(), 'metadata': { 'endpoint': '/v1/orders', 'method': 'POST', 'response_size': 1024 } } ] } ) ``` ```curl cURL theme={null} curl -X POST 'https://test.dodopayments.com/events/ingest' \ -H 'Authorization: Bearer dodo_test_...' \ -H 'Content-Type: application/json' \ -d '{ "events": [ { "event_id": "api_call_1234", "customer_id": "cus_atXa1lklCRRzMicTqfiw2", "event_name": "api.call", "timestamp": "2024-01-15T10:30:00Z", "metadata": { "endpoint": "/v1/orders", "method": "POST", "response_size": 1024 } } ] }' ``` ### Key Things to Know for Reliable Ingestion Follow these practices to keep usage tracking accurate and resilient in production. > [!TIP] > > **Use deterministic, idempotent `event_id`s.** The `event_id` must be unique across all events and acts as the idempotency key. A reused `event_id` is treated as a duplicate and not counted again, so retries never double-bill. Derive the ID from the action instead of a random value, e.g. `` `${customer_id}_${action}_${timestamp}` ``. > [!TIP] > > **Batch events, up to 1,000 per request.** The `/events/ingest` endpoint enforces a hard maximum of 1,000 events per request. Batches larger than that are rejected, so split high volumes across multiple calls. For high-volume workloads, buffer events and flush in batches rather than sending one request per event. > [!WARNING] > > **Retry 5xx and 429, never other 4xx.** Retry on server errors (5xx) and rate limits (429) with exponential backoff. Do not retry 400/422 validation errors — the payload is malformed and will fail every time. Fix it and re-send. Queue events that still fail after retries so none are lost. > [!NOTE] > > **Set timestamps intentionally.** Omit `timestamp` for real-time events and it defaults to the current UTC timestamp. Set it explicitly (ISO 8601) for delayed or batched events so usage lands in the correct billing period. Note the accepted window is narrow: events timestamped more than 1 hour in the past or more than 5 minutes in the future are rejected. Historical backfill is not supported — flush buffered events within the hour. > [!WARNING] > > **Send aggregated metadata as numbers, not strings.** Any property referenced by a meter's Over Property (Sum, Max, Last) must be a numeric type — `{ "tokens": 150 }`, not `{ "tokens": "150" }`. String values will not aggregate. ## Usage-Based Billing Analytics Monitor and analyze your usage-based billing data with a comprehensive analytics dashboard. Track customer consumption patterns, meter performance, and billing trends to optimize your pricing strategy and understand usage behaviors. ### Overview Analytics The Overview tab provides a comprehensive view of your usage-based billing performance: #### Activity Metrics Track key usage statistics across different time periods: **Current Month** `metric` Shows usage activity for the current billing period, helping you understand monthly consumption patterns. **All Time** `metric` Displays cumulative usage statistics since you started tracking, providing long-term growth insights. > [!TIP] > > Use the time period selector to compare usage across different months and identify seasonal trends or growth patterns. #### Meter Quantities Chart ![Meter quantities chart showing usage trends over time with purple gradient visualization](https://mintcdn.com/dodopayments/16r81mgDWvSgYER7/images/guides/usage-based-billing/meter-quantities-chart.png?fit=max\&auto=format\&n=16r81mgDWvSgYER7\&q=85\&s=1a8a39547bd0259a53d4591d7928c8ea) The meter quantities chart visualizes usage trends over time with the following features: * **Time-series visualization**: Track usage patterns across days, weeks, or months * **Multiple meter support**: View data from different meters simultaneously * **Trend analysis**: Identify usage spikes, patterns, and growth trajectories > [!NOTE] > > The chart automatically scales based on your usage volume and selected time range, providing clear visibility into both small fluctuations and major usage changes. ### Events Analytics ![Events table showing event names, IDs, and pagination controls for detailed event analysis](https://mintcdn.com/dodopayments/16r81mgDWvSgYER7/images/guides/usage-based-billing/events-table.png?fit=max\&auto=format\&n=16r81mgDWvSgYER7\&q=85\&s=0af7aad1d5e9a379eee18edc40aac157) The Events tab provides granular visibility into individual usage events: #### Event Information Display The events table provides a clear view of individual usage events with the following columns: * **Event Name**: The specific action or trigger that generated the usage event * **Event ID**: A unique identifier for each event instance * **Customer ID**: The customer associated with the event * **Timestamp**: When the event occurred > [!NOTE] > > This view allows you to track and monitor individual usage events across your customer base, providing transparency into billing calculations and usage patterns. ### Customer Analytics The Customers tab provides a detailed table view of customer usage data with the following information: #### Available Data Columns **Customer Email** `string` The email address of the customer for identification. **Subscription ID** `string` A unique identifier for the customer's subscription. **Free Threshold** `number` Number of free units included in the customer's plan before charges apply. **Price Per Unit** `currency` The cost per unit for usage beyond the free threshold. **Last Event** `timestamp` Timestamp of the customer's most recent usage event. **Total Price** `currency` Total amount charged to the customer for usage-based billing. **Consumed Units** `number` Total number of units the customer has consumed. **Chargeable Units** `number` Number of units that exceed the free threshold and are being charged. #### Table Features * **Column Filtering**: Use the "Edit Columns" feature to show or hide specific data columns * **Real-time Updates**: Usage data reflects the most current consumption metrics ## Aggregation Examples Here are practical examples of how different aggregation types work: ### Understanding Aggregation Types Different aggregation types serve different billing scenarios. Choose the right type based on how you want to measure and charge for usage. ### Practical Implementation Examples These examples demonstrate real-world applications of each aggregation type with sample events and expected results: > [accordion] Count Aggregation — API Calls > > Scenario: Track the total number of API requests > > Meter Configuration: > > * Event Name: `api.call` > * Aggregation Type: Count > * Measurement Unit: `calls` > > **Sample Events**: > > ```json theme={null} > { > "events": [ > {"event_id": "call_1", "customer_id": "cus_123", "event_name": "api.call"}, > {"event_id": "call_2", "customer_id": "cus_123", "event_name": "api.call"}, > {"event_id": "call_3", "customer_id": "cus_123", "event_name": "api.call"} > ] > } > ``` > > Result: 3 calls billed to customer > [accordion] Sum Aggregation — Data Transfer > > Scenario: Bill based on total bytes transferred > > Meter Configuration: > > * Event Name: `data.transfer` > * Aggregation Type: Sum > * Over Property: `bytes` > * Measurement Unit: `GB` > > **Sample Events**: > > ```json theme={null} > { > "events": [ > { > "event_id": "transfer_1", > "customer_id": "cus_123", > "event_name": "data.transfer", > "metadata": {"bytes": 1073741824} > }, > { > "event_id": "transfer_2", > "customer_id": "cus_123", > "event_name": "data.transfer", > "metadata": {"bytes": 536870912} > } > ] > } > ``` > > Result: 1.5 GB total transfer billed to customer > [accordion] Max Aggregation — Peak Concurrent Users > > Scenario: Bill based on highest concurrent user count > > Meter Configuration: > > * Event Name: `concurrent.users` > * Aggregation Type: Max > * Over Property: `count` > * Measurement Unit: `users` > > **Sample Events**: > > ```json theme={null} > { > "events": [ > { > "event_id": "peak_1", > "customer_id": "cus_123", > "event_name": "concurrent.users", > "metadata": {"count": 15} > }, > { > "event_id": "peak_2", > "customer_id": "cus_123", > "event_name": "concurrent.users", > "metadata": {"count": 23} > }, > { > "event_id": "peak_3", > "customer_id": "cus_123", > "event_name": "concurrent.users", > "metadata": {"count": 18} > } > ] > } > ``` > > Result: 23 peak concurrent users billed to customer ### Event Filtering Examples > [tab] Filter by API Endpoint > > Only count API calls to specific endpoints: > > Filter Configuration: > > * Property: `endpoint` > * Comparator: `equals` > * Value: `/v1/orders` > > Sample Event: > > ```json theme={null} > { > "event_id": "call_1", > "customer_id": "cus_123", > "event_name": "api.call", > "metadata": { > "endpoint": "/v1/orders", > "method": "POST" > } > } > ``` > > Result: Events matching the filter criteria are counted. Events with different endpoints are ignored. > [tab] Filter by Value Range > > Only count large file uploads: > > Filter Configuration: > > * Property: `file_size` > * Comparator: `greater_than` > * Value: `1048576` (1 MB in bytes) > > Sample Event: > > ```json theme={null} > { > "event_id": "upload_1", > "customer_id": "cus_123", > "event_name": "file.upload", > "metadata": { > "file_size": 5242880, > "file_type": "image" > } > } > ``` > > Result: Files larger than 1 MB are counted. Smaller files are ignored. > [tab] Complex Multi-Condition Filters > > Count premium API calls during business hours: > > Filter Configuration (using AND logic): > > * Property: `plan_type`, Comparator: `equals`, Value: `premium` > * Property: `hour`, Comparator: `greater_than_or_equals`, Value: `9` > * Property: `hour`, Comparator: `less_than`, Value: `17` > > Sample Event: > > ```json theme={null} > { > "event_id": "call_1", > "customer_id": "cus_123", > "event_name": "api.call", > "metadata": { > "plan_type": "premium", > "hour": 14, > "endpoint": "/v1/analytics" > } > } > ``` > > Result: Premium API calls during business hours (9 AM to 5 PM) are counted. ## Troubleshooting Resolve common issues with usage-based billing implementation and ensure accurate tracking and billing. ### Common Issues Most usage-based billing problems fall into these categories: * Event delivery and processing issues * Meter configuration problems * Data type and formatting errors * Customer ID and authentication issues ### Debugging Steps When troubleshooting usage-based billing: 1. Verify event delivery in the Events analytics tab 2. Check that meter configuration matches your event structure 3. Validate customer IDs and API authentication 4. Review filtering conditions and aggregation settings ### Solutions and Fixes > [accordion] Events not showing in meter > > Common causes: > > * Event name doesn't exactly match meter configuration > * Event filtering conditions are excluding your events > * Customer ID doesn't exist in your Dodo Payments account > * Event timestamp is outside the current billing period > > Solutions: > > * Verify event name spelling and case sensitivity > * Review and test your filtering conditions > * Confirm customer ID is valid and active > * Check that event timestamps are recent and properly formatted > [accordion] Aggregation not working as expected > > Common causes: > > * Over Property name doesn't match event metadata keys > * Metadata values are the wrong data type (string vs number) > * Missing required metadata properties > > Solutions: > > * Ensure metadata keys exactly match your Over Property setting > * Convert string numbers to actual numbers in your events > * Include all required properties in every event > [accordion] Filtering not working > > Common causes: > > * Filter property names don't match event metadata > * Wrong comparator for data type (string vs number) > * Case sensitivity in string comparisons > > Solutions: > > * Double-check that property names match exactly > * Use appropriate comparators for your data types > * Consider case sensitivity when filtering strings ## Related API Reference > [card] [Create Meter](/api-reference/meters/create-meter) > > API reference for creating and configuring usage meters for tracking customer consumption. > [card] [Ingest Usage Events](/api-reference/usage-events/ingest-events) > > API reference for sending usage events to your configured meters for billing calculations. # Webhooks Source: https://docs.dodopayments.com/developer-resources/webhooks Receive real-time event notifications from Dodo Payments. Set up endpoints, verify signatures, handle retries, and test webhooks during development. ![Webhook Cover Image](https://mintcdn.com/dodopayments/mOQO5ej_lx0yH9p-/images/cover-images/Webhooks.webp?fit=max\&auto=format\&n=mOQO5ej_lx0yH9p-\&q=85\&s=477435b1004773582aa51236b5cc58e7) Webhooks deliver real-time notifications when events occur in your Dodo Payments account. Use them to automate workflows, update your database, send notifications, and keep your systems in sync. > [!NOTE] > > Dodo Payments webhooks follow the [Standard Webhooks](https://standardwebhooks.com/) specification for signature verification and payload structure. ## Key Features Webhooks provide real-time delivery with built-in security, automatic retries, and event filtering. All official SDKs include signature verification helpers, and the dashboard offers testing, monitoring, and replay tools. ## Getting Started **1. Go to Developer → Webhooks** In the Dodo Payments Dashboard, navigate to **Developer → Webhooks**. **2. Click Add Endpoint** Click **Add endpoint** to create a new webhook receiver. **3. Enter Your Endpoint URL** Provide the HTTPS URL where Dodo Payments will send webhook events, or select an integration connector (Slack, Discord, Zapier, Resend, etc.) to route events to a third-party service without writing code. **4. Select Events** Choose which events to receive. Events are organized by resource (payment, subscription, dispute, etc.). You can select individual events or an entire resource to receive all related events. **5. Save** Click **Create endpoint**. Your webhook signing secret appears on the endpoint's **Overview** tab. > [!WARNING] > > Keep your webhook secret secure. Never expose it in client-side code or version control. To rotate your webhook secret, open the endpoint and click **Rotate secret** next to the secret on the **Overview** tab. The old secret remains valid for 24 hours after rotation. ## Integration Connectors Route webhook events directly to third-party services using integration connectors, eliminating the need to build and maintain custom webhook handlers. ### How Connectors Work A connector transforms Dodo Payments events into the format the destination expects. Which details you provide depends on the destination: | Connector type | What you provide | Destinations | | - | - | - | | **Incoming webhook URL** | A webhook URL you create in the vendor's dashboard. No API key. | [Slack](/integrations/slack), [Discord](/integrations/discord), [Microsoft Teams](/integrations/microsoft-teams), [Zapier](/integrations/zapier), [Windmill](/integrations/windmill) | | **Vendor API** | An API key. The destination URL comes from the connector template. | [Resend](/integrations/resend), [SendGrid](/integrations/sendgrid), [Segment](/integrations/segment), [Customer.io](/integrations/customer-io), [Close CRM](/integrations/close-crm), [Loops](/integrations/loops) | The dashboard shows all connectors available to your business. See [External Integrations](/integrations/introduction) for what each destination can do with the events. ### Setting Up a Connector When creating or editing an endpoint, select a connector and the side sheet shows setup instructions for that destination. Test the transformation before saving to confirm events are converted correctly. > [!TIP] > > Use a connector to reach a supported destination without writing code. If you need custom logic, use a standard endpoint with a [transformation](#transformations) instead. ## Configuring Subscribed Events Configure which events each webhook endpoint receives. **1. Navigate to Webhook Endpoints** Go to **Developer → Webhooks** and click on your endpoint. **2. Open Event Configuration** Click **Edit** to open the endpoint configuration side sheet. **3. Select Events** The event type selector displays all available webhook events organized in a searchable tree, grouped by resource (e.g., `payment`, `subscription`, `dispute`). Check the boxes next to the events you want to receive. You can select individual events, an entire resource, or mix and match. **4. Save Configuration** Click **Save** to apply your changes. > [!WARNING] > > If you deselect all events, your webhook endpoint receives every event type. Select only the events your application needs. ## Event Catalog Go to **Developer → Webhooks** and open the **Event catalog** tab to see every event type Dodo Payments can send. Select an event to view its schema and sample payload. > [card] [Webhook Events Guide](/developer-resources/webhooks/intents/webhook-events-guide) > > Browse events as reference documentation, grouped by resource. ## Webhook Delivery ### Timeouts Webhooks have a **30-second timeout** for both connection and read operations. Process webhooks asynchronously by returning a `200` status code immediately, then handle the event in the background. ### Automatic Retries Failed deliveries are retried with exponential backoff, up to 8 attempts total: | Attempt | Delay | | - | - | | 1 | Immediately | | 2 | 5 seconds | | 3 | 5 minutes | | 4 | 30 minutes | | 5 | 2 hours | | 6 | 5 hours | | 7 | 10 hours | | 8 | 10 hours (final) | Use the dashboard to manually replay failed messages or bulk recover messages from a specific time range. ### Idempotency Each webhook includes a unique `webhook-id` header. Store this ID to detect and skip duplicate events, since retries may deliver the same event multiple times. ```javascript theme={null} // Use a persistent store such as your database in production. An in-memory Set is lost on restart. const processedWebhooks = new Set(); app.post('/webhook', async (req, res) => { const webhookId = req.headers['webhook-id']; if (processedWebhooks.has(webhookId)) { return res.status(200).json({ received: true }); } // processWebhook is your handler. Record the ID only after it succeeds, // so a failed attempt is processed again on retry. await processWebhook(req.body); processedWebhooks.add(webhookId); res.status(200).json({ received: true }); }); ``` > [!WARNING] > > Always implement idempotency checks. Due to retries, you may receive the same event multiple times. ### Event Ordering Events may arrive out of order due to retries or network conditions. Each webhook includes a `timestamp` field; use it to order events if your application requires it. You always receive the latest payload state at delivery time. ## Securing Webhooks Always validate webhook payloads and use HTTPS. ### Verifying Signatures Each webhook includes a `webhook-signature` header: an HMAC SHA256 signature of the payload and timestamp, signed with your secret key. #### SDK Verification (Recommended) All official SDKs include built-in helpers. Set `DODO_PAYMENTS_WEBHOOK_KEY` when initializing the client, then call `unwrap()` to verify and parse the payload. Two methods are available: * `unwrap` — Verifies the signature with your webhook secret key, then parses the payload. * `unsafe_unwrap` — Parses the payload without verifying it. Use it for testing only. The method names follow each language's conventions: `unwrap` / `unsafeUnwrap` in TypeScript, `unwrap` / `unsafe_unwrap` in Python, and `Unwrap` / `UnsafeUnwrap` in Go. > [!TIP] > > Provide your webhook secret via `DODO_PAYMENTS_WEBHOOK_KEY` when initializing the Dodo Payments client. ```typescript TypeScript/Node.js theme={null} import DodoPayments from 'dodopayments'; import express from 'express'; const app = express(); app.use(express.raw({ type: 'application/json' })); const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY, webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, }); app.post('/webhook', async (req, res) => { try { const event = client.webhooks.unwrap(req.body.toString(), { headers: { 'webhook-id': req.headers['webhook-id'] as string, 'webhook-signature': req.headers['webhook-signature'] as string, 'webhook-timestamp': req.headers['webhook-timestamp'] as string, }, }); res.json({ received: true }); } catch (error) { res.status(401).json({ error: 'Invalid signature' }); } }); ``` ```python Python theme={null} from fastapi import FastAPI, Request, HTTPException from dodopayments import DodoPayments import os app = FastAPI() client = DodoPayments( bearer_token=os.getenv("DODO_PAYMENTS_API_KEY"), webhook_key=os.getenv("DODO_PAYMENTS_WEBHOOK_KEY"), ) @app.post("/webhook") async def handle_webhook(request: Request): try: event = client.webhooks.unwrap( await request.body(), headers={ "webhook-id": request.headers.get("webhook-id", ""), "webhook-signature": request.headers.get("webhook-signature", ""), "webhook-timestamp": request.headers.get("webhook-timestamp", ""), }, ) return {"received": True} except Exception: raise HTTPException(status_code=401, detail="Invalid signature") ``` ```go Go theme={null} import ( "io" "net/http" "os" "github.com/dodopayments/dodopayments-go" "github.com/dodopayments/dodopayments-go/option" ) func webhookHandler(w http.ResponseWriter, r *http.Request) { client := dodopayments.NewClient( option.WithBearerToken(os.Getenv("DODO_PAYMENTS_API_KEY")), option.WithWebhookKey(os.Getenv("DODO_PAYMENTS_WEBHOOK_KEY")), ) rawBody, _ := io.ReadAll(r.Body) event, err := client.Webhooks.Unwrap(rawBody, r.Header) if err != nil { http.Error(w, "Invalid signature", http.StatusUnauthorized) return } _ = event // Handle the verified event here. w.WriteHeader(http.StatusOK) } ``` #### Manual Verification (Alternative) If you're not using an SDK, verify the signature yourself: 1. Build the signed content by joining `webhook-id`, `webhook-timestamp`, and the raw request body with periods: `{id}.{timestamp}.{body}`. Use the raw body exactly as received, before any JSON parsing. 2. Take your webhook secret. If it starts with `whsec_`, remove that prefix, then base64-decode the rest to get the signing key. 3. Compute the HMAC-SHA256 of the signed content with the signing key, and base64-encode the result. 4. The `webhook-signature` header holds one or more space-separated signatures, each in the form `v1,`. The request is valid if any `v1` signature matches yours. Compare with a constant-time function. 5. Reject the request if `webhook-timestamp` is too far from the current time, to prevent replay attacks. The Standard Webhooks libraries allow 5 minutes. See the [Standard Webhooks libraries](https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries) for reference implementations. For event payload formats, see the [Webhook Payload](/developer-resources/webhooks/intents/payment). ### Source IP Addresses Signature verification is the supported authentication method. It proves the request was signed with your webhook secret, which a network-level check cannot do. Webhook deliveries come from a pool of IP addresses that changes over time. Do not rely on IP allowlists for authentication. Always verify the `webhook-signature` header instead, as described in [Verifying Signatures](#verifying-signatures). If your firewall requires an allowlist: * **Do not hardcode addresses permanently.** Ranges change over time, and stale rules silently block deliveries. * **Request the current ranges** from [support@dodopayments.com](mailto:support@dodopayments.com) before locking down a firewall. * **Watch for change notices.** When delivery addresses change, we notify affected merchants by email — apply updates before the stated date. * **Keep signature verification enabled** regardless of any network rules you add. > [!TIP] > > On serverless and managed hosting platforms, inbound IP filtering is often unavailable or impractical. Signature verification is the correct control in those environments. > [!NOTE] > > A blocked delivery is treated as a failure and is retried on the schedule described in [Automatic Retries](#automatic-retries). If firewall rules caused deliveries to fail, you can re-send them once the rules are fixed — see [Replaying and Recovering Messages](#replaying-and-recovering-messages). ### Responding to Webhooks Your webhook handler must return a `2xx status code` to acknowledge receipt. Any other response is treated as a failure and the webhook will be retried. ### Best Practices * **Use HTTPS only.** HTTP endpoints are vulnerable to interception. * **Respond immediately.** Return a `200` status code right away, then process the event asynchronously. * **Implement idempotency.** Use the `webhook-id` header to detect and skip duplicate events. * **Secure your secret.** Store `DODO_PAYMENTS_WEBHOOK_KEY` in environment variables or a secrets manager, never in version control. ## Webhook Payload Structure ### Request Format ```http theme={null} POST /your-webhook-url Content-Type: application/json ``` ### Headers **webhook-id** `string` *required* Unique identifier for this webhook event. Use for idempotency checks. **webhook-signature** `string` *required* HMAC SHA256 signature for verifying webhook authenticity. **webhook-timestamp** `string` *required* Unix timestamp (in seconds) when the webhook was sent. ### Request Body **business\_id** `string` *required* Your Dodo Payments business identifier. **type** `string` *required* Event type that triggered this webhook (e.g., `payment.succeeded`, `subscription.active`). **timestamp** `string` *required* ISO 8601 formatted timestamp of when the event occurred. **data** `object` *required* Event-specific payload containing detailed information about the event. **Data object properties** **payload\_type** `string` Type of resource. One of: `Payment`, `Subscription`, `Refund`, `Dispute`, `LicenseKey`, `CreditLedgerEntry`, `CreditBalanceLow`, `AbandonedCheckout`, `DunningAttempt`, `EntitlementGrant`, `Payout`, or `Invoice`. Additional fields vary by event type. See the event-specific documentation for complete schemas. ### Example Payload ```json theme={null} { "business_id": "bus_H4ekzPSlcg", "type": "payment.succeeded", "timestamp": "2024-01-15T10:30:00Z", "data": { "payload_type": "Payment", // ... event-specific fields } } ``` > [card] [Event Types](/developer-resources/webhooks/intents/webhook-events-guide) > > Browse all available webhook event types > [card] [Event Payloads](/developer-resources/webhooks/intents/payment) > > View detailed payload schemas for each event > [card] [Handle Payment Failures](/developer-resources/handle-payment-failures) > > React to `payment.failed` and recover declined payments ## Testing Webhooks ### Send an Example Event Test your webhook integration directly from the dashboard: **1. Navigate to Webhooks** Go to **Developer → Webhooks** and click on your endpoint. **2. Open Testing Tab** Click the **Testing** tab. **3. Send Example** Select an event type and click **Send example**. The sample payload is delivered to your endpoint URL exactly like a real event, signed the same way. **4. Check Your Endpoint** Confirm the event arrived, that your signature verification passed, and that you returned a `2xx` status code. > [!NOTE] > > Failed messages sent from the Testing tab are retried on the normal retry schedule, like any other webhook. ### Implementation Example Complete Express.js implementation with webhook verification and handling: ```typescript Express.js Webhook Handler theme={null} import { Webhook } from "standardwebhooks"; import express from "express"; const app = express(); const webhook = new Webhook(process.env.DODO_PAYMENTS_WEBHOOK_KEY); // Use express.raw() for the webhook route so the exact bytes Dodo Payments // signed are preserved. Parsing with express.json() first and then calling // JSON.stringify(req.body) can alter the payload (e.g. whitespace), which // breaks signature verification. app.post( '/webhook/dodo-payments', express.raw({ type: "application/json" }), async (req, res) => { try { // Extract webhook headers const webhookHeaders = { "webhook-id": req.headers["webhook-id"] as string, "webhook-signature": req.headers["webhook-signature"] as string, "webhook-timestamp": req.headers["webhook-timestamp"] as string, }; // Verify the webhook signature against the raw, unmodified body const payload = req.body.toString("utf8"); await webhook.verify(payload, webhookHeaders); // Parse the payload only after verification succeeds const data = JSON.parse(payload); // Acknowledge receipt immediately res.status(200).json({ received: true }); // Process webhook asynchronously processWebhookAsync(data).catch(console.error); } catch (error) { console.error('Webhook verification failed:', error); res.status(401).json({ error: 'Invalid signature' }); } } ); // Register express.json() for other routes after the webhook route so it // doesn't consume the raw body needed for signature verification above. app.use(express.json()); async function processWebhookAsync(data: any) { // Handle the webhook event based on type switch (data.type) { case 'payment.succeeded': await handlePaymentSucceeded(data); break; case 'subscription.active': await handleSubscriptionActive(data); break; // Add more event handlers... } } ``` ```javascript Testing Webhooks Locally theme={null} const { Webhook } = require("standardwebhooks"); const axios = require("axios"); const crypto = require("crypto"); // Generate test webhook const timestamp = new Date(); const webhookId = crypto.randomUUID(); const payload = { business_id: "bus_H4ekzPSlcg", type: "payment.succeeded", timestamp: timestamp.toISOString(), data: { payload_type: "Payment", payment_id: "pay_test456", total_amount: 2999 } }; // Sign the payload const webhookSecret = process.env.DODO_PAYMENTS_WEBHOOK_KEY; const webhookInstance = new Webhook(webhookSecret); const payloadString = JSON.stringify(payload); const signature = webhookInstance.sign(webhookId, timestamp, payloadString); // Send test webhook. CommonJS scripts don't support top-level await, so use .then(). axios.post('http://localhost:3000/webhook/dodo-payments', payload, { headers: { "webhook-id": webhookId, "webhook-timestamp": Math.floor(timestamp.getTime() / 1000), "webhook-signature": signature, "Content-Type": "application/json" } }).then((response) => { console.log("Test webhook sent successfully:", response.data); }); ``` > [!TIP] > > Test your webhook handler thoroughly using the dashboard testing interface before processing production events. This helps identify and fix issues early. ## Testing Webhooks with the CLI The [Dodo Payments CLI](/developer-resources/sdks/cli) has two commands for testing webhooks during local development. ### Listen for Live Webhooks Locally Forward real webhook events from your test mode account to your local development server: ```bash theme={null} dodo wh listen ``` The CLI opens a WebSocket connection and forwards every webhook event to your local endpoint (e.g., `http://localhost:3000/webhook`), preserving all headers for signature verification testing. > [!NOTE] > > The listener only works with test mode API keys. Run `dodo login` and select Test Mode first. ### Trigger Mock Webhook Events Send mock webhook payloads to any endpoint without creating real transactions: ```bash theme={null} dodo wh trigger ``` This interactive tool lets you pick an event type and sends a realistic mock payload to your endpoint. It loops so you can test multiple events in one session. The trigger command covers the subscription, payment, refund, dispute, license key, payout, credit, abandoned checkout, dunning, and entitlement grant families. It does not send `subscription.past_due` or `subscription.unpaused`. See [Supported Webhook Events](/developer-resources/sdks/cli#supported-webhook-events) for the exact list. > [!WARNING] > > Mock webhook payloads from `dodo wh trigger` are not signed. Use the unverified parse method (`unsafeUnwrap` in TypeScript, `unsafe_unwrap` in Python, `UnsafeUnwrap` in Go) in your webhook handler during testing only. > [card] [CLI Webhook Testing Docs](/developer-resources/sdks/cli#webhooks) > > See the full CLI webhook testing documentation ## Advanced Settings The **Advanced** tab provides additional configuration options for fine-tuning your webhook endpoint behavior. ### Rate Limiting (Throttling) Control the rate at which webhook events are delivered to your endpoint. By default, webhooks have no rate limit applied and events are delivered as soon as they occur. **1. Open Advanced Tab** From your endpoint details page, click the **Advanced** tab. **2. Configure Rate Limit** Expand the **Endpoint throttling** section. **3. Set Your Limit** Enter the maximum number of messages per second, then click **Save**. Deliveries beyond this rate are queued rather than dropped. ### Custom Headers Add custom HTTP headers to all webhook requests sent to your endpoint. Useful for authentication, routing, or adding metadata. **1. Add Headers** In the **Custom headers** section, enter a header name and value. **2. Add Multiple Headers** Click **Add header** for each additional header, then click **Save**. ### Transformations Transformations allow you to modify a webhook's payload and optionally redirect it to a different URL. Use transformations to: * Modify the payload structure before processing * Route webhooks to different endpoints based on content * Add or remove fields from the payload * Transform data formats **1. Enable Transformations** In the **Transformation** section, turn on **Enable transformation**. **2. Configure Transformation** Write your transformation rules in JavaScript in the code editor, then click **Save**. The code must return the webhook object from `handler()`. **3. Test Transformation** Use the transformation test interface to verify your transformation works correctly before going live. > [!WARNING] > > Transformations can impact webhook delivery performance. Test thoroughly and keep transformation logic simple and efficient. ## Monitoring Webhook Logs The **Logs** tab provides visibility into your webhook delivery status. **1. Navigate to Logs Tab** Go to **Developer → Webhooks** and open the **Logs** tab. **2. Browse Delivery History** View a table of all webhook delivery attempts with columns for Event type, Message ID, Event ID, Sent at, Attempted at, Response code, and Duration. **3. Search and Filter** Use the search bar to find specific messages by ID or event type. Filter by status (Succeeded, Failed, Pending, etc.) to focus on the events you need to investigate. **4. View Message Details** Click on any message to open the message detail page, which shows: * The complete webhook payload * Every delivery attempt with response code and duration * Timestamp of each attempt * Any error messages from your endpoint Each attempt carries a **Replay** action to re-drive that one message without leaving the page. ## Activity Monitoring Go to **Developer → Webhooks** and open the **Activity** tab to see delivery performance across your endpoints. **Delivery activity** plots attempts over time, bucketed as **Attempts per 5 minutes**, **Attempts per hour**, or **Attempts per day** depending on the window. Each bar is split by outcome, and hovering a segment shows the status, the number of attempts, and its share of the total. On an endpoint, **Delivery stats (last 24h)** on the **Overview** tab summarizes the same information for the past day. > [!TIP] > > The **Error rate (24h)** column on the **Endpoints** tab shows which endpoints need attention at a glance. ## Replaying and Recovering Messages How you re-drive a message depends on how many you need: * **One message** — open it from the **Logs** tab and use the **Replay** action on the attempt. * **A range of messages** — open the endpoint, since the bulk modes act on a single endpoint at a time. ### Replaying in Bulk Open the endpoint from **Developer → Webhooks**. Three modes are available, each acting on that endpoint alone: | Mode | What it does | What you set | | - | - | - | | **Recover failed messages** | Replays every message to this endpoint that failed. | A starting point: **8 hours ago**, **Yesterday**, **3 days ago**, **Last week**, or **2 weeks ago** | | **Replay missing messages** | Replays messages that were never dispatched to this endpoint, for example after you subscribe it to a new event type. | The same starting points | | **Bulk replay messages** | Replays messages matching the filters you choose, including ones that already delivered successfully. | **Since** and **Until** bounds, defaulting to the last two weeks, plus optional event types, channel, or tag | **1. Open More Actions** On the endpoint, open **More actions** and pick one of the three modes above. **2. Set the Range** Fill in the range that mode asks for, as listed in the table. **3. Start the Run** Click **Recover** or **Replay**, depending on the mode you picked. Every run appears under **Replay history** on the endpoint's **Overview** tab, with its mode, time range, status, and the number of messages resent. ## Email Alerts The webhooks dashboard doesn't offer email alerts for failing deliveries. To monitor deliveries, go to **Developer → Webhooks** and check the **Logs** and **Activity** tabs. ## Deploy to Cloud Platforms Platform-specific guides for deploying webhook handlers to popular cloud providers: > [card] [Vercel](/developer-resources/webhooks/examples/vercel-example) > > Deploy webhooks to Vercel with serverless functions > [card] [Cloudflare Workers](/developer-resources/webhooks/examples/cloudflare-example) > > Run webhooks on Cloudflare's edge network > [card] [Supabase Edge Functions](/developer-resources/webhooks/examples/supabase-example) > > Integrate webhooks with Supabase > [card] [Netlify Functions](/developer-resources/webhooks/examples/netlify-example) > > Deploy webhooks as Netlify serverless functions ## Related API Reference > [card] [Create Webhook](/api-reference/webhooks/create-webhook) > > Create and configure webhook endpoints programmatically > [card] [List Webhooks](/api-reference/webhooks/list-webhooks) > > Retrieve and manage your webhook endpoints # Cloudflare Workers Source: https://docs.dodopayments.com/developer-resources/webhooks/examples/cloudflare-example Deploy Dodo Payments webhooks to Cloudflare Workers with signature verification and PostgreSQL storage. > [card] [GitHub Repository](https://github.com/dodopayments/cloud-functions/tree/main/cloudflare) > > Complete source code and setup guide ## Quick Setup ### 1. Prerequisites You need: * A [Cloudflare account](https://dash.cloudflare.com/sign-up) * A [Neon database](https://neon.com) account * A Dodo Payments API key from **Developer → API Keys** in the dashboard ### 2. Install Dependencies ```bash theme={null} npm install -g wrangler wrangler login git clone https://github.com/dodopayments/cloud-functions.git cd cloud-functions/cloudflare npm install ``` ### 3. Database Setup 1. Sign up for [Neon](https://neon.com) and create a project. 2. Open the SQL Editor. 3. Copy the entire contents of [`schema.sql`](#database-schema) and run it. 4. Copy your connection string from **Connection Details**. ### 4. Configure Initial Secrets ```bash theme={null} # Set your Neon database URL wrangler secret put DATABASE_URL # Set your API key wrangler secret put DODO_PAYMENTS_API_KEY ``` > [!NOTE] > > You'll set `DODO_PAYMENTS_WEBHOOK_KEY` after deployment, once you have your webhook URL. ### 5. Update wrangler.toml Edit `wrangler.toml` and set your worker name: ```toml theme={null} name = "my-dodo-webhook" ``` ### 6. Deploy ```bash theme={null} npm run deploy ``` ### 7. Get Your Webhook URL Your webhook URL is: ``` https://[worker-name].[your-subdomain].workers.dev ``` ### 8. Register Webhook in DodoPayments Dashboard 1. Go to **Developer → Webhooks** in the Dodo Payments dashboard. 2. Click **Add endpoint**. 3. Enter your webhook URL. 4. Select these events: `subscription.active`, `subscription.cancelled`, `subscription.renewed`. 5. Click **Create endpoint** and copy the signing secret. ### 9. Set Webhook Key & Redeploy ```bash theme={null} wrangler secret put DODO_PAYMENTS_WEBHOOK_KEY npm run deploy ``` ## What It Does The webhook handler processes subscription events and stores them in PostgreSQL: * `subscription.active` — Creates or updates customer and subscription records * `subscription.cancelled` — Marks the subscription as cancelled * `subscription.renewed` — Updates the next billing date ## Key Features * **Signature verification** — Uses the Dodo Payments SDK to verify webhook authenticity * **Idempotency** — Uses the `webhook-id` header to prevent duplicate processing * **Event logging** — Stores all events in the `webhook_events` table for audit trails * **Error handling** — Logs failures and marks events for retry > [!NOTE] > > This example handles three core subscription events with minimal fields. You can extend it to support additional event types and fields based on your needs. ## Configuration Files ```json package.json theme={null} { "name": "dodo-webhook-cloudflare", "version": "1.0.0", "type": "module", "description": "DodoPayments Webhook Handler for Cloudflare Workers", "main": "worker.ts", "scripts": { "dev": "wrangler dev", "deploy": "wrangler deploy", "tail": "wrangler tail" }, "dependencies": { "@neondatabase/serverless": "^1.0.2", "dodopayments": "^2.4.1" }, "devDependencies": { "@cloudflare/workers-types": "^4.0.0", "typescript": "^5.9.3", "wrangler": "^4.43.0" } } ``` ```toml wrangler.toml expandable theme={null} # Cloudflare Workers Configuration name = "dodo-webhook" main = "worker.ts" compatibility_date = "2025-10-20" [observability] [observability.logs] enabled = true head_sampling_rate = 1 invocation_logs = true persist = true ``` ```json tsconfig.json theme={null} { "compilerOptions": { "target": "ES2022", "module": "ES2022", "lib": ["ES2022"], "moduleResolution": "bundler", "types": ["@cloudflare/workers-types"], "esModuleInterop": true, "strict": true, "skipLibCheck": true, "resolveJsonModule": true, "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true }, "include": ["*.ts"], "exclude": ["node_modules"] } ``` ## Database Schema ```sql schema.sql expandable theme={null} -- DodoPayments Webhook Database Schema -- Compatible with PostgreSQL (Supabase, Neon, etc.) -- Enable UUID extension (if not already enabled) CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- Customers table CREATE TABLE IF NOT EXISTS customers ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), email TEXT NOT NULL, name TEXT NOT NULL, dodo_customer_id TEXT UNIQUE NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Subscriptions table CREATE TABLE IF NOT EXISTS subscriptions ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE CASCADE, dodo_subscription_id TEXT UNIQUE NOT NULL, product_id TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('pending', 'active', 'on_hold', 'past_due', 'paused', 'cancelled', 'failed', 'expired')), billing_interval TEXT NOT NULL CHECK (billing_interval IN ('day', 'week', 'month', 'year')), amount INTEGER NOT NULL, currency TEXT NOT NULL, next_billing_date TIMESTAMP WITH TIME ZONE NOT NULL, cancelled_at TIMESTAMP WITH TIME ZONE, created_at TIMESTAMP WITH TIME ZONE NOT NULL, updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Webhook events log CREATE TABLE IF NOT EXISTS webhook_events ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), webhook_id TEXT UNIQUE, event_type TEXT NOT NULL, data JSONB NOT NULL, processed BOOLEAN DEFAULT FALSE, error_message TEXT, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), processed_at TIMESTAMP WITH TIME ZONE, attempts INTEGER DEFAULT 0 ); -- Indexes for better query performance CREATE INDEX IF NOT EXISTS idx_customers_email ON customers(email); CREATE INDEX IF NOT EXISTS idx_customers_dodo_id ON customers(dodo_customer_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_dodo_id ON subscriptions(dodo_subscription_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_customer_id ON subscriptions(customer_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_status ON subscriptions(status); CREATE INDEX IF NOT EXISTS idx_webhook_events_processed ON webhook_events(processed, created_at); CREATE INDEX IF NOT EXISTS idx_webhook_events_type ON webhook_events(event_type); CREATE INDEX IF NOT EXISTS idx_webhook_events_created_at ON webhook_events(created_at DESC); CREATE INDEX IF NOT EXISTS idx_webhook_events_webhook_id ON webhook_events(webhook_id); -- Function to automatically update updated_at timestamp CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql; -- Triggers to automatically update updated_at CREATE TRIGGER update_customers_updated_at BEFORE UPDATE ON customers FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); CREATE TRIGGER update_subscriptions_updated_at BEFORE UPDATE ON subscriptions FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); -- Comments for documentation COMMENT ON TABLE customers IS 'Stores customer information from DodoPayments'; COMMENT ON TABLE subscriptions IS 'Stores subscription data from DodoPayments'; COMMENT ON TABLE webhook_events IS 'Logs all incoming webhook events for audit and retry purposes'; COMMENT ON COLUMN customers.dodo_customer_id IS 'Unique customer ID from DodoPayments'; COMMENT ON COLUMN subscriptions.dodo_subscription_id IS 'Unique subscription ID from DodoPayments'; COMMENT ON COLUMN subscriptions.amount IS 'Amount in smallest currency unit (e.g., cents)'; COMMENT ON COLUMN subscriptions.currency IS 'Currency used for the subscription payments (e.g., USD, EUR, INR)'; COMMENT ON COLUMN webhook_events.attempts IS 'Number of processing attempts for failed webhooks'; COMMENT ON COLUMN webhook_events.data IS 'Full webhook payload as JSON'; ``` **Tables created:** * `customers` — Email, name, and Dodo Payments customer ID * `subscriptions` — Status, amount, next billing date, linked to customers * `webhook_events` — Event log with webhook ID for idempotency ## Implementation Code ```typescript worker.ts expandable theme={null} import { DodoPayments } from 'dodopayments'; import { neon, NeonQueryFunction } from '@neondatabase/serverless'; interface Env { DATABASE_URL: string; DODO_PAYMENTS_API_KEY: string; DODO_PAYMENTS_WEBHOOK_KEY: string; } interface WebhookPayload { business_id: string; type: string; timestamp: string; data: { payload_type: | "Payment" | "Subscription" | "Refund" | "Dispute" | "LicenseKey" | "CreditLedgerEntry" | "CreditBalanceLow" | "AbandonedCheckout" | "DunningAttempt" | "EntitlementGrant" | "Payout" | "Invoice"; subscription_id: string; customer: { customer_id: string; email: string; name: string; }; product_id: string; status: string; recurring_pre_tax_amount: number; payment_frequency_interval: string; created_at: string; next_billing_date: string; cancelled_at?: string | null; currency: string; }; } const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, webhook-id, webhook-signature, webhook-timestamp', 'Access-Control-Allow-Methods': 'POST, OPTIONS', }; async function handleSubscriptionEvent(sql: NeonQueryFunction, payload: WebhookPayload, status: string) { if (!payload.data.customer.customer_id || !payload.data.subscription_id) { throw new Error('Missing required fields: customer_id or subscription_id'); } console.log('🔄 Processing subscription event:', JSON.stringify(payload, null, 2)); const customer = payload.data.customer; // Upsert customer (create if doesn't exist, otherwise use existing) const customerResult = await sql` INSERT INTO customers (email, name, dodo_customer_id, created_at) VALUES (${customer.email}, ${customer.name}, ${customer.customer_id}, ${new Date().toISOString()}) ON CONFLICT (dodo_customer_id) DO UPDATE SET email = EXCLUDED.email, name = EXCLUDED.name, updated_at = ${new Date().toISOString()} RETURNING id `; const customerId = customerResult[0].id; console.log(`✅ Customer upserted with ID: ${customerId}`); // Upsert subscription await sql` INSERT INTO subscriptions ( customer_id, dodo_subscription_id, product_id, status, billing_interval, amount, currency, created_at, next_billing_date, cancelled_at, updated_at ) VALUES ( ${customerId}, ${payload.data.subscription_id}, ${payload.data.product_id}, ${status}, ${payload.data.payment_frequency_interval.toLowerCase()}, ${payload.data.recurring_pre_tax_amount}, ${payload.data.currency}, ${payload.data.created_at}, ${payload.data.next_billing_date}, ${payload.data.cancelled_at ?? null}, ${new Date().toISOString()} ) ON CONFLICT (dodo_subscription_id) DO UPDATE SET customer_id = EXCLUDED.customer_id, product_id = EXCLUDED.product_id, status = EXCLUDED.status, billing_interval = EXCLUDED.billing_interval, amount = EXCLUDED.amount, currency = EXCLUDED.currency, created_at = EXCLUDED.created_at, next_billing_date = EXCLUDED.next_billing_date, cancelled_at = EXCLUDED.cancelled_at, updated_at = EXCLUDED.updated_at `; console.log(`✅ Subscription upserted with ${status} status`) } export default { async fetch(request: Request, env: Env): Promise { // Handle CORS preflight if (request.method === 'OPTIONS') { return new Response('ok', { headers: corsHeaders }); } if (request.method !== 'POST') { return new Response(JSON.stringify({ error: 'Method not allowed' }), { status: 405, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }); } try { const rawBody = await request.text(); console.log('📨 Webhook received'); // Verify required environment variables if (!env.DODO_PAYMENTS_API_KEY) { console.error('❌ DODO_PAYMENTS_API_KEY is not configured'); return new Response( JSON.stringify({ error: 'API key not configured' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } if (!env.DODO_PAYMENTS_WEBHOOK_KEY) { console.error('❌ DODO_PAYMENTS_WEBHOOK_KEY is not configured'); return new Response( JSON.stringify({ error: 'Webhook verification key not configured' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } if (!env.DATABASE_URL) { console.error('❌ DATABASE_URL is not configured'); return new Response( JSON.stringify({ error: 'Database URL not configured' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } // Verify webhook signature (required for security) const webhookHeaders = { 'webhook-id': request.headers.get('webhook-id') || '', 'webhook-signature': request.headers.get('webhook-signature') || '', 'webhook-timestamp': request.headers.get('webhook-timestamp') || '', }; try { const dodoPaymentsClient = new DodoPayments({ bearerToken: env.DODO_PAYMENTS_API_KEY, webhookKey: env.DODO_PAYMENTS_WEBHOOK_KEY, }); const unwrappedWebhook = dodoPaymentsClient.webhooks.unwrap(rawBody, { headers: webhookHeaders }); console.log('Unwrapped webhook:', unwrappedWebhook); console.log('✅ Webhook signature verified'); } catch (error) { console.error('❌ Webhook verification failed:', error); return new Response( JSON.stringify({ error: 'Webhook verification failed' }), { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } // Initialize Neon client const sql = neon(env.DATABASE_URL); const payload: WebhookPayload = JSON.parse(rawBody); const eventType = payload.type; const eventData = payload.data; const webhookId = request.headers.get('webhook-id') || ''; console.log(`📋 Webhook payload:`, JSON.stringify(payload, null, 2)); // Check for duplicate webhook-id (idempotency) if (webhookId) { const existingEvent = await sql` SELECT id FROM webhook_events WHERE webhook_id = ${webhookId} `; if (existingEvent.length > 0) { console.log(`⚠️ Webhook ${webhookId} already processed, skipping (idempotency)`); return new Response( JSON.stringify({ success: true, message: 'Webhook already processed' }), { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } } // Log webhook event with webhook_id for idempotency const logResult = await sql` INSERT INTO webhook_events (webhook_id, event_type, data, processed, created_at) VALUES (${webhookId || null}, ${eventType}, ${JSON.stringify(eventData)}, ${false}, ${new Date().toISOString()}) RETURNING id `; const loggedEventId = logResult[0].id; console.log('📝 Webhook event logged with ID:', loggedEventId); console.log(`🔄 Processing: ${eventType} (${eventData.payload_type || 'unknown payload type'})`); try { switch (eventType) { case 'subscription.active': await handleSubscriptionEvent(sql, payload, 'active'); break; case 'subscription.cancelled': await handleSubscriptionEvent(sql, payload, 'cancelled'); break; case 'subscription.renewed': console.log('🔄 Subscription renewed - keeping active status and updating billing date'); await handleSubscriptionEvent(sql, payload, 'active'); break; default: console.log(`ℹ️ Event ${eventType} logged but not processed (no handler available)`); } await sql` UPDATE webhook_events SET processed = ${true}, processed_at = ${new Date().toISOString()} WHERE id = ${loggedEventId} `; console.log('✅ Webhook marked as processed'); } catch (processingError) { console.error('❌ Error processing webhook event:', processingError); await sql` UPDATE webhook_events SET processed = ${false}, error_message = ${processingError instanceof Error ? processingError.message : 'Unknown error'}, processed_at = ${new Date().toISOString()} WHERE id = ${loggedEventId} `; throw processingError; } console.log('✅ Webhook processed successfully'); return new Response( JSON.stringify({ success: true, event_type: eventType, event_id: loggedEventId }), { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } catch (error) { console.error('❌ Webhook processing failed:', error); return new Response( JSON.stringify({ error: 'Webhook processing failed', details: error instanceof Error ? error.message : 'Unknown error' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } } }; ``` ## How It Works The webhook handler: 1. **Verifies the signature** — Uses the Dodo Payments SDK to verify the request with HMAC-SHA256 2. **Checks for duplicates** — Uses the `webhook-id` header to prevent processing the same event twice 3. **Logs the event** — Stores the raw webhook in the `webhook_events` table for audit trails 4. **Processes the event** — Creates or updates customers and subscriptions in the database 5. **Handles errors** — Logs failures and marks events as unprocessed for retry ## Testing **Local development:** ```bash theme={null} npm run dev # Available at http://localhost:8787 ``` **Configure in the Dodo Payments dashboard:** 1. Go to **Developer → Webhooks**. 2. Add an endpoint with your Worker URL. 3. Select `subscription.active`, `subscription.cancelled`, and `subscription.renewed`. ## Common Issues | Issue | Solution | | - | - | | Verification failed | Verify the webhook key is correct from the dashboard | | Database connection error | Check your Neon connection string | | Worker not deploying | Run `npm install` and verify `wrangler.toml` syntax | ## Resources * [Cloudflare Workers documentation](https://developers.cloudflare.com/workers/) * [Neon documentation](https://neon.com/docs/) * [Webhook Events Guide](/developer-resources/webhooks/intents/webhook-events-guide) * [GitHub repository](https://github.com/dodopayments/cloud-functions/tree/main/cloudflare) # Netlify Functions Source: https://docs.dodopayments.com/developer-resources/webhooks/examples/netlify-example Deploy Dodo Payments webhooks to Netlify Functions with signature verification and PostgreSQL storage. > [card] [GitHub Repository](https://github.com/dodopayments/cloud-functions/tree/main/netlify) > > Complete source code and setup guide ## Quick Setup ### 1. Prerequisites You need: * A [Netlify account](https://app.netlify.com/signup) * A [Neon database](https://neon.com) account * A Dodo Payments API key from **Developer → API Keys** in the dashboard ### 2. Install Dependencies ```bash theme={null} npm install -g netlify-cli netlify login git clone https://github.com/dodopayments/cloud-functions.git cd cloud-functions/netlify npm install ``` ### 3. Database Setup 1. Sign up for [Neon](https://neon.com) and create a project. 2. Open the SQL Editor. 3. Copy the entire contents of [`schema.sql`](#database-schema) and run it. 4. Copy your connection string from **Connection Details**. ### 4. Set Initial Environment Variables ```bash theme={null} netlify env:set DATABASE_URL "your-neon-connection-string" netlify env:set DODO_PAYMENTS_API_KEY "dodo_test_..." ``` > [!NOTE] > > You'll set `DODO_PAYMENTS_WEBHOOK_KEY` after deployment, once you have your webhook URL. ### 5. Initialize & Deploy ```bash theme={null} netlify init # Link to your site (first time only) npm run deploy ``` ### 6. Get Your Webhook URL Your webhook URL is: ``` https://[your-project].netlify.app/.netlify/functions/webhook ``` ### 7. Register Webhook in DodoPayments Dashboard 1. Go to **Developer → Webhooks** in the Dodo Payments dashboard. 2. Click **Add endpoint**. 3. Enter your webhook URL. 4. Select these events: `subscription.active`, `subscription.cancelled`, `subscription.renewed`. 5. Click **Create endpoint** and copy the signing secret. ### 8. Set Webhook Key & Redeploy ```bash theme={null} netlify env:set DODO_PAYMENTS_WEBHOOK_KEY "your-webhook-signing-key" npm run deploy ``` ## What It Does The webhook handler processes subscription events and stores them in PostgreSQL: * `subscription.active` — Creates or updates customer and subscription records * `subscription.cancelled` — Marks the subscription as cancelled * `subscription.renewed` — Updates the next billing date ## Key Features * **Signature verification** — Uses the Dodo Payments SDK to verify webhook authenticity * **Idempotency** — Uses the `webhook-id` header to prevent duplicate processing * **Event logging** — Stores all events in the `webhook_events` table for audit trails * **Error handling** — Logs failures and marks events for retry > [!NOTE] > > This example handles three core subscription events with minimal fields. You can extend it to support additional event types and fields based on your needs. ## Configuration Files ```json package.json theme={null} { "name": "dodo-webhook-netlify", "version": "1.0.0", "type": "module", "description": "DodoPayments Webhook Handler for Netlify", "scripts": { "dev": "netlify dev", "deploy": "netlify deploy --prod" }, "dependencies": { "@neondatabase/serverless": "^1.0.2", "dodopayments": "^2.4.1" }, "devDependencies": { "@netlify/functions": "^5.0.0", "netlify-cli": "^23.9.1", "typescript": "^5.9.3" } } ``` ```json tsconfig.json theme={null} { "compilerOptions": { "target": "ES2022", "module": "ES2022", "lib": ["ES2022"], "moduleResolution": "node", "esModuleInterop": true, "strict": true, "skipLibCheck": true, "resolveJsonModule": true, "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true, "types": ["node"] }, "include": ["functions/*.ts"], "exclude": ["node_modules"] } ``` ```toml netlify.toml theme={null} [build] functions = "functions" [build.environment] NODE_VERSION = "18" [functions] # Functions will be available at /.netlify/functions/[function-name] directory = "functions" ``` ## Database Schema ```sql schema.sql expandable theme={null} -- DodoPayments Webhook Database Schema -- Compatible with PostgreSQL (Supabase, Neon, etc.) -- Enable UUID extension (if not already enabled) CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- Customers table CREATE TABLE IF NOT EXISTS customers ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), email TEXT NOT NULL, name TEXT NOT NULL, dodo_customer_id TEXT UNIQUE NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Subscriptions table CREATE TABLE IF NOT EXISTS subscriptions ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE CASCADE, dodo_subscription_id TEXT UNIQUE NOT NULL, product_id TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('pending', 'active', 'on_hold', 'past_due', 'paused', 'cancelled', 'failed', 'expired')), billing_interval TEXT NOT NULL CHECK (billing_interval IN ('day', 'week', 'month', 'year')), amount INTEGER NOT NULL, currency TEXT NOT NULL, next_billing_date TIMESTAMP WITH TIME ZONE NOT NULL, cancelled_at TIMESTAMP WITH TIME ZONE, created_at TIMESTAMP WITH TIME ZONE NOT NULL, updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Webhook events log CREATE TABLE IF NOT EXISTS webhook_events ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), webhook_id TEXT UNIQUE, event_type TEXT NOT NULL, data JSONB NOT NULL, processed BOOLEAN DEFAULT FALSE, error_message TEXT, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), processed_at TIMESTAMP WITH TIME ZONE, attempts INTEGER DEFAULT 0 ); -- Indexes for better query performance CREATE INDEX IF NOT EXISTS idx_customers_email ON customers(email); CREATE INDEX IF NOT EXISTS idx_customers_dodo_id ON customers(dodo_customer_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_dodo_id ON subscriptions(dodo_subscription_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_customer_id ON subscriptions(customer_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_status ON subscriptions(status); CREATE INDEX IF NOT EXISTS idx_webhook_events_processed ON webhook_events(processed, created_at); CREATE INDEX IF NOT EXISTS idx_webhook_events_type ON webhook_events(event_type); CREATE INDEX IF NOT EXISTS idx_webhook_events_created_at ON webhook_events(created_at DESC); CREATE INDEX IF NOT EXISTS idx_webhook_events_webhook_id ON webhook_events(webhook_id); -- Function to automatically update updated_at timestamp CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql; -- Triggers to automatically update updated_at CREATE TRIGGER update_customers_updated_at BEFORE UPDATE ON customers FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); CREATE TRIGGER update_subscriptions_updated_at BEFORE UPDATE ON subscriptions FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); -- Comments for documentation COMMENT ON TABLE customers IS 'Stores customer information from DodoPayments'; COMMENT ON TABLE subscriptions IS 'Stores subscription data from DodoPayments'; COMMENT ON TABLE webhook_events IS 'Logs all incoming webhook events for audit and retry purposes'; COMMENT ON COLUMN customers.dodo_customer_id IS 'Unique customer ID from DodoPayments'; COMMENT ON COLUMN subscriptions.dodo_subscription_id IS 'Unique subscription ID from DodoPayments'; COMMENT ON COLUMN subscriptions.amount IS 'Amount in smallest currency unit (e.g., cents)'; COMMENT ON COLUMN subscriptions.currency IS 'Currency used for the subscription payments (e.g., USD, EUR, INR)'; COMMENT ON COLUMN webhook_events.attempts IS 'Number of processing attempts for failed webhooks'; COMMENT ON COLUMN webhook_events.data IS 'Full webhook payload as JSON'; ``` **Tables created:** * `customers` — Email, name, and Dodo Payments customer ID * `subscriptions` — Status, amount, next billing date, linked to customers * `webhook_events` — Event log with webhook ID for idempotency ## Implementation Code ```typescript functions/webhook.ts expandable theme={null} import { Handler, HandlerEvent, HandlerContext } from '@netlify/functions'; import { neon, NeonQueryFunction } from '@neondatabase/serverless'; import { DodoPayments } from 'dodopayments'; interface WebhookPayload { business_id: string; type: string; timestamp: string; data: { payload_type: | "Payment" | "Subscription" | "Refund" | "Dispute" | "LicenseKey" | "CreditLedgerEntry" | "CreditBalanceLow" | "AbandonedCheckout" | "DunningAttempt" | "EntitlementGrant" | "Payout" | "Invoice"; subscription_id: string; customer: { customer_id: string; email: string; name: string; }; product_id: string; status: string; recurring_pre_tax_amount: number; payment_frequency_interval: string; created_at: string; next_billing_date: string; cancelled_at?: string | null; currency: string; }; } const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, webhook-id, webhook-signature, webhook-timestamp', 'Access-Control-Allow-Methods': 'POST, OPTIONS', }; async function handleSubscriptionEvent(sql: NeonQueryFunction, payload: WebhookPayload, status: string) { if (!payload.data.customer.customer_id || !payload.data.subscription_id) { throw new Error('Missing required fields: customer_id or subscription_id'); } console.log('🔄 Processing subscription event:', JSON.stringify(payload, null, 2)); const customer = payload.data.customer; // Upsert customer (create if doesn't exist, otherwise use existing) const customerResult = await sql` INSERT INTO customers (email, name, dodo_customer_id, created_at) VALUES (${customer.email}, ${customer.name}, ${customer.customer_id}, ${new Date().toISOString()}) ON CONFLICT (dodo_customer_id) DO UPDATE SET email = EXCLUDED.email, name = EXCLUDED.name, updated_at = ${new Date().toISOString()} RETURNING id `; const customerId = customerResult[0].id; console.log(`✅ Customer upserted with ID: ${customerId}`); // Upsert subscription await sql` INSERT INTO subscriptions ( customer_id, dodo_subscription_id, product_id, status, billing_interval, amount, currency, created_at, next_billing_date, cancelled_at, updated_at ) VALUES ( ${customerId}, ${payload.data.subscription_id}, ${payload.data.product_id}, ${status}, ${payload.data.payment_frequency_interval.toLowerCase()}, ${payload.data.recurring_pre_tax_amount}, ${payload.data.currency}, ${payload.data.created_at}, ${payload.data.next_billing_date}, ${payload.data.cancelled_at ?? null}, ${new Date().toISOString()} ) ON CONFLICT (dodo_subscription_id) DO UPDATE SET customer_id = EXCLUDED.customer_id, product_id = EXCLUDED.product_id, status = EXCLUDED.status, billing_interval = EXCLUDED.billing_interval, amount = EXCLUDED.amount, currency = EXCLUDED.currency, created_at = EXCLUDED.created_at, next_billing_date = EXCLUDED.next_billing_date, cancelled_at = EXCLUDED.cancelled_at, updated_at = EXCLUDED.updated_at `; console.log(`✅ Subscription upserted with ${status} status`) } export const handler: Handler = async (event: HandlerEvent, context: HandlerContext) => { // Handle CORS preflight if (event.httpMethod === 'OPTIONS') { return { statusCode: 200, headers: corsHeaders, body: 'ok' }; } if (event.httpMethod !== 'POST') { return { statusCode: 405, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, body: JSON.stringify({ error: 'Method not allowed' }) }; } try { const rawBody = event.body || ''; console.log('📨 Webhook received'); const DATABASE_URL = process.env.DATABASE_URL; const API_KEY = process.env.DODO_PAYMENTS_API_KEY; const WEBHOOK_KEY = process.env.DODO_PAYMENTS_WEBHOOK_KEY; if (!DATABASE_URL) { console.error('❌ Missing DATABASE_URL environment variable'); return { statusCode: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, body: JSON.stringify({ error: 'Server configuration error' }) }; } // Verify required environment variables if (!API_KEY) { console.error('❌ DODO_PAYMENTS_API_KEY is not configured'); return { statusCode: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, body: JSON.stringify({ error: 'API key not configured' }) }; } if (!WEBHOOK_KEY) { console.error('❌ DODO_PAYMENTS_WEBHOOK_KEY is not configured'); return { statusCode: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, body: JSON.stringify({ error: 'Webhook verification key not configured' }) }; } // Verify webhook signature (required for security) const webhookHeaders = { 'webhook-id': event.headers['webhook-id'] || '', 'webhook-signature': event.headers['webhook-signature'] || '', 'webhook-timestamp': event.headers['webhook-timestamp'] || '', }; try { const dodoPaymentsClient = new DodoPayments({ bearerToken: API_KEY, webhookKey: WEBHOOK_KEY, }); const unwrappedWebhook = dodoPaymentsClient.webhooks.unwrap(rawBody, { headers: webhookHeaders }); console.log('Unwrapped webhook:', unwrappedWebhook); console.log('✅ Webhook signature verified'); } catch (error) { console.error('❌ Webhook verification failed:', error); return { statusCode: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, body: JSON.stringify({ error: 'Webhook verification failed' }) }; } // Initialize Neon client const sql = neon(DATABASE_URL); const payload: WebhookPayload = JSON.parse(rawBody); const eventType = payload.type; const eventData = payload.data; const webhookId = event.headers['webhook-id'] || ''; console.log(`📋 Webhook payload:`, JSON.stringify(payload, null, 2)); // Check for duplicate webhook-id (idempotency) if (webhookId) { const existingEvent = await sql` SELECT id FROM webhook_events WHERE webhook_id = ${webhookId} `; if (existingEvent.length > 0) { console.log(`⚠️ Webhook ${webhookId} already processed, skipping (idempotency)`); return { statusCode: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true, message: 'Webhook already processed' }) }; } } // Log webhook event with webhook_id for idempotency const logResult = await sql` INSERT INTO webhook_events (webhook_id, event_type, data, processed, created_at) VALUES (${webhookId || null}, ${eventType}, ${JSON.stringify(eventData)}, ${false}, ${new Date().toISOString()}) RETURNING id `; const loggedEventId = logResult[0].id; console.log('📝 Webhook event logged with ID:', loggedEventId); console.log(`🔄 Processing: ${eventType} (${eventData.payload_type || 'unknown payload type'})`); try { switch (eventType) { case 'subscription.active': await handleSubscriptionEvent(sql, payload, 'active'); break; case 'subscription.cancelled': await handleSubscriptionEvent(sql, payload, 'cancelled'); break; case 'subscription.renewed': console.log('🔄 Subscription renewed - keeping active status and updating billing date'); await handleSubscriptionEvent(sql, payload, 'active'); break; default: console.log(`ℹ️ Event ${eventType} logged but not processed (no handler available)`); } await sql` UPDATE webhook_events SET processed = ${true}, processed_at = ${new Date().toISOString()} WHERE id = ${loggedEventId} `; console.log('✅ Webhook marked as processed'); } catch (processingError) { console.error('❌ Error processing webhook event:', processingError); await sql` UPDATE webhook_events SET processed = ${false}, error_message = ${processingError instanceof Error ? processingError.message : 'Unknown error'}, processed_at = ${new Date().toISOString()} WHERE id = ${loggedEventId} `; throw processingError; } console.log('✅ Webhook processed successfully'); return { statusCode: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, body: JSON.stringify({ success: true, event_type: eventType, event_id: loggedEventId }) }; } catch (error) { console.error('❌ Webhook processing failed:', error); return { statusCode: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' }, body: JSON.stringify({ error: 'Webhook processing failed', details: error instanceof Error ? error.message : 'Unknown error' }) }; } }; ``` ## How It Works The webhook handler: 1. **Verifies the signature** — Uses the Dodo Payments SDK to verify the request with HMAC-SHA256 2. **Checks for duplicates** — Uses the `webhook-id` header to prevent processing the same event twice 3. **Logs the event** — Stores the raw webhook in the `webhook_events` table for audit trails 4. **Processes the event** — Creates or updates customers and subscriptions in Neon 5. **Handles errors** — Logs failures and marks events as unprocessed for retry ## Testing **Local development:** ```bash theme={null} npm run dev # Available at http://localhost:8888/.netlify/functions/webhook ``` **View logs in the Netlify dashboard:** 1. Select your site and go to **Functions**. 2. Click the `webhook` function. 3. View real-time logs and invocation history. **Configure in the Dodo Payments dashboard:** 1. Go to **Developer → Webhooks**. 2. Add an endpoint with your Netlify Functions URL. 3. Select `subscription.active`, `subscription.cancelled`, and `subscription.renewed`. ## Common Issues | Issue | Solution | | - | - | | Verification failed | Verify the webhook key is correct from the dashboard | | Database connection error | Check your Neon connection string and use a pooled connection | | Function not found (404) | Run `netlify init` and `npm run deploy` again | | Environment variables not available | Set variables in the CLI or dashboard, then redeploy | ## Resources * [Netlify Functions documentation](https://docs.netlify.com/functions/overview/) * [Netlify CLI](https://docs.netlify.com/cli/get-started/) * [Neon documentation](https://neon.com/docs/) * [Webhook Events Guide](/developer-resources/webhooks/intents/webhook-events-guide) * [GitHub repository](https://github.com/dodopayments/cloud-functions/tree/main/netlify) # Supabase Edge Functions Source: https://docs.dodopayments.com/developer-resources/webhooks/examples/supabase-example Deploy Dodo Payments webhooks to Supabase Edge Functions with signature verification and PostgreSQL storage. > [card] [GitHub Repository](https://github.com/dodopayments/cloud-functions/tree/main/supabase) > > Complete source code and setup guide > [!TIP] > > Check out the [Dodo Payments Supabase Subscription Starter](https://github.com/dodopayments/dodo-supabase-subscription-starter) — a complete Next.js, Supabase, and Dodo Payments boilerplate with authentication, payments, and webhooks. ## Quick Setup ### 1. Prerequisites You need: * A [Supabase account](https://supabase.com/dashboard) with a project created * A Dodo Payments API key from **Developer → API Keys** in the dashboard ### 2. Authenticate & Link ```bash theme={null} npx supabase login git clone https://github.com/dodopayments/cloud-functions.git cd cloud-functions/supabase npx supabase link --project-ref your-project-ref ``` Find your project ref in **Project Settings** on the Supabase dashboard. ### 3. Database Setup 1. Go to the [Supabase dashboard](https://supabase.com/dashboard). 2. Open the SQL Editor. 3. Copy the entire contents of [`schema.sql`](#database-schema) and run it. ### 4. Set Initial Secrets Supabase automatically provides `SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` at runtime. ```bash theme={null} npx supabase secrets set DODO_PAYMENTS_API_KEY=dodo_test_... ``` > [!NOTE] > > You'll set `DODO_PAYMENTS_WEBHOOK_KEY` after deployment, once you have your webhook URL. ### 5. Deploy The function is already set up in `functions/webhook/index.ts`. ```bash theme={null} npm run deploy ``` ### 6. Get Your Webhook URL Your webhook URL is: ``` https://[project-ref].supabase.co/functions/v1/webhook ``` ### 7. Register Webhook in DodoPayments Dashboard 1. Go to **Developer → Webhooks** in the Dodo Payments dashboard. 2. Click **Add endpoint**. 3. Enter your webhook URL. 4. Select these events: `subscription.active`, `subscription.cancelled`, `subscription.renewed`. 5. Click **Create endpoint** and copy the signing secret. ### 8. Set Webhook Key & Redeploy ```bash theme={null} npx supabase secrets set DODO_PAYMENTS_WEBHOOK_KEY=your-webhook-signing-key npm run deploy ``` ## What It Does The webhook handler processes subscription events and stores them in Supabase PostgreSQL: * `subscription.active` — Creates or updates customer and subscription records * `subscription.cancelled` — Marks the subscription as cancelled * `subscription.renewed` — Updates the next billing date ## Key Features * **Signature verification** — Uses the Dodo Payments SDK to verify webhook authenticity * **Idempotency** — Uses the `webhook-id` header to prevent duplicate processing * **Event logging** — Stores all events in the `webhook_events` table for audit trails * **Error handling** — Logs failures and marks events for retry > [!NOTE] > > This example handles three core subscription events with minimal fields. You can extend it to support additional event types and fields based on your needs. ## Configuration Files ```json package.json theme={null} { "name": "dodo-webhook-supabase", "version": "1.0.0", "type": "module", "description": "DodoPayments Webhook Handler for Supabase Edge Functions", "scripts": { "dev": "npx supabase functions serve webhook --no-verify-jwt --workdir ..", "deploy": "npx supabase functions deploy webhook --no-verify-jwt --workdir .." } } ``` ```json tsconfig.json theme={null} { "compilerOptions": { "target": "ES2022", "module": "ES2022", "lib": ["ES2022", "DOM"], "moduleResolution": "bundler", "esModuleInterop": true, "strict": true, "skipLibCheck": true, "resolveJsonModule": true, "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true }, "include": ["functions/webhook/*.ts"], "exclude": ["node_modules"] } ``` ## Database Schema ```sql schema.sql expandable theme={null} -- DodoPayments Webhook Database Schema -- Compatible with PostgreSQL (Supabase, Neon, etc.) -- Enable UUID extension (if not already enabled) CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- Customers table CREATE TABLE IF NOT EXISTS customers ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), email TEXT NOT NULL, name TEXT NOT NULL, dodo_customer_id TEXT UNIQUE NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Subscriptions table CREATE TABLE IF NOT EXISTS subscriptions ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE CASCADE, dodo_subscription_id TEXT UNIQUE NOT NULL, product_id TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('pending', 'active', 'on_hold', 'past_due', 'paused', 'cancelled', 'failed', 'expired')), billing_interval TEXT NOT NULL CHECK (billing_interval IN ('day', 'week', 'month', 'year')), amount INTEGER NOT NULL, currency TEXT NOT NULL, next_billing_date TIMESTAMP WITH TIME ZONE NOT NULL, cancelled_at TIMESTAMP WITH TIME ZONE, created_at TIMESTAMP WITH TIME ZONE NOT NULL, updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Webhook events log CREATE TABLE IF NOT EXISTS webhook_events ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), webhook_id TEXT UNIQUE, event_type TEXT NOT NULL, data JSONB NOT NULL, processed BOOLEAN DEFAULT FALSE, error_message TEXT, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), processed_at TIMESTAMP WITH TIME ZONE, attempts INTEGER DEFAULT 0 ); -- Indexes for better query performance CREATE INDEX IF NOT EXISTS idx_customers_email ON customers(email); CREATE INDEX IF NOT EXISTS idx_customers_dodo_id ON customers(dodo_customer_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_dodo_id ON subscriptions(dodo_subscription_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_customer_id ON subscriptions(customer_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_status ON subscriptions(status); CREATE INDEX IF NOT EXISTS idx_webhook_events_processed ON webhook_events(processed, created_at); CREATE INDEX IF NOT EXISTS idx_webhook_events_type ON webhook_events(event_type); CREATE INDEX IF NOT EXISTS idx_webhook_events_created_at ON webhook_events(created_at DESC); CREATE INDEX IF NOT EXISTS idx_webhook_events_webhook_id ON webhook_events(webhook_id); -- Function to automatically update updated_at timestamp CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql; -- Triggers to automatically update updated_at CREATE TRIGGER update_customers_updated_at BEFORE UPDATE ON customers FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); CREATE TRIGGER update_subscriptions_updated_at BEFORE UPDATE ON subscriptions FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); -- Comments for documentation COMMENT ON TABLE customers IS 'Stores customer information from DodoPayments'; COMMENT ON TABLE subscriptions IS 'Stores subscription data from DodoPayments'; COMMENT ON TABLE webhook_events IS 'Logs all incoming webhook events for audit and retry purposes'; COMMENT ON COLUMN customers.dodo_customer_id IS 'Unique customer ID from DodoPayments'; COMMENT ON COLUMN subscriptions.dodo_subscription_id IS 'Unique subscription ID from DodoPayments'; COMMENT ON COLUMN subscriptions.amount IS 'Amount in smallest currency unit (e.g., cents)'; COMMENT ON COLUMN subscriptions.currency IS 'Currency used for the subscription payments (e.g., USD, EUR, INR)'; COMMENT ON COLUMN webhook_events.attempts IS 'Number of processing attempts for failed webhooks'; COMMENT ON COLUMN webhook_events.data IS 'Full webhook payload as JSON'; ``` **Tables created:** * `customers` — Email, name, and Dodo Payments customer ID * `subscriptions` — Status, amount, next billing date, linked to customers * `webhook_events` — Event log with webhook ID for idempotency ## Implementation Code ```typescript functions/webhook/index.ts expandable theme={null} import { serve } from 'https://deno.land/std@0.208.0/http/server.ts'; import { createClient, SupabaseClient } from 'https://esm.sh/@supabase/supabase-js@2.38.4'; import { DodoPayments } from 'https://esm.sh/dodopayments@2.4.1'; export const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, webhook-id, webhook-signature, webhook-timestamp', 'Access-Control-Allow-Methods': 'POST, OPTIONS', }; interface WebhookPayload { business_id: string; type: string; timestamp: string; data: { payload_type: | "Payment" | "Subscription" | "Refund" | "Dispute" | "LicenseKey" | "CreditLedgerEntry" | "CreditBalanceLow" | "AbandonedCheckout" | "DunningAttempt" | "EntitlementGrant" | "Payout" | "Invoice"; subscription_id: string; customer: { customer_id: string; email: string; name: string; }; product_id: string; status: string; recurring_pre_tax_amount: number; payment_frequency_interval: string; created_at: string; next_billing_date: string; cancelled_at?: string | null; currency: string; }; } // Handle subscription events async function handleSubscriptionEvent(supabase: SupabaseClient, payload: WebhookPayload, status: string) { if (!payload.data.customer.customer_id || !payload.data.subscription_id) { throw new Error('Missing required fields: customer_id or subscription_id'); } try { console.log('🔄 Processing subscription event:', JSON.stringify(payload, null, 2)); const customer = payload.data.customer; // Upsert customer (create if doesn't exist, otherwise update) const customerResult = await supabase .from('customers') .upsert({ email: customer.email, name: customer.name, dodo_customer_id: customer.customer_id }, { onConflict: 'dodo_customer_id', ignoreDuplicates: false }) .select('id') .single(); if (customerResult.error) { console.error('❌ Failed to upsert customer:', customerResult.error); throw new Error(`Failed to upsert customer: ${customerResult.error.message}`); } const customerId = customerResult.data.id; console.log(`✅ Customer upserted with ID: ${customerId}`); // Upsert subscription const subscriptionResult = await supabase .from('subscriptions') .upsert({ customer_id: customerId, dodo_subscription_id: payload.data.subscription_id, product_id: payload.data.product_id, status, billing_interval: payload.data.payment_frequency_interval.toLowerCase(), amount: payload.data.recurring_pre_tax_amount, currency: payload.data.currency, created_at: payload.data.created_at, next_billing_date: payload.data.next_billing_date, cancelled_at: payload.data.cancelled_at ?? null, updated_at: new Date().toISOString() }, { onConflict: 'dodo_subscription_id', ignoreDuplicates: false }) .select(); if (subscriptionResult.error) { console.error('❌ Failed to upsert subscription:', subscriptionResult.error); throw new Error(`Failed to upsert subscription: ${subscriptionResult.error.message}`); } console.log(`✅ Subscription upserted with ${status} status`); } catch (error) { console.error('❌ Error in handleSubscriptionEvent:', error); console.error('❌ Raw webhook data:', JSON.stringify(payload, null, 2)); throw error; } } serve(async (req: Request) => { if (req.method === 'OPTIONS') { return new Response('ok', { headers: corsHeaders }); } // Validate required environment variables try { const supabaseUrl = Deno.env.get('SUPABASE_URL'); const supabaseServiceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'); if (!supabaseUrl || !supabaseServiceKey) { console.error('❌ Missing required environment variables'); return new Response( JSON.stringify({ error: 'Server configuration error' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } const rawBody = await req.text(); console.log('📨 Webhook received'); const apiKey = Deno.env.get('DODO_PAYMENTS_API_KEY'); const webhookKey = Deno.env.get('DODO_PAYMENTS_WEBHOOK_KEY'); if (!apiKey) { console.error('❌ DODO_PAYMENTS_API_KEY is not configured'); return new Response( JSON.stringify({ error: 'API key not configured' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } if (!webhookKey) { console.error('❌ DODO_PAYMENTS_WEBHOOK_KEY is not configured'); return new Response( JSON.stringify({ error: 'Webhook verification key not configured' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } // Verify webhook signature (required for security) const webhookHeaders = { 'webhook-id': req.headers.get('webhook-id') || '', 'webhook-signature': req.headers.get('webhook-signature') || '', 'webhook-timestamp': req.headers.get('webhook-timestamp') || '', }; try { const dodoPaymentsClient = new DodoPayments({ bearerToken: apiKey, webhookKey: webhookKey, }); const unwrappedWebhook = dodoPaymentsClient.webhooks.unwrap(rawBody, { headers: webhookHeaders }); console.log('Unwrapped webhook:', unwrappedWebhook); console.log('✅ Webhook signature verified'); } catch (error) { console.error('❌ Webhook verification failed:', error); return new Response( JSON.stringify({ error: 'Webhook verification failed', details: error instanceof Error ? error.message : 'Invalid signature' }), { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } // Initialize Supabase client const supabase = createClient(supabaseUrl, supabaseServiceKey); let payload: WebhookPayload; try { payload = JSON.parse(rawBody) as WebhookPayload; } catch (parseError) { console.error('❌ Failed to parse webhook payload:', parseError); return new Response( JSON.stringify({ error: 'Invalid JSON payload' }), { status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } const eventType = payload.type; const eventData = payload.data; const webhookId = req.headers.get('webhook-id') || ''; console.log(`📋 Webhook payload:`, JSON.stringify(payload, null, 2)); // Check for duplicate webhook-id (idempotency) if (webhookId) { const { data: existingEvent } = await supabase .from('webhook_events') .select('id') .eq('webhook_id', webhookId) .single(); if (existingEvent) { console.log(`⚠️ Webhook ${webhookId} already processed, skipping (idempotency)`); return new Response( JSON.stringify({ success: true, message: 'Webhook already processed' }), { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } } // Log webhook event with webhook_id for idempotency const logResult = await supabase.from('webhook_events').insert([{ webhook_id: webhookId || null, event_type: eventType, data: eventData, processed: false, created_at: new Date().toISOString() }]).select('id').single(); if (logResult.error) { console.error('❌ Failed to log webhook event:', logResult.error); return new Response( JSON.stringify({ error: 'Failed to log webhook event' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } const loggedEventId = logResult.data.id; console.log('📝 Webhook event logged with ID:', loggedEventId); console.log(`🔄 Processing: ${eventType} (${eventData.payload_type || 'unknown payload type'})`); try { switch (eventType) { case 'subscription.active': await handleSubscriptionEvent(supabase, payload, 'active'); break; case 'subscription.cancelled': await handleSubscriptionEvent(supabase, payload, 'cancelled'); break; case 'subscription.renewed': console.log('🔄 Subscription renewed - keeping active status and updating billing date'); await handleSubscriptionEvent(supabase, payload, 'active'); break; default: console.log(`ℹ️ Event ${eventType} logged but not processed (no handler available)`); } const updateResult = await supabase .from('webhook_events') .update({ processed: true, processed_at: new Date().toISOString() }) .eq('id', loggedEventId); if (updateResult.error) { console.error('❌ Failed to mark webhook as processed:', updateResult.error); } else { console.log('✅ Webhook marked as processed'); } } catch (processingError) { console.error('❌ Error processing webhook event:', processingError); await supabase .from('webhook_events') .update({ processed: false, error_message: processingError instanceof Error ? processingError.message : 'Unknown error', processed_at: new Date().toISOString() }) .eq('id', loggedEventId); throw processingError; } console.log('✅ Webhook processed successfully'); return new Response( JSON.stringify({ success: true, event_type: eventType, event_id: loggedEventId }), { status: 200, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } catch (error) { console.error('❌ Webhook processing failed:', error); return new Response( JSON.stringify({ error: 'Webhook processing failed', details: error instanceof Error ? error.message : 'Unknown error' }), { status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' } } ); } }); ``` ## How It Works The Deno-based Edge Function: 1. **Verifies the signature** — Uses the Dodo Payments SDK for HMAC-SHA256 verification 2. **Checks for duplicates** — Uses the `webhook-id` header to prevent duplicate processing 3. **Logs the event** — Stores the raw webhook data in the `webhook_events` table 4. **Processes updates** — Creates or updates customers and subscriptions via the Supabase client 5. **Handles errors** — Logs failures and marks events for retry ## Testing **Local development:** ```bash theme={null} cd supabase npm run dev # Available at http://localhost:54321/functions/v1/webhook ``` > [!NOTE] > > The `--no-verify-jwt` flag is required because webhooks don't include JWT tokens. Security is provided by webhook signature verification. **View logs:** ```bash theme={null} npx supabase functions logs webhook ``` Or in the [Supabase dashboard](https://supabase.com/dashboard) under **Edge Functions** → **webhook** → **Logs**. **Configure in the Dodo Payments dashboard:** 1. Go to **Developer → Webhooks**. 2. Add an endpoint with your Supabase URL. 3. Select `subscription.active`, `subscription.cancelled`, and `subscription.renewed`. ## Common Issues | Issue | Solution | | - | - | | Verification failed | Verify the webhook key is correct from the dashboard | | Database permission error | Ensure you're using the Service Role Key | | JWT verification error | Deploy with the `--no-verify-jwt` flag | | Function not found | Verify the project ref is correct and the function is deployed | ## Resources * [Supabase Edge Functions documentation](https://supabase.com/docs/guides/functions) * [Supabase CLI](https://supabase.com/docs/reference/cli) * [Deno runtime](https://deno.land/) * [Webhook Events Guide](/developer-resources/webhooks/intents/webhook-events-guide) * [GitHub repository](https://github.com/dodopayments/cloud-functions/tree/main/supabase) # Vercel Functions Source: https://docs.dodopayments.com/developer-resources/webhooks/examples/vercel-example Deploy Dodo Payments webhooks to Vercel with signature verification and PostgreSQL storage. > [card] [GitHub Repository](https://github.com/dodopayments/cloud-functions/tree/main/vercel) > > Complete source code and setup guide ## Quick Setup ### 1. Prerequisites You need: * A [Vercel account](https://vercel.com/signup) * A [Neon database](https://neon.com) account * A Dodo Payments API key from **Developer → API Keys** in the dashboard ### 2. Install Dependencies ```bash theme={null} npm install -g vercel vercel login git clone https://github.com/dodopayments/cloud-functions.git cd cloud-functions/vercel npm install ``` ### 3. Database Setup 1. Sign up for [Neon](https://neon.com) and create a project. 2. Open the SQL Editor. 3. Copy the entire contents of [`schema.sql`](#database-schema) and run it. 4. Copy your connection string from **Connection Details**. ### 4. Set Initial Environment Variables ```bash theme={null} vercel env add DATABASE_URL vercel env add DODO_PAYMENTS_API_KEY ``` > [!NOTE] > > You'll set `DODO_PAYMENTS_WEBHOOK_KEY` after deployment, once you have your webhook URL. ### 5. Deploy ```bash theme={null} npm run deploy ``` ### 6. Get Your Webhook URL Your webhook URL is: ``` https://[your-project].vercel.app/api/webhook ``` ### 7. Register Webhook in DodoPayments Dashboard 1. Go to **Developer → Webhooks** in the Dodo Payments dashboard. 2. Click **Add endpoint**. 3. Enter your webhook URL. 4. Select these events: `subscription.active`, `subscription.cancelled`, `subscription.renewed`. 5. Click **Create endpoint** and copy the signing secret. ### 8. Set Webhook Key & Redeploy ```bash theme={null} vercel env add DODO_PAYMENTS_WEBHOOK_KEY npm run deploy ``` ## What It Does The webhook handler processes subscription events and stores them in PostgreSQL: * `subscription.active` — Creates or updates customer and subscription records * `subscription.cancelled` — Marks the subscription as cancelled * `subscription.renewed` — Updates the next billing date ## Key Features * **Signature verification** — Uses the Dodo Payments SDK to verify webhook authenticity * **Idempotency** — Uses the `webhook-id` header to prevent duplicate processing * **Event logging** — Stores all events in the `webhook_events` table for audit trails * **Error handling** — Logs failures and marks events for retry > [!NOTE] > > This example handles three core subscription events with minimal fields. You can extend it to support additional event types and fields based on your needs. ## Configuration Files ```json package.json theme={null} { "name": "dodo-webhook-vercel", "version": "1.0.0", "type": "module", "description": "DodoPayments Webhook Handler for Vercel", "scripts": { "start": "vercel dev", "deploy": "vercel --prod" }, "dependencies": { "@neondatabase/serverless": "^1.0.2", "dodopayments": "^2.4.1" }, "devDependencies": { "typescript": "^5.9.3", "vercel": "^48.4.1" } } ``` ```json tsconfig.json theme={null} { "compilerOptions": { "target": "ES2022", "module": "ES2022", "lib": ["ES2022"], "moduleResolution": "node", "esModuleInterop": true, "strict": true, "skipLibCheck": true, "resolveJsonModule": true, "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true, "types": ["node"] }, "include": ["api/**/*.ts"], "exclude": ["node_modules"] } ``` ## Database Schema ```sql schema.sql expandable theme={null} -- DodoPayments Webhook Database Schema -- Compatible with PostgreSQL (Supabase, Neon, etc.) -- Enable UUID extension (if not already enabled) CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- Customers table CREATE TABLE IF NOT EXISTS customers ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), email TEXT NOT NULL, name TEXT NOT NULL, dodo_customer_id TEXT UNIQUE NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Subscriptions table CREATE TABLE IF NOT EXISTS subscriptions ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE CASCADE, dodo_subscription_id TEXT UNIQUE NOT NULL, product_id TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('pending', 'active', 'on_hold', 'past_due', 'paused', 'cancelled', 'failed', 'expired')), billing_interval TEXT NOT NULL CHECK (billing_interval IN ('day', 'week', 'month', 'year')), amount INTEGER NOT NULL, currency TEXT NOT NULL, next_billing_date TIMESTAMP WITH TIME ZONE NOT NULL, cancelled_at TIMESTAMP WITH TIME ZONE, created_at TIMESTAMP WITH TIME ZONE NOT NULL, updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); -- Webhook events log CREATE TABLE IF NOT EXISTS webhook_events ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), webhook_id TEXT UNIQUE, event_type TEXT NOT NULL, data JSONB NOT NULL, processed BOOLEAN DEFAULT FALSE, error_message TEXT, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), processed_at TIMESTAMP WITH TIME ZONE, attempts INTEGER DEFAULT 0 ); -- Indexes for better query performance CREATE INDEX IF NOT EXISTS idx_customers_email ON customers(email); CREATE INDEX IF NOT EXISTS idx_customers_dodo_id ON customers(dodo_customer_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_dodo_id ON subscriptions(dodo_subscription_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_customer_id ON subscriptions(customer_id); CREATE INDEX IF NOT EXISTS idx_subscriptions_status ON subscriptions(status); CREATE INDEX IF NOT EXISTS idx_webhook_events_processed ON webhook_events(processed, created_at); CREATE INDEX IF NOT EXISTS idx_webhook_events_type ON webhook_events(event_type); CREATE INDEX IF NOT EXISTS idx_webhook_events_created_at ON webhook_events(created_at DESC); CREATE INDEX IF NOT EXISTS idx_webhook_events_webhook_id ON webhook_events(webhook_id); -- Function to automatically update updated_at timestamp CREATE OR REPLACE FUNCTION update_updated_at_column() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql; -- Triggers to automatically update updated_at CREATE TRIGGER update_customers_updated_at BEFORE UPDATE ON customers FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); CREATE TRIGGER update_subscriptions_updated_at BEFORE UPDATE ON subscriptions FOR EACH ROW EXECUTE FUNCTION update_updated_at_column(); -- Comments for documentation COMMENT ON TABLE customers IS 'Stores customer information from DodoPayments'; COMMENT ON TABLE subscriptions IS 'Stores subscription data from DodoPayments'; COMMENT ON TABLE webhook_events IS 'Logs all incoming webhook events for audit and retry purposes'; COMMENT ON COLUMN customers.dodo_customer_id IS 'Unique customer ID from DodoPayments'; COMMENT ON COLUMN subscriptions.dodo_subscription_id IS 'Unique subscription ID from DodoPayments'; COMMENT ON COLUMN subscriptions.amount IS 'Amount in smallest currency unit (e.g., cents)'; COMMENT ON COLUMN subscriptions.currency IS 'Currency used for the subscription payments (e.g., USD, EUR, INR)'; COMMENT ON COLUMN webhook_events.attempts IS 'Number of processing attempts for failed webhooks'; COMMENT ON COLUMN webhook_events.data IS 'Full webhook payload as JSON'; ``` **Tables created:** * `customers` — Email, name, and Dodo Payments customer ID * `subscriptions` — Status, amount, next billing date, linked to customers * `webhook_events` — Event log with webhook ID for idempotency ## Implementation Code ```typescript api/webhook/index.ts expandable theme={null} import { neon, NeonQueryFunction } from '@neondatabase/serverless'; import { DodoPayments } from 'dodopayments'; interface WebhookPayload { business_id: string; type: string; timestamp: string; data: { payload_type: | "Payment" | "Subscription" | "Refund" | "Dispute" | "LicenseKey" | "CreditLedgerEntry" | "CreditBalanceLow" | "AbandonedCheckout" | "DunningAttempt" | "EntitlementGrant" | "Payout" | "Invoice"; subscription_id: string; customer: { customer_id: string; email: string; name: string; }; product_id: string; status: string; recurring_pre_tax_amount: number; payment_frequency_interval: string; created_at: string; next_billing_date: string; cancelled_at?: string | null; currency: string; }; } // Disable body parsing to access raw body for webhook verification export const config = { api: { bodyParser: false, }, }; const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, webhook-id, webhook-signature, webhook-timestamp', 'Access-Control-Allow-Methods': 'POST, OPTIONS', }; // Helper function for JSON responses function jsonResponse(data: unknown, status: number = 200) { return new Response(JSON.stringify(data), { status, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }); } // Handle subscription events async function handleSubscriptionEvent(sql: NeonQueryFunction, payload: WebhookPayload, status: string) { if (!payload.data.customer.customer_id || !payload.data.subscription_id) { throw new Error('Missing required fields: customer_id or subscription_id'); } console.log('🔄 Processing subscription event:', JSON.stringify(payload, null, 2)); const customer = payload.data.customer; // Upsert customer (create if doesn't exist, otherwise use existing) const customerResult = await sql` INSERT INTO customers (email, name, dodo_customer_id, created_at) VALUES (${customer.email}, ${customer.name}, ${customer.customer_id}, ${new Date().toISOString()}) ON CONFLICT (dodo_customer_id) DO UPDATE SET email = EXCLUDED.email, name = EXCLUDED.name, updated_at = ${new Date().toISOString()} RETURNING id `; const customerId = customerResult[0].id; console.log(`✅ Customer upserted with ID: ${customerId}`); // Upsert subscription await sql` INSERT INTO subscriptions ( customer_id, dodo_subscription_id, product_id, status, billing_interval, amount, currency, created_at, next_billing_date, cancelled_at, updated_at ) VALUES ( ${customerId}, ${payload.data.subscription_id}, ${payload.data.product_id}, ${status}, ${payload.data.payment_frequency_interval.toLowerCase()}, ${payload.data.recurring_pre_tax_amount}, ${payload.data.currency}, ${payload.data.created_at}, ${payload.data.next_billing_date}, ${payload.data.cancelled_at ?? null}, ${new Date().toISOString()} ) ON CONFLICT (dodo_subscription_id) DO UPDATE SET customer_id = EXCLUDED.customer_id, product_id = EXCLUDED.product_id, status = EXCLUDED.status, billing_interval = EXCLUDED.billing_interval, amount = EXCLUDED.amount, currency = EXCLUDED.currency, created_at = EXCLUDED.created_at, next_billing_date = EXCLUDED.next_billing_date, cancelled_at = EXCLUDED.cancelled_at, updated_at = EXCLUDED.updated_at `; console.log(`✅ Subscription upserted with ${status} status`) } // Handle CORS preflight export async function OPTIONS() { return new Response('ok', { status: 200, headers: corsHeaders }); } // Handle webhook POST request export async function POST(req: Request) { try { // Get raw body for webhook signature verification const rawBody = await req.text(); console.log('📨 Webhook received'); const DATABASE_URL = process.env.DATABASE_URL; const API_KEY = process.env.DODO_PAYMENTS_API_KEY; const WEBHOOK_KEY = process.env.DODO_PAYMENTS_WEBHOOK_KEY; if (!DATABASE_URL) { console.error('❌ Missing DATABASE_URL environment variable'); return jsonResponse({ error: 'Server configuration error' }, 500); } // Verify required environment variables if (!API_KEY) { console.error('❌ DODO_PAYMENTS_API_KEY is not configured'); return jsonResponse({ error: 'API key not configured' }, 500); } if (!WEBHOOK_KEY) { console.error('❌ DODO_PAYMENTS_WEBHOOK_KEY is not configured'); return jsonResponse({ error: 'Webhook verification key not configured' }, 500); } // Verify webhook signature (required for security) const webhookHeaders = { 'webhook-id': req.headers.get('webhook-id') || '', 'webhook-signature': req.headers.get('webhook-signature') || '', 'webhook-timestamp': req.headers.get('webhook-timestamp') || '', }; try { const dodoPaymentsClient = new DodoPayments({ bearerToken: API_KEY, webhookKey: WEBHOOK_KEY, }); const unwrappedWebhook = dodoPaymentsClient.webhooks.unwrap(rawBody, { headers: webhookHeaders }); console.log('Unwrapped webhook:', unwrappedWebhook); console.log('✅ Webhook signature verified'); } catch (error) { console.error('❌ Webhook verification failed:', error); return jsonResponse({ error: 'Webhook verification failed' }, 401); } // Initialize Neon client const sql = neon(DATABASE_URL); const payload: WebhookPayload = JSON.parse(rawBody); const eventType = payload.type; const eventData = payload.data; const webhookId = req.headers.get('webhook-id') || ''; console.log(`📋 Webhook payload:`, JSON.stringify(payload, null, 2)); // Check for duplicate webhook-id (idempotency) if (webhookId) { const existingEvent = await sql` SELECT id FROM webhook_events WHERE webhook_id = ${webhookId} `; if (existingEvent.length > 0) { console.log(`⚠️ Webhook ${webhookId} already processed, skipping (idempotency)`); return jsonResponse({ success: true, message: 'Webhook already processed' }); } } // Log webhook event with webhook_id for idempotency const logResult = await sql` INSERT INTO webhook_events (webhook_id, event_type, data, processed, created_at) VALUES (${webhookId || null}, ${eventType}, ${JSON.stringify(eventData)}, ${false}, ${new Date().toISOString()}) RETURNING id `; const loggedEventId = logResult[0].id; console.log('📝 Webhook event logged with ID:', loggedEventId); console.log(`🔄 Processing: ${eventType} (${eventData.payload_type || 'unknown payload type'})`); try { switch (eventType) { case 'subscription.active': await handleSubscriptionEvent(sql, payload, 'active'); break; case 'subscription.cancelled': await handleSubscriptionEvent(sql, payload, 'cancelled'); break; case 'subscription.renewed': console.log('🔄 Subscription renewed - keeping active status and updating billing date'); await handleSubscriptionEvent(sql, payload, 'active'); break; default: console.log(`ℹ️ Event ${eventType} logged but not processed (no handler available)`); } await sql` UPDATE webhook_events SET processed = ${true}, processed_at = ${new Date().toISOString()} WHERE id = ${loggedEventId} `; console.log('✅ Webhook marked as processed'); } catch (processingError) { console.error('❌ Error processing webhook event:', processingError); await sql` UPDATE webhook_events SET processed = ${false}, error_message = ${processingError instanceof Error ? processingError.message : 'Unknown error'}, processed_at = ${new Date().toISOString()} WHERE id = ${loggedEventId} `; throw processingError; } console.log('✅ Webhook processed successfully'); return jsonResponse({ success: true, event_type: eventType, event_id: loggedEventId }); } catch (error) { console.error('❌ Webhook processing failed:', error); return jsonResponse({ error: 'Webhook processing failed', details: error instanceof Error ? error.message : 'Unknown error' }, 500); } } ``` ## How It Works The webhook handler: 1. **Disables body parsing** — To access the raw body for signature verification 2. **Verifies the signature** — Uses the Dodo Payments SDK to verify the request with HMAC-SHA256 3. **Checks for duplicates** — Uses the `webhook-id` header to prevent processing the same event twice 4. **Logs the event** — Stores the raw webhook in the `webhook_events` table for audit trails 5. **Processes the event** — Creates or updates customers and subscriptions in Neon 6. **Handles errors** — Logs failures and marks events as unprocessed for retry ## Testing **Local development:** ```bash theme={null} npm start ``` **View logs in the Vercel dashboard:** 1. Select your project. 2. Go to **Deployments** → latest deployment. 3. Click **Functions** → **Logs**. **Configure in the Dodo Payments dashboard:** 1. Go to **Developer → Webhooks**. 2. Add an endpoint with your Vercel Functions URL. 3. Select `subscription.active`, `subscription.cancelled`, and `subscription.renewed`. ## Common Issues | Issue | Solution | | - | - | | Verification failed | Verify the webhook key is correct from the dashboard | | Database connection error | Check your Neon connection string and use a pooled connection | | Function timeout | Optimize queries; the Pro plan has a longer timeout (60 seconds) | | Environment variables not available | Set variables in the dashboard or CLI, ensure all environments are selected, then redeploy | ## Resources * [Vercel Functions documentation](https://vercel.com/docs/functions) * [Vercel CLI](https://vercel.com/docs/cli) * [Neon documentation](https://neon.com/docs/) * [Webhook Events Guide](/developer-resources/webhooks/intents/webhook-events-guide) * [GitHub repository](https://github.com/dodopayments/cloud-functions/tree/main/vercel) # Credit-Based Billing Webhooks Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/credit The payload sent to your webhook endpoint when credit-based billing events occur — virtual credits granted, consumed, expired, rolled over, or balance alerts. ## Credit-Based Billing Webhook Events The following webhook events are available for tracking credit-based billing lifecycle changes. These events apply to virtual credit entitlements (API calls, tokens, compute hours), not to [Customer Wallets](/features/customer-wallet) (monetary balances). | Event | Description | | - | - | | `credit.added` | Credits are granted to a customer (via subscription, one-time purchase, add-on, or API) | | `credit.deducted` | Credits are consumed through usage or manual debit | | `credit.expired` | Unused credits expired after the configured expiry period | | `credit.rolled_over` | Unused credits are carried forward to a new grant at cycle end | | `credit.rollover_forfeited` | Credits forfeited because the max rollover count was reached | | `credit.overage_charged` | Overage charges applied when usage continues beyond zero balance | | `credit.overage_reset` | Accumulated overage charges are reset (for example, at the start of a new billing cycle) | | `credit.manual_adjustment` | Manual credit or debit adjustment made via dashboard or API | | `credit.balance_low` | Credit balance drops below the configured low balance threshold | ### Ledger Events All ledger events (`credit.added` through `credit.manual_adjustment`) share the same `CreditLedgerEntryResponse` payload documented in the schema below. The payload includes a `metadata` field resolved from the credit grant's **source** — the subscription or payment created at checkout. This lets you key wallet credits off your own checkout `metadata` (for example, an `orgId`) rather than the Dodo-issued `customer_id`: subscription-sourced grants surface the subscription's `metadata` and payment-sourced grants surface the payment's `metadata`. The field is empty when the grant has no resolvable source (for example, credits granted directly via the API). ### Balance Low Event (credit.balance\_low) The `credit.balance_low` event uses a different payload (`CreditBalanceLowPayload`) focused on threshold alerting: ```json theme={null} { "business_id": "bus_H4ekzPSlcg", "type": "credit.balance_low", "timestamp": "2025-08-04T06:15:00.000000Z", "data": { "payload_type": "CreditBalanceLow", "brand_id": "brd_123", "customer_id": "cus_8VbC6JDZzPEqfBPUdpj0K", "subscription_id": "sub_7EeHq2ewQuadropD2ra", "credit_entitlement_id": "cde_9xY2bKwQn5MjRpL8d", "credit_entitlement_name": "API Credits", "available_balance": "15", "subscription_credits_amount": "100", "threshold_percent": 20, "threshold_amount": "20" } } ``` **brand\_id** `string` The brand this credit entitlement belongs to. **customer\_id** `string` The customer whose credit balance triggered the alert. **subscription\_id** `string` The subscription associated with this credit entitlement. **credit\_entitlement\_id** `string` The credit entitlement that has a low balance. **credit\_entitlement\_name** `string` Display name of the credit entitlement. **available\_balance** `string` Current credit balance at the time of the alert. **subscription\_credits\_amount** `string` Total credits issued per billing cycle for this subscription. **threshold\_percent** `integer` The configured low balance threshold percentage. **threshold\_amount** `string` The absolute credit amount that the threshold corresponds to. ### Using `credit.balance_low` for Proactive Alerts Use the `credit.balance_low` webhook to notify customers before they run out of credits: ```javascript theme={null} app.post('/webhooks/dodo', async (req, res) => { // Verify the signature first. See /developer-resources/webhooks#verifying-signatures. // With express.raw(), req.body is a Buffer, so parse it after verification. const event = JSON.parse(req.body); if (event.type === 'credit.balance_low') { const data = event.data; // Notify the customer their credits are running low await sendEmail(data.customer_id, { subject: `Your ${data.credit_entitlement_name} balance is running low`, body: `You have ${data.available_balance} credits remaining ` + `(${data.threshold_percent}% threshold reached). ` + `Consider upgrading your plan or purchasing additional credits.` }); console.log(`Low balance alert for customer ${data.customer_id}`); } res.json({ received: true }); }); ``` > [!TIP] > > Subscribe to `credit.balance_low` to proactively alert customers before they exhaust their credits. Combine with `credit.deducted` to track real-time consumption patterns. > [card] [Get Customer Balance](/api-reference/credit-entitlements/get-customer-balance) > > Check a customer's current balance via API. > [card] [Create Ledger Entry](/api-reference/credit-entitlements/create-ledger-entry) > > Manually credit or debit a customer's balance. ## Webhook Payload Schema # Dispute Webhooks Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/dispute The payload sent to your webhook endpoint when a dispute is created or updated. Handle each event to respond to disputes and reconcile your records. > [!NOTE] > > As your [Merchant of Record](/features/mor-introduction), Dodo Payments manages the dispute and chargeback process with the card networks on your behalf. These webhooks keep your systems in sync as a dispute moves through its lifecycle so you can revoke access, gather evidence, and reconcile your records. ## Dispute Webhook Events A dispute emits an event at each stage of its lifecycle: | Event | Fires when | What it usually means | | - | - | - | | `dispute.opened` | A cardholder opens a dispute on a payment | Funds are held; prepare to respond | | `dispute.challenged` | Evidence has been submitted to contest the dispute | The dispute is being reviewed by the network | | `dispute.accepted` | The dispute was accepted (not contested) | The funds are returned to the cardholder | | `dispute.cancelled` | The dispute was withdrawn or cancelled | No further action needed | | `dispute.expired` | The response window passed without resolution | Typically resolves against you | | `dispute.won` | The dispute was resolved in your favor | Funds are retained | | `dispute.lost` | The dispute was resolved in the cardholder's favor | Funds are returned to the cardholder | > [!NOTE] > > Disputes auto-resolved through [Visa Rapid Dispute Resolution (RDR)](/features/transactions/disputes#visa-rapid-dispute-resolution-rdr) appear as `dispute.lost` with `is_resolved_by_rdr: true`. This is expected — the refund was issued automatically to prevent a formal chargeback. > [!NOTE] > > [Ethoca alerts](/features/transactions/disputes#ethoca-alerts) and [deflections](/features/transactions/disputes#deflections) never create a dispute, so they emit no `dispute.*` events. An Ethoca alert refund fires the standard `refund.succeeded` event, and any linked subscription cancellation fires the usual subscription event. A deflection fires no event. ## Handling Dispute Events When `dispute.opened` fires, the disputed amount is held immediately. Use the event to update your records and, if you intend to contest it, gather evidence in the dashboard. ```javascript Handling dispute events expandable theme={null} app.post('/webhooks/dodo', async (req, res) => { // Verify the signature first. See /developer-resources/webhooks#verifying-signatures. // With express.raw(), req.body is a Buffer, so parse it after verification. const event = JSON.parse(req.body); switch (event.type) { case 'dispute.opened': { const dispute = event.data; // Record the dispute and consider revoking access while it is open await recordDispute(dispute.dispute_id, dispute.payment_id, dispute.amount); // Gather and submit evidence from the Dodo Payments dashboard (within 10 days) break; } case 'dispute.won': { // Funds retained — restore normal state in your records await markDisputeResolved(event.data.dispute_id, 'won'); break; } case 'dispute.lost': { // Funds returned to the cardholder — reconcile and keep access revoked await markDisputeResolved(event.data.dispute_id, 'lost'); break; } } res.json({ received: true }); }); ``` > [!TIP] > > Always verify the webhook signature before processing — see the [Webhooks guide](/developer-resources/webhooks) for setup. The handler above omits verification for brevity. > [!WARNING] > > You have **10 days** to respond to a dispute after it is created. See [Dispute Response Best Practices](/features/transactions/disputes#dispute-response-best-practices) for the evidence to gather and how to format it. ## Dispute Status and Stage The dispute object reports its progress through two fields: | Field | Values | | - | - | | `dispute_status` | `dispute_opened`, `dispute_expired`, `dispute_accepted`, `dispute_cancelled`, `dispute_challenged`, `dispute_won`, `dispute_lost` | | `dispute_stage` | `pre_dispute`, `dispute`, `pre_arbitration` | ## Related > [card] [Managing Disputes](/features/transactions/disputes) > > How to respond to disputes, submit evidence, and how RDR protects your dispute rate. > [card] [Handle Payment Failures](/developer-resources/handle-payment-failures) > > Detect and recover failed payments before they become disputes. ## Webhook Payload Schema # Entitlement Grant Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/entitlement-grant The payload sent to your webhook endpoint when an entitlement grant is created, delivered, fails, or is revoked. ## Entitlement Grant Webhook Events These events fire whenever a customer's entitlement grant changes state, for example when a license key is generated, a Discord role is assigned, a download link is provisioned, or access is revoked. Subscribe to these events to keep your application in sync with what each customer can access. | Event | Description | | - | - | | `entitlement_grant.created` | A new grant row was created. Status is `Delivered` immediately for auto-fulfilled license keys and feature flags, and `Pending` for manually-fulfilled license keys and every other integration. | | `entitlement_grant.delivered` | The grant transitions to delivered. The customer now has access to the entitled platform, file, or license key. | | `entitlement_grant.failed` | Delivery failed and is not being retried. Inspect `error_code` and `error_message`. | | `entitlement_grant.revoked` | Access was withdrawn. Inspect `revocation_reason` to understand why. | All four events share the same `EntitlementGrantResponse` payload documented in the schema below. *** ## Event Triggers ### entitlement\_grant.created A grant row was inserted. The grant always has a stable `id` from this point on, even if its status changes. Use this event to record that fulfillment is in progress. For **auto-fulfilled license keys** and **feature flags** the row is inserted directly with `status: "Delivered"` and `delivered_at` populated, so a single `created` event is followed by no further state changes unless the grant is later revoked. For **manually-fulfilled license keys** (entitlements with `fulfillment_mode: manual`) the row arrives with `status: "Pending"` and no `license_key` object — there is no key yet. This event is your signal that a key is awaiting fulfillment; supply it via [`POST /grants/{grant_id}/license-key`](/api-reference/entitlements/fulfill-license-key), which then fires `license_key.created` and `entitlement_grant.delivered`. See [Manual Fulfillment](/features/license-keys#manual-fulfillment). For **every other integration** the row arrives with `status: "Pending"`. A `delivered` or `failed` event follows once delivery completes: * **OAuth-based integrations** (Discord, GitHub, Notion) use an `oauth_url` the customer must visit to complete consent. Dodo Payments tries to create it when the grant is created, so `entitlement_grant.created` may include it; if it is `null`, it is filled in when the customer starts the accept flow from the Customer Portal. The grant stays `Pending` until the customer authorizes. * **Platform-direct integrations** (Telegram, Framer, Digital Files) sit in `Pending` only briefly while the platform call runs, then move to `Delivered`. ### entitlement\_grant.delivered The grant transitioned to `Delivered`, usually from `Pending`. The customer now has the access described by the entitlement. Use this event to unlock dependent features in your own systems, for example to provision a workspace, send a custom welcome email, or mark a "fulfilled" flag. The payload's `delivered_at` field captures when delivery completed. `delivered` fires whenever an existing grant's status changes to `Delivered`: from `Pending`, when a failed OAuth grant later succeeds, or when a revoked grant is restored. A grant that arrives `Delivered` on creation, such as an auto-fulfilled license key, fires `created` only. ### entitlement\_grant.failed Delivery was attempted and failed with a non-retryable error. The `error_code` and `error_message` fields explain the failure. Common causes include a revoked OAuth token, a denied platform permission, or a missing target (e.g., a deleted Discord guild). > [!TIP] > > Treat `entitlement_grant.failed` as actionable. The customer paid but did not get access. Surface failures to your support team or trigger a regrant once the underlying issue is resolved. ### entitlement\_grant.revoked Access was withdrawn at the platform level: Discord role removed, GitHub collaborator removed, license key disabled, file download URLs no longer issued. The `revocation_reason` field records the trigger. | `revocation_reason` | Trigger | | - | - | | `subscription_cancelled` | The customer's subscription was cancelled (`subscription.cancelled` event). | | `subscription_on_hold` | The subscription is on hold due to failed renewal (`subscription.on_hold`). Recoverable: a successful retry produces a re-grant. | | `subscription_paused` | The subscription was paused (`subscription.paused`). Recoverable: resuming produces a re-grant. | | `subscription_expired` | The subscription reached the end of its term (`subscription.expired`). | | `plan_changed` | The plan changed; old grants are revoked before new ones are issued (`subscription.plan_changed`). | | `refund` | A refund was processed for the original one-time payment (`refund.succeeded`). | | `manual` | A merchant revoked the grant via the API or dashboard. Manual revokes are not auto-regranted on subscription renewal. | | `license_key_disabled` | The license key behind a license-key grant was disabled. The grant is re-activated automatically if the key is re-enabled. | | `platform_external` | The platform side of an integration drifted out of sync (for example, a Discord role was removed manually, the GitHub App lost repository access, or a reconciliation pass detected a missing target). The grant is not auto-regranted on subscription renewal until the underlying platform issue is resolved. | *** ## Payload Variants The `data` field is always an `EntitlementGrantResponse` object. The payload carries an `integration_type` field (for example `license_key`, `digital_files`, `discord`) so you can recognize the grant type directly. Three integration types also attach extra nested objects: * **`license_key`** is included when `integration_type` is `license_key` **and a key has been issued**. It contains the generated key, expiry, and activation usage. For a manually-fulfilled grant still in `Pending`, this object is `null` until you fulfill the grant. * **`digital_product_delivery`** is included when `integration_type` is `digital_files`. It contains presigned download URLs, the optional `instructions`, and the optional `external_url`. * **`feature`** is included when `integration_type` is `feature_flag`. It contains the `feature_type` and `feature_id` of the capability conferred by the grant. For all other integration types (Discord, GitHub, Telegram, Figma, Framer, Notion) these nested fields are `null`; the relevant configuration is captured in the entitlement itself, not the grant. *** ## Sample Payloads ### License Key Delivered (`entitlement_grant.delivered`) ```json theme={null} theme={null} { "business_id": "bus_H4ekzPSlcg", "type": "entitlement_grant.delivered", "timestamp": "2026-05-01T10:25:33.000000Z", "data": { "payload_type": "EntitlementGrant", "id": "grant_8VbC6JDZzPEqfBPUdpj0K", "business_id": "bus_H4ekzPSlcg", "brand_id": "brd_123", "entitlement_id": "ent_9xY2bKwQn5MjRpL8d", "customer_id": "cus_abc123", "payment_id": "pay_a1b2c3d4", "subscription_id": null, "status": "Delivered", "integration_type": "license_key", "license_key": { "id": "lic_4hQ2mZ8bR", "key": "PRO-AAAA-BBBB-CCCC-DDDD", "status": "active", "expires_at": "2027-05-01T00:00:00Z", "activations_used": 0, "activations_limit": 5 }, "digital_product_delivery": null, "delivered_at": "2026-05-01T10:25:33Z", "revoked_at": null, "revocation_reason": null, "error_code": null, "error_message": null, "oauth_url": null, "oauth_expires_at": null, "metadata": {}, "created_at": "2026-05-01T10:25:33Z", "updated_at": "2026-05-01T10:25:33Z" } } ``` ### License Key Pending Manual Fulfillment (`entitlement_grant.created`) Fired when a customer buys a product whose License Key entitlement uses `fulfillment_mode: manual`. The grant is `Pending` with no `license_key` object yet — the merchant must supply the key. ```json theme={null} theme={null} { "business_id": "bus_H4ekzPSlcg", "type": "entitlement_grant.created", "timestamp": "2026-05-01T10:24:00.000000Z", "data": { "payload_type": "EntitlementGrant", "id": "grant_8VbC6JDZzPEqfBPUdpj0K", "business_id": "bus_H4ekzPSlcg", "brand_id": "brd_123", "entitlement_id": "ent_9xY2bKwQn5MjRpL8d", "customer_id": "cus_abc123", "payment_id": "pay_a1b2c3d4", "subscription_id": null, "status": "Pending", "integration_type": "license_key", "license_key": null, "digital_product_delivery": null, "delivered_at": null, "revoked_at": null, "revocation_reason": null, "error_code": null, "error_message": null, "oauth_url": null, "oauth_expires_at": null, "metadata": {}, "created_at": "2026-05-01T10:24:00Z", "updated_at": "2026-05-01T10:24:00Z" } } ``` ### Digital Files Delivered (`entitlement_grant.delivered`) ```json theme={null} theme={null} { "business_id": "bus_H4ekzPSlcg", "type": "entitlement_grant.delivered", "timestamp": "2026-05-01T10:30:12.000000Z", "data": { "payload_type": "EntitlementGrant", "id": "grant_2P9rQwYvMxTnKoCb4", "business_id": "bus_H4ekzPSlcg", "brand_id": "brd_123", "entitlement_id": "ent_files_J3kLmN4oP5", "customer_id": "cus_abc123", "payment_id": "pay_a1b2c3d4", "subscription_id": null, "status": "Delivered", "integration_type": "digital_files", "license_key": null, "digital_product_delivery": { "files": [ { "file_id": "df_a4f6c1de", "download_url": "https://files.dodopayments.com/.../pro-bundle.zip?Signature=...", "filename": "pro-bundle.zip", "content_type": "application/zip", "file_size": 18742390, "expires_in": 900 } ], "instructions": "Unzip and run setup.sh from the project root.", "external_url": null }, "delivered_at": "2026-05-01T10:30:12Z", "revoked_at": null, "revocation_reason": null, "error_code": null, "error_message": null, "oauth_url": null, "oauth_expires_at": null, "metadata": {}, "created_at": "2026-05-01T10:30:12Z", "updated_at": "2026-05-01T10:30:12Z" } } ``` ### Discord Role Created and Pending (`entitlement_grant.created`) ```json theme={null} theme={null} { "business_id": "bus_H4ekzPSlcg", "type": "entitlement_grant.created", "timestamp": "2026-05-01T10:31:00.000000Z", "data": { "payload_type": "EntitlementGrant", "id": "grant_DiscordPending5L", "business_id": "bus_H4ekzPSlcg", "brand_id": "brd_123", "entitlement_id": "ent_discord_patrons", "customer_id": "cus_abc123", "payment_id": null, "subscription_id": "sub_pro_monthly_001", "status": "Pending", "integration_type": "discord", "license_key": null, "digital_product_delivery": null, "delivered_at": null, "revoked_at": null, "revocation_reason": null, "error_code": null, "error_message": null, "oauth_url": "https://discord.com/oauth2/authorize?...", "oauth_expires_at": "2026-05-08T10:31:00Z", "metadata": {}, "created_at": "2026-05-01T10:31:00Z", "updated_at": "2026-05-01T10:31:00Z" } } ``` ### Grant Revoked on Subscription Cancellation (`entitlement_grant.revoked`) ```json theme={null} theme={null} { "business_id": "bus_H4ekzPSlcg", "type": "entitlement_grant.revoked", "timestamp": "2026-06-15T08:12:44.000000Z", "data": { "payload_type": "EntitlementGrant", "id": "grant_8VbC6JDZzPEqfBPUdpj0K", "business_id": "bus_H4ekzPSlcg", "brand_id": "brd_123", "entitlement_id": "ent_9xY2bKwQn5MjRpL8d", "customer_id": "cus_abc123", "payment_id": null, "subscription_id": "sub_pro_monthly_001", "status": "Revoked", "integration_type": "license_key", "revocation_reason": "subscription_cancelled", "license_key": { "id": "lic_4hQ2mZ8bR", "key": "PRO-AAAA-BBBB-CCCC-DDDD", "status": "disabled", "expires_at": null, "activations_used": 1, "activations_limit": 5 }, "digital_product_delivery": null, "delivered_at": "2026-05-01T10:25:33Z", "revoked_at": "2026-06-15T08:12:44Z", "error_code": null, "error_message": null, "oauth_url": null, "oauth_expires_at": null, "metadata": {}, "created_at": "2026-05-01T10:25:33Z", "updated_at": "2026-06-15T08:12:44Z" } } ``` ### Delivery Failed (`entitlement_grant.failed`) ```json theme={null} theme={null} { "business_id": "bus_H4ekzPSlcg", "type": "entitlement_grant.failed", "timestamp": "2026-05-01T10:36:21.000000Z", "data": { "payload_type": "EntitlementGrant", "id": "grant_GhFailed7Z", "business_id": "bus_H4ekzPSlcg", "brand_id": "brd_123", "entitlement_id": "ent_github_repo", "customer_id": "cus_abc123", "payment_id": "pay_a1b2c3d4", "subscription_id": null, "status": "Failed", "integration_type": "github", "license_key": null, "digital_product_delivery": null, "delivered_at": null, "revoked_at": null, "revocation_reason": null, "error_code": "github_permission_denied", "error_message": "Repository access could not be granted: the GitHub App installation no longer has permission on this repository.", "oauth_url": null, "oauth_expires_at": null, "metadata": {}, "created_at": "2026-05-01T10:36:00Z", "updated_at": "2026-05-01T10:36:21Z" } } ``` *** ## Integration Tips * **Unlock dependent features when a grant reaches `Delivered`.** A `payment.succeeded` event tells you the money cleared; it does not tell you the customer has the GitHub repo or the Discord role yet. Handle `entitlement_grant.delivered`, and also `entitlement_grant.created` with `status: "Delivered"`, because a grant that is delivered on creation fires no `delivered` event. * **Map `revocation_reason` to retention flows.** A `subscription_on_hold` revoke usually means the customer's card failed and the next renewal will re-grant access. A `manual` or `subscription_cancelled` revoke is intentional. Treat them differently in customer messaging. * **Detect duplicates with the `webhook-id` header, not the grant `id`.** A grant emits `created` once, but `delivered` and `revoked` can each fire more than once, because a revoked grant can be restored and revoked again. `failed` is not always final either: a failed OAuth grant can still be delivered. Re-deliveries from the webhook system can also repeat an event. Skip repeats by `webhook-id`, and key your own grant records on the grant `id`. * **Read `integration_type` to recognize the grant type.** The payload carries `integration_type` directly (for example `license_key`, `digital_files`, `discord`). The `license_key` and `digital_product_delivery` nested objects are populated once their respective grants are delivered; a manually-fulfilled license-key grant stays `Pending` with `integration_type: "license_key"` and a `null` `license_key` until you fulfill it. * **For OAuth-based grants, surface `oauth_url` to the customer.** The `entitlement_grant.created` event for Discord, GitHub, or Notion subscriber flows may include an `oauth_url` and `oauth_expires_at`. If it is `null`, wait for a later event or direct the customer to the Customer Portal. Email the URL to the customer or display it in your app to unblock delivery. # Invoice Webhooks Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/invoice The payload sent to your webhook endpoint when an invoice of invoice-based billing is finalized, sent, paid, past due, voided, or marked uncollectable. > [!NOTE] > > Invoice webhooks apply to [invoice-based billing](/features/invoice-based-billing). Use them to keep the invoice status in your system the same as in Dodo Payments. ## Invoice Webhook Events | Event | Fires when | | - | - | | `invoice.finalized` | An invoice is finalized. | | `invoice.sent` | You send an invoice, Dodo Payments sends a renewal invoice, or the hosted link is first created. | | `invoice.paid` | An invoice is paid, including a \$0 invoice at finalize. | | `invoice.payment_failed` | An automatic charge fails. | | `invoice.past_due` | An invoice becomes past due. | | `invoice.reopened` | A past-due invoice becomes open after a due date change. | | `invoice.voided` | An invoice is voided. | | `invoice.marked_uncollectable` | An invoice is marked uncollectable. | > [!NOTE] > > The payload shows the invoice at the time of delivery, not at the time of the event. Read `status` from the payload, and do not assume it from the event type. ## Handling Invoice Events ```javascript Handling invoice events expandable theme={null} app.post('/webhooks/dodo', async (req, res) => { // Verify the signature first. See /developer-resources/webhooks#verifying-signatures. const event = JSON.parse(req.body); const invoice = event.data; switch (event.type) { case 'invoice.paid': await markInvoicePaid(invoice.invoice_id, invoice.amount_paid); break; case 'invoice.past_due': await notifyAccountManager(invoice.invoice_id, invoice.amount_due); break; case 'invoice.voided': case 'invoice.marked_uncollectable': await closeInvoice(invoice.invoice_id, invoice.status); break; } res.json({ received: true }); }); ``` > [!TIP] > > Refunds and disputes on invoice payments send the [refund](/developer-resources/webhooks/intents/refund) and [dispute](/developer-resources/webhooks/intents/dispute) events. ## Webhook Payload Schema # License Key Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/license-key The payload sent to your webhook endpoint when a license key is created. # Payment Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/payment The payload sent to your webhook endpoint when a payment is created or updated. # Payout Webhooks Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/payout The payload sent to your webhook endpoint when a payout is created or changes status. Use these events to reconcile payouts in your accounting systems. > [!NOTE] > > Payout webhooks tell you when your own funds move from Dodo Payments to your bank account. Use them to reconcile payouts in your accounting systems without polling the [List Payouts](/api-reference/payouts/get-payouts) endpoint. ## Payout Webhook Events A payout emits an event at each stage of its lifecycle. The stages match the [payout statuses](/features/payouts/payout-structure) shown in your dashboard. | Event | Fires when | What it usually means | | - | - | - | | `payout.created` | A payout is created, by the automatic payout cycle or off-cycle | The payout exists but has not started moving yet | | `payout.in_progress` | The payout due date arrives and processing starts | Funds are on their way to your bank account | | `payout.on_hold` | The payout is paused or placed under review | You may need to supply additional information | | `payout.success` | The payout to your bank account settles | Funds should be available in your account | | `payout.failed` | The payout fails | The amount and fees are credited back to your wallet | > [!NOTE] > > `payout.created` was previously emitted as `payout.not_initiated`. If an existing endpoint filters on `payout.not_initiated`, update the filter to `payout.created` so it keeps matching. The `status` field on the payload still reports `not_initiated` at this stage. ## Handling Payout Events Payouts are about your own money rather than a customer's, so these events usually feed bookkeeping and internal alerting rather than customer-facing flows. ```javascript Handling payout events expandable theme={null} app.post('/webhooks/dodo', async (req, res) => { // Verify the signature first. See /developer-resources/webhooks#verifying-signatures. // With express.raw(), req.body is a Buffer, so parse it after verification. const event = JSON.parse(req.body); switch (event.type) { case 'payout.created': { const payout = event.data; // Record the expected payout so finance can reconcile it later await recordPayout(payout.payout_id, payout.amount, payout.currency); break; } case 'payout.success': { // Funds settled — mark the payout as received await markPayoutSettled(event.data.payout_id, event.data.updated_at); break; } case 'payout.failed': { // Funds and fees are credited back to your wallet — alert finance await alertPayoutFailed(event.data.payout_id, event.data.remarks); break; } case 'payout.on_hold': { // Review may be required before the payout can continue await alertPayoutOnHold(event.data.payout_id, event.data.remarks); break; } } res.json({ received: true }); }); ``` > [!TIP] > > Always verify the webhook signature before processing — see the [Webhooks guide](/developer-resources/webhooks) for setup. The handler above omits verification for brevity. > [!WARNING] > > Payout events are neither terminal nor strictly ordered. `payout.failed` can arrive after `payout.success` when a bank returns the transfer, and `payout.success` can arrive after `payout.failed` when a failed payout is later recovered. The payload's `status` always reflects the event type (`payout.created` carries `not_initiated`), even when the event is delivered late, so compare each event's top-level `timestamp` with the last one you processed for that payout rather than assuming the last event you received is final. ## Payout Status The payout object reports its progress through a single field: | Field | Values | | - | - | | `status` | `not_initiated`, `in_progress`, `on_hold`, `success`, `failed` | > [!NOTE] > > `refunds`, `chargebacks`, and `tax` on the payload are deprecated. Use the [payout breakup endpoints](/api-reference/payouts/retrieve-breakup) for a detailed breakdown instead. ## Related > [card] [Payout Structure](/features/payouts/payout-structure) > > How payouts are scheduled and calculated, and what each payout status means. > [card] [Balances & Wallets](/features/account-summary-payout-wallet) > > Track wallet balances and the ledger behind each payout. ## Webhook Payload Schema # Recovery Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/recovery The payloads sent to your webhook endpoint when abandoned cart recovery or subscription dunning events occur. ## Abandoned Cart Recovery Events The following webhook events track the abandoned cart recovery lifecycle: | Event | Description | | - | - | | `abandoned_checkout.detected` | An abandoned checkout has been detected. Sent when a payment is identified as abandoned (failed or incomplete) and the recovery workflow begins. | | `abandoned_checkout.recovered` | The customer completed payment through the recovery link. The `recovered_payment_id` field contains the successful payment ID. | ### Abandoned Checkout Payload Fields **payment\_id** `string` *required* The original payment that was abandoned. Use this to look up product, amount, and currency details. **brand\_id** `string` *required* The brand this abandoned checkout belongs to. **customer\_id** `string` *required* The customer who abandoned the checkout. **abandonment\_reason** `string` *required* Why the checkout was abandoned. One of: * `payment_failed` — Customer attempted payment but it failed * `checkout_incomplete` — Customer visited checkout but never attempted payment **status** `string` *required* Current lifecycle state of this recovery attempt. One of: * `abandoned` — Detected, no emails sent yet * `recovering` — At least one recovery email sent * `recovered` — Customer completed payment * `exhausted` — All emails sent or newer checkout found * `opted_out` — Customer unsubscribed **abandoned\_at** `string` *required* ISO 8601 timestamp of when the checkout was detected as abandoned. **recovered\_payment\_id** `string | null` The payment ID of the successful recovery payment. `null` until the checkout is recovered. ### Example: Handling ACR Webhooks ```javascript theme={null} app.post('/webhooks/dodo', async (req, res) => { // Verify the signature first. See /developer-resources/webhooks#verifying-signatures. // With express.raw(), req.body is a Buffer, so parse it after verification. const event = JSON.parse(req.body); switch (event.type) { case 'abandoned_checkout.detected': console.log(`Checkout abandoned: ${event.data.payment_id}`); console.log(`Reason: ${event.data.abandonment_reason}`); // Track abandonment in your analytics await trackAbandonment(event.data); break; case 'abandoned_checkout.recovered': console.log(`Checkout recovered: ${event.data.payment_id}`); console.log(`Recovery payment: ${event.data.recovered_payment_id}`); // Grant access, update records await handleRecovery(event.data); break; } res.json({ received: true }); }); ``` *** ## Dunning Events The following webhook events track the subscription dunning lifecycle: | Event | Description | | - | - | | `dunning.started` | A dunning attempt has been created for a subscription that entered `past_due` or `on_hold`, or was cancelled by the customer. The `trigger_state` field says which. | | `dunning.recovered` | The customer updated their payment method and the resulting payment succeeded. The `payment_id` field contains the successful payment ID. | ### Dunning Attempt Payload Fields **subscription\_id** `string` *required* The subscription that triggered the dunning attempt. **brand\_id** `string` *required* The brand this dunning attempt belongs to. **customer\_id** `string` *required* The customer who owns the subscription. **trigger\_state** `string` *required* The subscription state that triggered dunning. One of: * `on_hold` — Renewals stopped due to payment failure * `past_due` — A renewal failed while a [grace period](/features/subscription#grace-period) is open * `cancelled` — Customer cancelled from the customer portal **status** `string` *required* Current lifecycle state of this dunning attempt. One of: * `recovering` — Dunning emails are being sent * `recovered` — Customer updated payment method and payment succeeded * `exhausted` — All emails sent or subscription state changed **created\_at** `string` *required* ISO 8601 timestamp of when the dunning attempt was created. **payment\_id** `string | null` The payment ID of the successful recovery payment. `null` while recovering. ### Example: Handling Dunning Webhooks ```javascript theme={null} app.post('/webhooks/dodo', async (req, res) => { // Verify the signature first. See /developer-resources/webhooks#verifying-signatures. // With express.raw(), req.body is a Buffer, so parse it after verification. const event = JSON.parse(req.body); switch (event.type) { case 'dunning.started': console.log(`Dunning started for subscription: ${event.data.subscription_id}`); console.log(`Trigger: ${event.data.trigger_state}`); // Track dunning in your system await trackDunning(event.data); break; case 'dunning.recovered': console.log(`Subscription recovered: ${event.data.subscription_id}`); console.log(`Recovery payment: ${event.data.payment_id}`); // Reactivate access, update records await handleDunningRecovery(event.data); break; } res.json({ received: true }); }); ``` > [!TIP] > > Subscribe to both `dunning.started` and `dunning.recovered` to track the full dunning lifecycle. Use `dunning.started` to pause grace periods or flag at-risk subscriptions in your system. > [card] [Abandoned Cart Recovery](/features/recovery/abandoned-cart-recovery) > > Configure ACR email sequences and discount incentives. > [card] [Subscription Dunning](/features/recovery/subscription-dunning) > > Configure dunning email sequences for lapsed subscriptions. > [card] [Subscription Webhooks](/developer-resources/webhooks/intents/subscription) > > Related subscription lifecycle events like `subscription.on_hold` and `subscription.cancelled`. ## Webhook Payload Schema The schema below is the abandoned checkout payload (`AbandonedCheckoutPayload`). For the dunning payload fields, see [Dunning Attempt Payload Fields](#dunning-attempt-payload-fields). # Refund Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/refund The payload sent to your webhook endpoint when a refund is created or updated. # Subscription Webhooks Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/subscription The payload sent to your webhook endpoint when a subscription is created, updated, or changes state. Handle each event to keep your records in sync. ## Subscription Webhook Events A subscription emits an event at each stage of its lifecycle: | Event | Fires when | | - | - | | `subscription.active` | A subscription is successfully activated and recurring charges are scheduled. | | `subscription.updated` | Any subscription field changes (real-time sync without polling). | | `subscription.past_due` | A renewal fails and the grace period opens; the customer keeps access until the deadline. The payload includes `past_due_ends_at`. | | `subscription.on_hold` | A subscription is put on hold due to failed renewal. | | `subscription.paused` | A subscription is paused. | | `subscription.unpaused` | A paused subscription is resumed. | | `subscription.renewed` | A subscription is renewed for the next billing period. The payload includes `payment_id`, the ID of the renewal payment. | | `subscription.plan_changed` | A subscription is upgraded, downgraded, or modified with different add-ons. | | `subscription.update_payment_method` | A subscription's payment method is updated. | | `subscription.cancelled` | A subscription is cancelled by the merchant or customer. | | `subscription.failed` | Subscription creation fails during mandate creation. | | `subscription.expired` | A subscription reaches the end of its term and expires. | ### Using `subscription.updated` for Real-Time Sync The `subscription.updated` webhook fires whenever any subscription field changes, allowing you to keep your application state in sync without polling: ```javascript theme={null} app.post('/webhooks/dodo', async (req, res) => { // Verify the signature first. See /developer-resources/webhooks#verifying-signatures. // With express.raw(), req.body is a Buffer, so parse it after verification. const event = JSON.parse(req.body); if (event.type === 'subscription.updated') { const subscription = event.data; // Sync subscription changes to your database await syncSubscription(subscription.subscription_id, { status: subscription.status, next_billing_date: subscription.next_billing_date, metadata: subscription.metadata, // ... other fields you want to track }); console.log(`Subscription ${subscription.subscription_id} updated`); } res.json({ received: true }); }); ``` > [!TIP] > > Subscribe to `subscription.updated` to get real-time notifications about any subscription changes, eliminating the need to poll the API for updates. ## Webhook Payload Schema # Webhook Events Guide Source: https://docs.dodopayments.com/developer-resources/webhooks/intents/webhook-events-guide Reference for all webhook events emitted by Dodo Payments, organized by resource. Each event fires at a specific point in a payment, subscription, dispute, or payout lifecycle. Dodo Payments emits webhook events at each stage of a payment, subscription, invoice, dispute, payout, credit, or license key lifecycle. This page lists every event by resource. For detailed payload schemas and handler examples, see the resource-specific pages linked below. ## Payment Events | Event | Fires when | | - | - | | `payment.succeeded` | A payment is successfully processed. | | `payment.failed` | A payment attempt fails due to declined cards, insufficient funds, or other errors. | | `payment.processing` | A payment is being processed. | | `payment.cancelled` | A payment is cancelled before completion. | For the full payload schema, see [Payment Webhooks](/developer-resources/webhooks/intents/payment). ## Refund Events | Event | Fires when | | - | - | | `refund.succeeded` | A refund is successfully processed. | | `refund.failed` | A refund attempt fails due to processing errors or other issues. | For the full payload schema, see [Refund Webhooks](/developer-resources/webhooks/intents/refund). ## Dispute Events | Event | Fires when | | - | - | | `dispute.opened` | A cardholder opens a dispute on a payment. | | `dispute.challenged` | Evidence has been submitted to contest the dispute. | | `dispute.accepted` | The dispute was accepted without being contested. | | `dispute.cancelled` | The dispute was withdrawn or cancelled. | | `dispute.expired` | The response window passed without resolution. | | `dispute.won` | The dispute was resolved in your favor. | | `dispute.lost` | The dispute was resolved in the cardholder's favor. | For detailed payload schemas and handler examples, see [Dispute Webhooks](/developer-resources/webhooks/intents/dispute). ## Subscription Events | Event | Fires when | | - | - | | `subscription.active` | A subscription is successfully activated and recurring charges are scheduled. | | `subscription.updated` | Any subscription field changes (real-time sync without polling). | | `subscription.past_due` | A renewal fails and the grace period opens; the customer keeps access until the deadline. | | `subscription.on_hold` | A subscription is temporarily put on hold due to failed renewal. | | `subscription.paused` | A subscription is paused. | | `subscription.unpaused` | A paused subscription is resumed. | | `subscription.renewed` | A subscription is successfully renewed for the next billing period. | | `subscription.plan_changed` | A subscription is upgraded, downgraded, or modified with different add-ons. | | `subscription.update_payment_method` | A subscription's payment method is updated. | | `subscription.cancelled` | A subscription is cancelled by the merchant or customer. | | `subscription.failed` | Subscription creation fails during mandate creation. | | `subscription.expired` | A subscription reaches the end of its term and expires. | For detailed payload schemas and handler examples, see [Subscription Webhooks](/developer-resources/webhooks/intents/subscription). ## Invoice Events These events apply to [invoice-based billing](/features/invoice-based-billing). The payload is the invoice object. See [Invoice Webhooks](/developer-resources/webhooks/intents/invoice). | Event | Fires when | | - | - | | `invoice.finalized` | An invoice is finalized. | | `invoice.sent` | You send an invoice, Dodo Payments sends a renewal invoice, or the hosted link is first created. | | `invoice.paid` | An invoice is paid, including a \$0 invoice at finalize. | | `invoice.payment_failed` | An automatic charge fails. | | `invoice.past_due` | An invoice becomes past due. | | `invoice.reopened` | A past-due invoice becomes open after a due date change. | | `invoice.voided` | An invoice is voided. | | `invoice.marked_uncollectable` | An invoice is marked uncollectable. | ## License Key Events | Event | Fires when | | - | - | | `license_key.created` | A new license key is created for a product. | For the full payload schema, see [License Key Webhooks](/developer-resources/webhooks/intents/license-key). ## Entitlement Grant Events | Event | Fires when | | - | - | | `entitlement_grant.created` | A new entitlement grant is created for a customer. Auto-fulfilled license-key grants and feature-flag grants arrive with `status: "Delivered"` and fire no separate `delivered` event. Other grants, including manually-fulfilled license keys, arrive `Pending`. See [Entitlement Grant](/developer-resources/webhooks/intents/entitlement-grant). | | `entitlement_grant.delivered` | Grant fulfillment completes — license key issued, file links resolved, or platform access granted. | | `entitlement_grant.failed` | Grant fulfillment fails. Check `error_code` and `error_message` in the payload. | | `entitlement_grant.revoked` | Access is withdrawn. Check `revocation_reason` in the payload. | For detailed payload schemas, sample events, and the full `revocation_reason` reference, see [Entitlement Grant Webhooks](/developer-resources/webhooks/intents/entitlement-grant). ## Credit Events | Event | Fires when | | - | - | | `credit.added` | Credits are granted to a customer (via subscription, one-time purchase, add-on, or API). | | `credit.deducted` | Credits are consumed through usage or manual debit. | | `credit.expired` | Unused credits expire after the configured expiry period. | | `credit.rolled_over` | Unused credits are carried forward to a new grant at cycle end. | | `credit.rollover_forfeited` | Credits are forfeited because the max rollover count was reached. | | `credit.overage_charged` | Overage charges are applied for usage beyond zero balance. | | `credit.overage_reset` | Accumulated overage charges are reset (for example, at the start of a new billing cycle). | | `credit.manual_adjustment` | A manual credit or debit adjustment is made. | | `credit.balance_low` | Credit balance drops below the configured threshold. | For detailed payload schemas and handler examples, see [Credit-Based Billing Webhooks](/developer-resources/webhooks/intents/credit). ## Recovery Events | Event | Fires when | | - | - | | `abandoned_checkout.detected` | An incomplete or failed checkout is detected after 60 minutes. | | `abandoned_checkout.recovered` | A customer completes payment through a recovery link. | For detailed payload schemas, field descriptions, and handler examples, see [Recovery Webhooks](/developer-resources/webhooks/intents/recovery). ## Dunning Events | Event | Fires when | | - | - | | `dunning.started` | A dunning attempt begins for a subscription that went past due or on hold, or was cancelled. | | `dunning.recovered` | A customer updates their payment method and the resulting charge succeeds. | For detailed payload schemas, field descriptions, and handler examples, see [Recovery Webhooks](/developer-resources/webhooks/intents/recovery). ## Payout Events Payout events track your funds moving from Dodo Payments to your bank account. They mirror the [payout statuses](/features/payouts/payout-structure#payout-status) shown in the dashboard. The payload is a payout object with the same shape as an entry from `GET /payouts`. | Event | Fires when | | - | - | | `payout.created` | A payout is created, either by the automatic payout cycle or off-cycle. | | `payout.in_progress` | The payout due date arrives and processing starts. | | `payout.on_hold` | A payout is paused or placed under review. | | `payout.success` | The payout to your bank account settles. | | `payout.failed` | A payout fails. The funds and fees are credited back to your wallet. | > [!WARNING] > > Payout events are neither terminal nor strictly ordered. `payout.failed` can arrive after `payout.success` when a bank returns the transfer, and `payout.success` can arrive after `payout.failed` when a failed payout is later recovered. The payload's `status` always reflects the event type (`payout.created` carries `not_initiated`), so use each event's top-level `timestamp` to find the latest state. > [!NOTE] > > `payout.created` was previously emitted as `payout.not_initiated`. If an existing endpoint filters on `payout.not_initiated`, update the filter to `payout.created` so it keeps matching. For detailed payload schemas, field descriptions, and handler examples, see [Payout Webhooks](/developer-resources/webhooks/intents/payout). # Set Up Workload Identity in the Dashboard Source: https://docs.dodopayments.com/developer-resources/workload-identity/dashboard-setup Create an identity provider and a mapping in the Dodo Payments dashboard, then view and revoke workload tokens and examine the audit events. You manage workload identity only in the dashboard. There is no public API to create providers or mappings. Each provider belongs to the mode that you select in the dashboard, test mode or live mode. To use both modes, create one provider in each mode. To open the page, go to **Developer → Workload Identity** in the dashboard. ![Workload Identity page in the dashboard that lists the identity providers of the business](https://mintcdn.com/dodopayments/rF0hPasO2gd-TLgx/images/workload-identity/providers-list.png?fit=max\&auto=format\&n=rF0hPasO2gd-TLgx\&q=85\&s=ee134382abe83b9cb60ae2e448e75b87) ## Permissions | Action | Scope that the dashboard user must hold | | - | - | | View providers, mappings, tokens, and events | `api_keys:read` | | Create, change, or delete a provider or a mapping | `api_keys:write` | | Revoke one token or all tokens of a mapping | `api_keys:write` | A mapping issues tokens like an API key. Thus each scope of a mapping must be a scope that you hold. You cannot change a mapping that has a scope that you do not hold. ## Create a Provider **1. Open Workload Identity** In the dashboard, go to **Developer → Workload Identity**. Make sure that the mode switch shows the mode that you want. **2. Select the provider type** Click **Add Provider** and select the platform of your workload. ![Provider type picker with logos for GitHub Actions, GitLab, Terraform Cloud, Google Cloud, Vercel, Kubernetes, AWS, and Custom OIDC](https://mintcdn.com/dodopayments/rF0hPasO2gd-TLgx/images/workload-identity/create-provider.png?fit=max\&auto=format\&n=rF0hPasO2gd-TLgx\&q=85\&s=8d077eb5b237b13f8780117fa906ded0) **3. Enter the issuer and the audience** Enter a name for the provider. The issuer and the audience have default values for most types: | Provider type | Issuer | | - | - | | `github_actions` | `https://token.actions.githubusercontent.com` (fixed) | | `gitlab` | `https://gitlab.com`, or the URL of your self-managed GitLab | | `terraform_cloud` | `https://app.terraform.io`, or the URL of your Terraform Enterprise | | `gcp` | `https://accounts.google.com` (fixed) | | `vercel` | `https://oidc.vercel.com/` | | `aws` | `https://.tokens.sts.global.api.aws` | | `kubernetes` | The issuer of your cluster | | `custom` | Any HTTPS URL | The default audience is `https://live.dodopayments.com` in live mode and `https://test.dodopayments.com` in test mode. Keep the default unless your platform cannot use it. **4. Save the provider** Click **Create**. Dodo Payments gets the discovery document and the JWKS of the issuer before it saves the provider. If the keys are not available, the dashboard shows an error that names the field. A `custom` provider can have a `discovery_url`, or uploaded public keys (JWKS) for an issuer that does not publish its keys. **5. Copy the provider id** Open the provider and copy its id (`wip_...`). Your workload uses this id. It is not a secret. ![Provider detail page with the provider id, the issuer, the audience, and the list of mappings](https://mintcdn.com/dodopayments/rF0hPasO2gd-TLgx/images/workload-identity/provider-detail.png?fit=max\&auto=format\&n=rF0hPasO2gd-TLgx\&q=85\&s=9b0ec766dd50d419f486965ac6c78031) > [!WARNING] > > A change to the audience, the discovery URL, or the uploaded keys of a provider revokes all tokens of all its mappings. A deleted provider also deletes its mappings and revokes their tokens. ## Add a Mapping A mapping tells Dodo Payments which JWTs to trust and which scopes to give them. ![Create mapping form with claim conditions, API scopes, allowed CIDR ranges, and token lifetime](https://mintcdn.com/dodopayments/rF0hPasO2gd-TLgx/images/workload-identity/create-mapping.png?fit=max\&auto=format\&n=rF0hPasO2gd-TLgx\&q=85\&s=5a87e9e64dfd23851e951a4eb266f2bb) **1. Open the provider** On the provider detail page, click **Add Mapping**. **2. Add the conditions** Each condition has a claim name and a value. All conditions must match (AND). A claim that is not in the JWT never matches. ```json theme={null} [ { "claim": "repository_owner_id", "value": "123456" }, { "claim": "repository_id", "value": "987654321" }, { "claim": "ref", "value": "refs/heads/main" } ] ``` * Add 1 to 20 conditions. A claim name has 128 characters or fewer. A value has 512 characters or fewer. * A value can end with one `*` after a prefix, for example `repo:acme/billing:*`. A value of only `*`, or a `*` in the middle, is not permitted. * Dodo Payments compares a number or a boolean claim in its JSON text form. Thus `"123456"` matches the number `123456`. * Conditions read top-level claims only. * Each provider type has required claims that you must pin with an exact value. Refer to the guide for your platform. **3. Select the scopes** Select the API scopes that the workload needs. Give the smallest set of scopes. **4. Add allowed CIDR ranges (optional)** Enter the IPv4 or IPv6 ranges of your workload, for example `203.0.113.0/24`. The exchange and each API call must come from an IP in the list. **5. Set the token lifetime (optional)** Enter a value between 300 and 3600 seconds. The default is 3600 seconds. The `terraform_cloud` type ignores this value and uses the end of the run phase. **6. Save the mapping** Click **Create**. The mapping is active immediately. > [!TIP] > > Make sure that a JWT matches exactly one mapping. If two enabled mappings match, the exchange fails with the `multiple_mappings` reason. A change to a mapping or a deleted mapping revokes all tokens of that mapping. ## View and Revoke Tokens Open a mapping to see its active tokens. The list shows the token prefix, the creation time, the expiry time, and the last use. ![Active tokens of a mapping with the prefix, created time, expiry time, and last used time](https://mintcdn.com/dodopayments/rF0hPasO2gd-TLgx/images/workload-identity/tokens-list.png?fit=max\&auto=format\&n=rF0hPasO2gd-TLgx\&q=85\&s=bd871a8e12821b46bd6ce96fb87271ba) * To revoke one token, click **Revoke** on the row of the token. * To revoke all tokens of the mapping, click **Revoke All Tokens**. The mapping stays, and the workload can do a new exchange. ![Confirmation dialog to revoke all active tokens of a mapping](https://mintcdn.com/dodopayments/rF0hPasO2gd-TLgx/images/workload-identity/revoke-tokens.png?fit=max\&auto=format\&n=rF0hPasO2gd-TLgx\&q=85\&s=4066903f7203bf1c145ab6f7cc9b2226) Workload tokens do not show on the **Developer → API Keys** page, and you cannot change them there. To stop a workload permanently, disable or delete its mapping. Revoking a token does not stop the next exchange. ## View Events The events list shows each exchange, failure, revocation, and configuration change for 90 days. Filter the list by provider, mapping, event type, or time range. ![Workload identity events list with event types, reason codes such as Too many failed exchanges in one minute, and source IPs](https://mintcdn.com/dodopayments/rF0hPasO2gd-TLgx/images/workload-identity/events-list.png?fit=max\&auto=format\&n=rF0hPasO2gd-TLgx\&q=85\&s=ca3de2d868ea72765f549665a15e5ebb) For a failed exchange, the reason code tells you what to correct. For example, `no_mapping` means that no mapping condition matched, and `audience_mismatch` means that the workload requested the JWT with the wrong audience. Refer to [Reason Codes](/developer-resources/workload-identity/overview#reason-codes) for the full list. > [card] [SDK Usage](/developer-resources/workload-identity/sdk-usage) > > Configure your workload to use the provider. > [card] [Overview](/developer-resources/workload-identity/overview) > > Token lifetime, revocation, and audit rules. # Workload Identity Federation Source: https://docs.dodopayments.com/developer-resources/workload-identity/overview Call the Dodo Payments API from CI pipelines and cloud workloads without a stored API key. Exchange a short-lived OIDC token from your platform for a short-lived Dodo token. Workload identity federation lets a workload call the Dodo Payments API with no stored API key. The workload gets a signed OIDC token (a JWT) from its own platform, for example GitHub Actions or Google Cloud. Dodo Payments verifies the JWT and gives back a short-lived Dodo token. The token expires in 1 hour or less, except for `terraform_cloud`, where it lasts until the run phase ends. > [card] [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup) > > Add an identity provider and a mapping, then monitor tokens and events. > [card] [SDK Usage](/developer-resources/workload-identity/sdk-usage) > > Configure the SDKs to do the exchange and the refresh for you. > [card] [Provider Guides](/developer-resources/workload-identity/providers/github-actions) > > Step-by-step setup for each supported platform. > [card] [Terraform](/developer-resources/workload-identity/terraform) > > Run the Terraform provider with no API key in your pipeline. ## Why Use Workload Identity An API key is a long-lived secret. You must store it in your CI system or your cloud, rotate it, and remove it when a person leaves. If the key leaks, an attacker can use it until you delete it. With workload identity federation: * **No secret to store.** The workload keeps only the identity provider id (`wip_...`). This id is not a secret. * **Short-lived credentials.** Each Dodo token expires in 1 hour or less. A `terraform_cloud` token lasts until the end of the run phase. To continue, the workload does a new exchange. * **Precise trust.** A mapping trusts only the JWTs that match its conditions, for example one repository and one branch. * **Same permissions model.** The token gets the scopes of the mapping, and the usual API key rate limits apply. * **Audit.** Each exchange, failure, revocation, and configuration change writes an event that you can see in the dashboard. ## Supported Platforms | Provider type | Platform | Guide | | - | - | - | | `github_actions` | GitHub Actions | [GitHub Actions](/developer-resources/workload-identity/providers/github-actions) | | `gitlab` | GitLab CI/CD (GitLab.com or self-managed) | [GitLab](/developer-resources/workload-identity/providers/gitlab) | | `terraform_cloud` | HCP Terraform or Terraform Enterprise | [Terraform Cloud](/developer-resources/workload-identity/providers/terraform-cloud) | | `gcp` | Google Cloud (Cloud Run, GCE, GKE metadata server) | [Google Cloud](/developer-resources/workload-identity/providers/google-cloud) | | `vercel` | Vercel | [Vercel](/developer-resources/workload-identity/providers/vercel) | | `kubernetes` | Kubernetes, including Amazon EKS | [Kubernetes and EKS](/developer-resources/workload-identity/providers/kubernetes) | | `aws` | AWS IAM outbound identity federation | [AWS](/developer-resources/workload-identity/providers/aws) | | `custom` | Any OIDC issuer with an HTTPS URL | [Custom OIDC](/developer-resources/workload-identity/providers/custom-oidc) | ## Key Concepts > [accordion] Identity provider > > An identity provider (`wip_...`) tells Dodo Payments which issuer to trust. It has a provider type, an issuer URL, and an audience. Each provider belongs to one mode, test mode or live mode. A business can have 50 providers. > [accordion] Mapping > > A mapping (`wim_...`) belongs to a provider. It has a list of claim conditions, a list of API scopes, an optional list of allowed CIDR ranges, and a token lifetime. A provider can have 50 mappings. > [accordion] Dodo token > > The exchange gives a Dodo token that has the same format as an API key. Send it as `Authorization: Bearer `. There is no refresh token. To renew the token, do the exchange again. ## How the Exchange Works ```mermaid theme={null} sequenceDiagram participant W as Your workload (SDK) participant P as Your platform (OIDC issuer) participant D as Dodo Payments API W->>P: Request an OIDC token (audience: Dodo Payments) P-->>W: Signed JWT W->>D: POST /workload-identity/token (JWT + identity_provider_id) D->>P: Get the signing keys (JWKS), cached D->>D: Verify the JWT and find one matching mapping D-->>W: Dodo token with the mapping scopes W->>D: API calls with Authorization: Bearer ``` 1. The workload requests an OIDC token from its platform. The audience of the token is the Dodo Payments audience of your mode. 2. The workload sends the JWT and the identity provider id to `POST /workload-identity/token`. This request does not need an API key. 3. Dodo Payments verifies the JWT signature with the public keys of the issuer. It also checks the issuer, the audience, the times, and the required claims. 4. Dodo Payments finds the enabled mappings whose conditions all match the JWT. Exactly one mapping must match. 5. Dodo Payments gives back a Dodo token with the scopes of that mapping. The SDKs do these steps for you. Refer to [SDK Usage](/developer-resources/workload-identity/sdk-usage). ### Audience The default audience is the Dodo Payments URL of the mode of the provider: | Mode | Audience | | - | - | | Live mode | `https://live.dodopayments.com` | | Test mode | `https://test.dodopayments.com` | Thus a test mode JWT fails in live mode. A provider cannot use the audience of the other mode. The `kubernetes`, `gcp`, `vercel`, and `custom` types must use the default audience. The `github_actions`, `gitlab`, `terraform_cloud`, and `aws` types can use a different audience. ### Verification Rules | Check | Rule | | - | - | | Signature | RS256, RS384, RS512, PS256, ES256, ES384, or EdDSA. The `kid` header must select a key from the JWKS of the issuer. | | `iss` | Must be equal to the issuer of the provider. | | `aud` | Must contain the audience of the provider. `aud` can be a string or a list. | | `sub` | Required. | | `iat`, `exp` | Required, with 60 seconds of clock leeway. `nbf` is used when present. | | JWT lifetime | `exp - iat` must be 1 hour or less. For `terraform_cloud` and `kubernetes`, 24 hours or less. | | Mapping | Exactly one enabled mapping must match. Dodo Payments never combines the scopes of two mappings. | ## Token Lifetime A Dodo token lives for the `token_ttl_seconds` of the mapping. The value is between 300 and 3600 seconds. The default is 3600 seconds (1 hour). The lifetime does not depend on the `exp` of the JWT. The `terraform_cloud` type is different. HCP Terraform gives one JWT for each plan or apply phase, and that JWT can do one exchange only. Thus the Dodo token lives until the JWT expires, which is the end of the run phase, with a maximum of 24 hours. A mapping can have a maximum of 500 active tokens. When it has 500, the exchange fails with the `token_limit` reason until tokens expire or you revoke them. ## Scopes The Dodo token gets the scopes of the mapping that matched. The workload cannot ask for more scopes. Each scope of a mapping must be a scope that the dashboard user who creates the mapping also holds. Refer to [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup#add-a-mapping). ## IP Allowlist A mapping can have a list of allowed CIDR ranges (`allowed_cidrs`), for IPv4 and IPv6. * **At the exchange.** If the source IP is not in the list, the exchange fails with `invalid_grant` and the `ip_not_allowed` reason. * **On each API call.** The Dodo token gets a copy of the list. Each API call from an IP that is not in the list gets `403`. Use this list to limit a workload to its known egress IPs, for example the NAT IPs of a cluster. ## Replay Protection The `github_actions`, `gitlab`, `terraform_cloud`, and `aws` platforms give a new JWT for each request. For these types, the JWT must have a `jti` claim, and each JWT can do one exchange only. A second exchange with the same JWT fails with `invalid_subject_token` and the `replay` reason. The `kubernetes`, `gcp`, `vercel`, and `custom` types do not enforce `jti`. For example, the kubelet writes the same service account token to a file for most of its life, and all processes in the pod read that token. For these types, these controls apply: * The provider must use the Dodo Payments audience of its mode, thus no other service accepts the JWT. * The mapping must pin a stable claim, for example `sub`. * The Dodo token lives 1 hour or less. * You can add `allowed_cidrs` to the mapping. ## Revocation These actions stop Dodo tokens immediately: | Action | Effect | | - | - | | Change or delete a mapping | Revokes all tokens of that mapping. | | Change the trust of a provider (`audience`, `discovery_url`, or `uploaded_jwks`) | Revokes all tokens of all mappings of that provider. A change to the name only does not revoke tokens. | | Delete a provider | Deletes its mappings and revokes their tokens. | | Revoke from the dashboard | Revokes one token, or all tokens of a mapping. The mapping stays. | | Self-revoke | The workload calls `POST /workload-identity/token/revoke` with its token. | Dodo Payments examines the JWT claims at the exchange only. A change on your platform after the exchange does not revoke a Dodo token. Examples are a moved repository, a deleted service account, or a renamed environment. The token stays valid until it expires, and the next exchange fails. For an immediate stop, use one of the actions in the table. To revoke the current token from a workload, send it to the revoke endpoint. The response is `204`: ```bash theme={null} curl -X POST https://live.dodopayments.com/workload-identity/token/revoke \ -H "Authorization: Bearer $DODO_TOKEN" ``` ## Audit Events The dashboard lists the events of your providers for 90 days. | Event type | When | | - | - | | `exchange_succeeded` | An exchange gave a token. Records the mapping, the token prefix, the allowed JWT claims, the source IP, and the user agent. | | `exchange_failed` | An exchange failed. Records the reason code, the source IP, and the user agent. Records the claims only when the signature is valid. | | `token_revoked` | A token was revoked from the dashboard or by the workload. | | `mapping_tokens_revoked` | All tokens of a mapping were revoked. | | `provider_created`, `provider_updated`, `provider_deleted` | A dashboard user changed a provider. Records the user and the changed fields. | | `mapping_created`, `mapping_updated`, `mapping_deleted` | A dashboard user changed a mapping. Records the user and the changed fields. | Events record only an allowlist of claims, for example `iss`, `sub`, `jti`, `repository`, `ref`, `sha`, and `run_id`. Dodo Payments never stores the JWT. ### Reason Codes | Reason code | Meaning | | - | - | | `invalid_signature` | The signature is not valid, or the algorithm is not permitted. | | `unknown_kid` | No key in the JWKS of the issuer has the `kid` of the JWT. | | `issuer_mismatch` | The `iss` claim is not the issuer of the provider. | | `audience_mismatch` | The `aud` claim does not contain the audience of the provider. | | `expired` | The JWT expired, is not valid yet, or has a lifetime that is too long. | | `missing_claim` | A required claim or header is missing or has the wrong type. | | `event_not_allowed` | The GitHub Actions event is `pull_request_target` or `workflow_run`. | | `replay` | The JWT was used before (`jti`). | | `no_mapping` | No enabled mapping matches the JWT. | | `multiple_mappings` | More than one enabled mapping matches the JWT. | | `ip_not_allowed` | The source IP is not in the `allowed_cidrs` of the mapping. | | `jwks_unavailable` | Dodo Payments could not get the keys of the issuer. | | `token_limit` | The mapping has 500 active tokens. | | `rate_limited` | Too many failed exchanges in one minute. Dodo Payments recorded one summary event in place of the other failure events. | ### Event Limits Dodo Payments records failure events only for a known provider. A provider records a maximum of 60 `exchange_failed` events each minute for one source IP, and 600 each minute for all source IPs. The first failure over a limit records one `rate_limited` event. These limits apply to the audit log only. They do not change the result of an exchange. ## Exchange Errors The exchange endpoint uses the OAuth 2.0 error format `{ "error", "error_description" }`. | `error` | HTTP status | When | | - | - | - | | `invalid_request` | 400 | A field is missing or not supported. | | `invalid_subject_token` | 401 | Bad signature, unknown `kid`, wrong `iss` or `aud`, expired JWT, missing claim, or a JWT that was used before. | | `invalid_grant` | 403 | Unknown provider, wrong mode, archived business, IP not allowed, or not exactly one matching mapping. | | `temporarily_unavailable` | 503 | Dodo Payments could not get the discovery document or the JWKS. Try again. | `error_description` tells you which claim or value to correct. It does not show the expected value of a condition. The audit event has the full reason. > [card] [Dashboard Setup](/developer-resources/workload-identity/dashboard-setup) > > Create your first provider and mapping. > [card] [SDK Usage](/developer-resources/workload-identity/sdk-usage) > > Use workload identity from the SDKs or with curl. # Workload Identity for AWS Source: https://docs.dodopayments.com/developer-resources/workload-identity/providers/aws Call the Dodo Payments API from AWS workloads with a JWT from AWS IAM outbound identity federation, signed for the IAM role of the workload. AWS IAM outbound identity federation gives an IAM role a signed JWT through the STS `GetWebIdentityToken` action. Dodo Payments trusts this token through an `aws` provider. Use it for Lambda, ECS, EC2, and other AWS compute that has an IAM role. > [!NOTE] > > For pods on Amazon EKS, use the [Kubernetes](/developer-resources/workload-identity/providers/kubernetes) type with a projected service account token. ## Provider Settings | Setting | Value | | - | - | | Provider type | `aws` | | Issuer | The account issuer, `https://.tokens.sts.global.api.aws` | | Audience | `https://live.dodopayments.com` or `https://test.dodopayments.com` | | Replay protection | Each JWT can do one exchange (`jti`). | | JWT lifetime | 1 hour or less. | Turn on outbound identity federation in your AWS account, then copy the issuer URL of the account into the provider. ## Required Claims The mapping must pin `sub` with the ARN of the IAM role: ```json theme={null} [ { "claim": "sub", "value": "arn:aws:iam::111122223333:role/billing-worker" } ] ``` ## IAM Permissions The role of the workload must have permission to call `sts:GetWebIdentityToken`. This policy lets the role get tokens only for the Dodo Payments audience, with a maximum lifetime of 5 minutes: ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "sts:GetWebIdentityToken", "Resource": "*", "Condition": { "ForAllValues:StringEquals": { "sts:IdentityTokenAudience": "https://live.dodopayments.com" }, "NumericLessThanEquals": { "sts:DurationSeconds": 300 } } } ] } ``` For test mode, use `https://test.dodopayments.com` as the audience. ## SDK Usage The `aws(fn)` helper takes a function that returns a new JWT. Call `GetWebIdentityToken` in that function with the Dodo Payments audience. The SDK calls the function for each exchange. `GetWebIdentityToken` needs a signing algorithm: `RS256` or `ES384`. The action is not available on the STS global endpoint, so configure the STS client with a region. ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; import { STSClient, GetWebIdentityTokenCommand } from '@aws-sdk/client-sts'; const sts = new STSClient({}); const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: process.env.DODO_PAYMENTS_IDENTITY_PROVIDER_ID, provider: DodoPayments.workloadIdentity.aws(async () => { const result = await sts.send( new GetWebIdentityTokenCommand({ Audience: ['https://live.dodopayments.com'], SigningAlgorithm: 'RS256', DurationSeconds: 300, }), ); return result.WebIdentityToken!; }), }, }); ``` ```python Python theme={null} import os import boto3 from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, aws sts = boto3.client("sts") def get_jwt() -> str: response = sts.get_web_identity_token( Audience=["https://live.dodopayments.com"], SigningAlgorithm="RS256", DurationSeconds=300, ) return response["WebIdentityToken"] client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id=os.environ["DODO_PAYMENTS_IDENTITY_PROVIDER_ID"], provider=aws(get_jwt), ), ) ``` Refer to [SDK Usage](/developer-resources/workload-identity/sdk-usage) for the other languages. # Workload Identity for a Custom OIDC Issuer Source: https://docs.dodopayments.com/developer-resources/workload-identity/providers/custom-oidc Trust JWTs from any OIDC issuer with an HTTPS URL, through a discovery document or uploaded public keys, and exchange them for Dodo tokens. Use a `custom` provider for an issuer that has no built-in type, for example a self-hosted identity provider or a CI system with OIDC support. ## Provider Settings | Setting | Value | | - | - | | Provider type | `custom` | | Issuer | Any HTTPS URL. The `iss` claim must be equal to this value. | | Audience | Must be `https://live.dodopayments.com` or `https://test.dodopayments.com` | | Keys | The default discovery endpoint of the issuer, a `discovery_url`, or uploaded keys (JWKS) | | Replay protection | Not enforced. The audience and the `sub` pin replace it. | | JWT lifetime | 1 hour or less. | A `custom` provider cannot use the issuer host of a built-in type, for example `token.actions.githubusercontent.com` or `gitlab.com`. Use the built-in type for these issuers. ### Keys Select one key source: * **Discovery (default).** Dodo Payments reads the discovery document of the issuer and its `jwks_uri`. The `issuer` in the discovery document must be equal to the issuer of the provider. * **Discovery URL.** Enter a `discovery_url` when the discovery document is not at the default location. * **Uploaded keys.** For an issuer with no public JWKS, upload a JWKS. It must have 1 to 20 public keys, with a size of 64 KB or less. Each key must have a `kty` of `RSA`, `EC` (`P-256` or `P-384`), or `OKP` (`Ed25519`). Private key members are not permitted. Dodo Payments gets the remote keys over HTTPS only. It does not follow redirects, and it refuses private IP addresses. The JWKS must have a minimum of one key with a `kid` and a permitted algorithm. ## Required Claims The mapping must pin `sub` with an exact value: ```json theme={null} [ { "claim": "sub", "value": "service:billing-worker" } ] ``` The JWT must have `kid` in its header, and `iss`, `aud`, `sub`, `iat`, and `exp` in its payload. Refer to [Verification Rules](/developer-resources/workload-identity/overview#verification-rules). ## SDK Usage Write the JWT to a file, and point `DODO_PAYMENTS_IDENTITY_TOKEN_FILE` to it. The `file()` helper reads the file for each exchange. ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: process.env.DODO_PAYMENTS_IDENTITY_PROVIDER_ID, provider: DodoPayments.workloadIdentity.file(), }, }); ``` ```python Python theme={null} import os from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, file client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id=os.environ["DODO_PAYMENTS_IDENTITY_PROVIDER_ID"], provider=file(), ), ) ``` ```go Go theme={null} client := dodopayments.NewClient( option.WithEnvironmentLiveMode(), option.WithWorkloadIdentity(option.WorkloadIdentity{ IdentityProviderID: os.Getenv("DODO_PAYMENTS_IDENTITY_PROVIDER_ID"), Provider: workloadidentity.File(""), }), ) ``` You can also send the JWT to the exchange endpoint yourself. Refer to [Raw HTTP Exchange](/developer-resources/workload-identity/sdk-usage#raw-http-exchange). # Workload Identity for GitHub Actions Source: https://docs.dodopayments.com/developer-resources/workload-identity/providers/github-actions Call the Dodo Payments API from a GitHub Actions workflow with the GitHub OIDC token, with no API key stored in GitHub secrets. A GitHub Actions job can get an OIDC token from GitHub for each run. Dodo Payments trusts this token through a `github_actions` provider. ## Provider Settings | Setting | Value | | - | - | | Provider type | `github_actions` | | Issuer | `https://token.actions.githubusercontent.com` (fixed) | | Audience | `https://live.dodopayments.com` or `https://test.dodopayments.com` | | Replay protection | Each JWT can do one exchange (`jti`). | | JWT lifetime | 1 hour or less. | ## Required Claims The mapping must pin `repository_owner_id` or `repository_id` with an exact numeric value. A repository name can pass to a new owner after a delete, but a numeric id cannot. The dashboard can find the `repository_id` from the repository name. Add other conditions to limit the trust, for example: ```json theme={null} [ { "claim": "repository_id", "value": "987654321" }, { "claim": "ref", "value": "refs/heads/main" }, { "claim": "environment", "value": "production" } ] ``` Useful claims are `repository`, `repository_owner`, `ref`, `ref_type`, `environment`, `event_name`, `workflow_ref`, `job_workflow_ref`, and `sub`, for example `repo:acme/billing:environment:production`. > [!WARNING] > > Dodo Payments refuses JWTs from the `pull_request_target` and `workflow_run` events, with the `event_not_allowed` reason. A run of these events can execute code from a fork with the identity of the base repository. ## Workflow Give the job the `id-token: write` permission. The SDK uses `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN`, which GitHub sets when the job has this permission. ```yaml expandable theme={null} name: Sync products on: push: branches: [main] jobs: sync: runs-on: ubuntu-latest environment: production permissions: id-token: write contents: read env: DODO_PAYMENTS_IDENTITY_PROVIDER_ID: wip_... steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - run: npm ci - run: node scripts/sync-products.js ``` To get the JWT without an SDK, request it with the Dodo Payments audience: ```bash theme={null} PLATFORM_JWT=$(curl -sS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \ "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=https://live.dodopayments.com" | jq -r .value) ``` Then send it to the exchange endpoint. Refer to [Raw HTTP Exchange](/developer-resources/workload-identity/sdk-usage#raw-http-exchange). ## SDK Usage ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: process.env.DODO_PAYMENTS_IDENTITY_PROVIDER_ID, provider: DodoPayments.workloadIdentity.githubActions(), }, }); ``` ```python Python theme={null} import os from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, github_actions client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id=os.environ["DODO_PAYMENTS_IDENTITY_PROVIDER_ID"], provider=github_actions(), ), ) ``` ```go Go theme={null} client := dodopayments.NewClient( option.WithEnvironmentLiveMode(), option.WithWorkloadIdentity(option.WorkloadIdentity{ IdentityProviderID: os.Getenv("DODO_PAYMENTS_IDENTITY_PROVIDER_ID"), Provider: workloadidentity.GitHubActions(""), }), ) ``` The helper requests a new JWT for each exchange, thus a long job can refresh its Dodo token. Refer to [SDK Usage](/developer-resources/workload-identity/sdk-usage) for the other languages. # Workload Identity for GitLab CI/CD Source: https://docs.dodopayments.com/developer-resources/workload-identity/providers/gitlab Call the Dodo Payments API from a GitLab CI/CD job with a GitLab ID token, on GitLab.com or a self-managed GitLab instance. A GitLab CI/CD job can get an ID token from GitLab. Dodo Payments trusts this token through a `gitlab` provider. ## Provider Settings | Setting | Value | | - | - | | Provider type | `gitlab` | | Issuer | `https://gitlab.com`, or the URL of your self-managed GitLab | | Audience | `https://live.dodopayments.com` or `https://test.dodopayments.com` | | Replay protection | Each JWT can do one exchange (`jti`). | | JWT lifetime | 1 hour or less. | ## Required Claims The mapping must pin `namespace_id` or `project_id` with an exact numeric value. ```json theme={null} [ { "claim": "project_id", "value": "42424242" }, { "claim": "ref", "value": "main" }, { "claim": "ref_protected", "value": "true" } ] ``` Other useful claims are `namespace_path`, `project_path`, `ref_type`, `pipeline_source`, `environment`, and `sub`. ## Job Configuration Define an ID token with the Dodo Payments audience in `.gitlab-ci.yml`. GitLab sets it as an environment variable of the job. ```yaml expandable theme={null} sync-products: image: node:22 id_tokens: DODO_PAYMENTS_ID_TOKEN: aud: https://live.dodopayments.com variables: DODO_PAYMENTS_IDENTITY_PROVIDER_ID: wip_... script: - npm ci - node scripts/sync-products.js rules: - if: $CI_COMMIT_BRANCH == "main" ``` The `gitlab()` helper reads `DODO_PAYMENTS_ID_TOKEN`. If you use a different variable name, give the name to the helper. Each job gets one ID token, and the token can do one exchange. A job that runs longer than the Dodo token lifetime cannot refresh with the same ID token. ## SDK Usage ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: process.env.DODO_PAYMENTS_IDENTITY_PROVIDER_ID, provider: DodoPayments.workloadIdentity.gitlab(), }, }); ``` ```python Python theme={null} import os from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, gitlab client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id=os.environ["DODO_PAYMENTS_IDENTITY_PROVIDER_ID"], provider=gitlab(), ), ) ``` ```go Go theme={null} client := dodopayments.NewClient( option.WithEnvironmentLiveMode(), option.WithWorkloadIdentity(option.WorkloadIdentity{ IdentityProviderID: os.Getenv("DODO_PAYMENTS_IDENTITY_PROVIDER_ID"), Provider: workloadidentity.GitLab(""), }), ) ``` Refer to [SDK Usage](/developer-resources/workload-identity/sdk-usage) for the other languages. # Workload Identity for Google Cloud Source: https://docs.dodopayments.com/developer-resources/workload-identity/providers/google-cloud Call the Dodo Payments API from Cloud Run, Compute Engine, or GKE with a Google-signed identity token for the service account of the workload. A workload on Google Cloud can get a Google-signed identity token for its service account from the metadata server. Dodo Payments trusts this token through a `gcp` provider. ## Provider Settings | Setting | Value | | - | - | | Provider type | `gcp` | | Issuer | `https://accounts.google.com` (fixed) | | Audience | Must be `https://live.dodopayments.com` or `https://test.dodopayments.com` | | Replay protection | Not enforced. The audience and the `sub` pin replace it. | | JWT lifetime | 1 hour or less. | ## Required Claims The mapping must pin `sub` with the numeric unique id of the service account. Do not use the email of the service account. To find the unique id, run: ```bash theme={null} gcloud iam service-accounts describe billing@my-project.iam.gserviceaccount.com \ --format='value(uniqueId)' ``` ```json theme={null} [ { "claim": "sub", "value": "112233445566778899000" } ] ``` ## Get the Token Cloud Run, Compute Engine, and GKE with Workload Identity have a metadata server. The `gcp()` helper requests the token from it with the Dodo Payments audience. To get the token yourself: ```bash theme={null} PLATFORM_JWT=$(curl -sS -H "Metadata-Flavor: Google" \ "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://live.dodopayments.com") ``` ## SDK Usage ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: process.env.DODO_PAYMENTS_IDENTITY_PROVIDER_ID, provider: DodoPayments.workloadIdentity.gcp(), }, }); ``` ```python Python theme={null} import os from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, gcp client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id=os.environ["DODO_PAYMENTS_IDENTITY_PROVIDER_ID"], provider=gcp(), ), ) ``` ```go Go theme={null} client := dodopayments.NewClient( option.WithEnvironmentLiveMode(), option.WithWorkloadIdentity(option.WorkloadIdentity{ IdentityProviderID: os.Getenv("DODO_PAYMENTS_IDENTITY_PROVIDER_ID"), Provider: workloadidentity.GCP(""), }), ) ``` Set `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` on the Cloud Run service or the instance: ```bash theme={null} gcloud run services update billing-api \ --service-account billing@my-project.iam.gserviceaccount.com \ --set-env-vars DODO_PAYMENTS_IDENTITY_PROVIDER_ID=wip_... ``` The SDK refreshes the Dodo token before it expires, thus a long-running service needs no stored secret. Refer to [SDK Usage](/developer-resources/workload-identity/sdk-usage) for the other languages. # Workload Identity for Kubernetes and Amazon EKS Source: https://docs.dodopayments.com/developer-resources/workload-identity/providers/kubernetes Call the Dodo Payments API from a Kubernetes pod with a projected service account token, on any cluster with a public OIDC issuer, including Amazon EKS. A Kubernetes pod can get a service account token with a custom audience as a projected volume. Dodo Payments trusts this token through a `kubernetes` provider. Use this type for Amazon EKS also. Do not use the `aws` type for EKS. ## Provider Settings | Setting | Value | | - | - | | Provider type | `kubernetes` | | Issuer | The issuer of your cluster, for example `https://oidc.eks..amazonaws.com/id/` on EKS | | Audience | Must be `https://live.dodopayments.com` or `https://test.dodopayments.com` | | Replay protection | Not enforced. All processes in the pod read the same token until the kubelet writes a new one. | | JWT lifetime | 24 hours or less. | Dodo Payments must be able to get the discovery document and the JWKS of the issuer over HTTPS. The EKS OIDC issuer is public. For a cluster with a private issuer, use a `custom` provider with uploaded keys. Refer to [Custom OIDC](/developer-resources/workload-identity/providers/custom-oidc). To find the issuer of an EKS cluster, run: ```bash theme={null} aws eks describe-cluster --name my-cluster \ --query "cluster.identity.oidc.issuer" --output text ``` ## Required Claims The mapping must pin `sub` to one service account: ```json theme={null} [ { "claim": "sub", "value": "system:serviceaccount:payments:billing-worker" } ] ``` Conditions read top-level claims only. The namespace and the pod are in the `kubernetes.io` object, thus pin them through `sub`. > [!TIP] > > Add the egress IPs of the cluster, for example the NAT gateway IPs, to the `allowed_cidrs` of the mapping. A stolen token file then cannot do an exchange from another network. ## Pod Configuration Mount a projected service account token with the Dodo Payments audience, and point `DODO_PAYMENTS_IDENTITY_TOKEN_FILE` to it: ```yaml expandable theme={null} apiVersion: v1 kind: ServiceAccount metadata: name: billing-worker namespace: payments --- apiVersion: apps/v1 kind: Deployment metadata: name: billing-worker namespace: payments spec: replicas: 2 selector: matchLabels: app: billing-worker template: metadata: labels: app: billing-worker spec: serviceAccountName: billing-worker containers: - name: worker image: ghcr.io/acme/billing-worker:latest env: - name: DODO_PAYMENTS_IDENTITY_PROVIDER_ID value: wip_... volumeMounts: - name: dodo-token mountPath: /var/run/secrets/tokens readOnly: true volumes: - name: dodo-token projected: sources: - serviceAccountToken: path: dodo-token audience: https://live.dodopayments.com expirationSeconds: 3600 ``` The kubelet writes a new token when the token is older than 80% of its life. With `expirationSeconds: 3600`, this occurs after about 48 minutes. The SDK reads the file again for each exchange. ## SDK Usage ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: process.env.DODO_PAYMENTS_IDENTITY_PROVIDER_ID, provider: DodoPayments.workloadIdentity.kubernetes(), }, }); ``` ```python Python theme={null} import os from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, kubernetes client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id=os.environ["DODO_PAYMENTS_IDENTITY_PROVIDER_ID"], provider=kubernetes(), ), ) ``` ```go Go theme={null} client := dodopayments.NewClient( option.WithEnvironmentLiveMode(), option.WithWorkloadIdentity(option.WorkloadIdentity{ IdentityProviderID: os.Getenv("DODO_PAYMENTS_IDENTITY_PROVIDER_ID"), Provider: workloadidentity.Kubernetes(""), }), ) ``` The `kubernetes()` helper reads `/var/run/secrets/tokens/dodo-token`. To use a different path, give the path to the helper. Refer to [SDK Usage](/developer-resources/workload-identity/sdk-usage) for the other languages. # Workload Identity for HCP Terraform Source: https://docs.dodopayments.com/developer-resources/workload-identity/providers/terraform-cloud Let HCP Terraform or Terraform Enterprise runs call the Dodo Payments API with a workload identity token, with separate mappings for plan and apply. HCP Terraform gives each plan and each apply phase a workload identity token. Dodo Payments trusts this token through a `terraform_cloud` provider. ## Provider Settings | Setting | Value | | - | - | | Provider type | `terraform_cloud` | | Issuer | `https://app.terraform.io`, or the URL of your Terraform Enterprise | | Audience | `https://live.dodopayments.com` or `https://test.dodopayments.com` | | Replay protection | Each JWT can do one exchange (`jti`). | | JWT lifetime | 24 hours or less. | | Dodo token lifetime | Until the JWT expires (the end of the run phase), 24 hours maximum. | ## Required Claims The mapping must pin both `terraform_organization_id` and `terraform_workspace_id`. Pin `terraform_run_phase` to split plan and apply: ```json theme={null} [ { "claim": "terraform_organization_id", "value": "org-..." }, { "claim": "terraform_workspace_id", "value": "ws-..." }, { "claim": "terraform_run_phase", "value": "apply" } ] ``` Create a second mapping with `terraform_run_phase` set to `plan` and read scopes only. ## Workspace Configuration In the workspace, add these environment variables: | Variable | Value | | - | - | | `TFC_WORKLOAD_IDENTITY_AUDIENCE` | `https://live.dodopayments.com` (or `https://test.dodopayments.com`) | | `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` | `wip_...` | HCP Terraform then sets `TFC_WORKLOAD_IDENTITY_TOKEN` in each run phase. ## Terraform Provider ```hcl theme={null} provider "dodopayments" { environment = "live_mode" workload_identity { token_source = "terraform_cloud" } } ``` The provider does one exchange at the start of each phase. Refer to [Terraform](/developer-resources/workload-identity/terraform). ## SDK Usage For code that runs in a Terraform run, for example an external data source, use the `terraformCloud()` helper: ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: process.env.DODO_PAYMENTS_IDENTITY_PROVIDER_ID, provider: DodoPayments.workloadIdentity.terraformCloud(), }, }); ``` ```python Python theme={null} import os from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, terraform_cloud client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id=os.environ["DODO_PAYMENTS_IDENTITY_PROVIDER_ID"], provider=terraform_cloud(), ), ) ``` ```go Go theme={null} client := dodopayments.NewClient( option.WithEnvironmentLiveMode(), option.WithWorkloadIdentity(option.WorkloadIdentity{ IdentityProviderID: os.Getenv("DODO_PAYMENTS_IDENTITY_PROVIDER_ID"), Provider: workloadidentity.TerraformCloud(), }), ) ``` > [!WARNING] > > The JWT of a phase can do one exchange only. Two processes that read the same `TFC_WORKLOAD_IDENTITY_TOKEN` cannot both do an exchange. The second exchange fails with the `replay` reason. # Workload Identity for Vercel Source: https://docs.dodopayments.com/developer-resources/workload-identity/providers/vercel Call the Dodo Payments API from Vercel functions with the Vercel OIDC token, with no API key in your project environment variables. Vercel can give your functions an OIDC token for the project. Dodo Payments trusts this token through a `vercel` provider. ## Provider Settings | Setting | Value | | - | - | | Provider type | `vercel` | | Issuer | `https://oidc.vercel.com/` (team issuer mode) | | Audience | Must be `https://live.dodopayments.com` or `https://test.dodopayments.com` | | Replay protection | Not enforced. The audience and the claim pins replace it. | | JWT lifetime | 1 hour or less. | The team slug has lowercase letters, digits, and hyphens only. ## Required Claims The mapping must pin both `owner_id` (the team id) and `project_id`. Add `environment` to limit the trust to one environment: ```json theme={null} [ { "claim": "owner_id", "value": "team_..." }, { "claim": "project_id", "value": "prj_..." }, { "claim": "environment", "value": "production" } ] ``` ## Project Configuration 1. In the Vercel project, open **Settings → Security** and turn on **Secure backend access with OIDC federation**. 2. Select the **Team** issuer mode. 3. Add `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` with the value `wip_...` to the project environment variables. ## Token Audience The default `aud` claim of a Vercel OIDC token is `https://vercel.com/`. Dodo Payments does not accept this audience. The `vercel()` helper exchanges the Vercel token at `https://oidc.vercel.com/~token` for a token with the Dodo Payments audience. You do not have to do more steps. > [!NOTE] > > This exchange is available from these SDK versions: TypeScript 2.59.0, Python 1.125.0, Go v1.125.0, Java 1.125.0, Kotlin 1.125.0, Ruby 2.37.0, PHP 6.34.0, C# 6.43.0, Rust 1.127.0, and the Terraform provider 0.3.2. An older version sends the token with the default Vercel audience, and the exchange fails. ## SDK Usage ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: process.env.DODO_PAYMENTS_IDENTITY_PROVIDER_ID, provider: DodoPayments.workloadIdentity.vercel(), }, }); ``` ```python Python theme={null} import os from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, vercel client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id=os.environ["DODO_PAYMENTS_IDENTITY_PROVIDER_ID"], provider=vercel(), ), ) ``` ```go Go theme={null} client := dodopayments.NewClient( option.WithEnvironmentLiveMode(), option.WithWorkloadIdentity(option.WorkloadIdentity{ IdentityProviderID: os.Getenv("DODO_PAYMENTS_IDENTITY_PROVIDER_ID"), Provider: workloadidentity.Vercel(), }), ) ``` Refer to [SDK Usage](/developer-resources/workload-identity/sdk-usage) for the other languages. # Use Workload Identity with the SDKs Source: https://docs.dodopayments.com/developer-resources/workload-identity/sdk-usage Configure the Dodo Payments SDKs to exchange a platform OIDC token for a Dodo token and refresh it, or do the exchange yourself with curl. Each Dodo Payments server SDK has a `workloadIdentity` client option. The SDK gets the JWT from your platform, does the exchange, keeps the Dodo token, and refreshes it. > [!NOTE] > > The workload identity options are available from these SDK versions: TypeScript 2.58.0, Python 1.124.0, Go v1.124.0, Java 1.124.0, Kotlin 1.124.0, Ruby 2.36.0, PHP 6.33.0, C# 6.42.0, and Rust 1.125.0. ## Client Configuration Give the SDK two values: the identity provider id (`wip_...`) and a provider helper that gets the JWT. The samples use live mode. The Java, Kotlin, and PHP clients use live mode when you do not set a mode. ```typescript TypeScript theme={null} import DodoPayments from 'dodopayments'; const client = new DodoPayments({ environment: 'live_mode', workloadIdentity: { identityProviderId: 'wip_...', provider: DodoPayments.workloadIdentity.githubActions(), }, }); ``` ```python Python theme={null} from dodopayments import DodoPayments from dodopayments.workload_identity import WorkloadIdentity, github_actions client = DodoPayments( environment="live_mode", workload_identity=WorkloadIdentity( identity_provider_id="wip_...", provider=github_actions(), ), ) ``` ```go Go theme={null} import ( "github.com/dodopayments/dodopayments-go" "github.com/dodopayments/dodopayments-go/option" "github.com/dodopayments/dodopayments-go/workloadidentity" ) client := dodopayments.NewClient( option.WithEnvironmentLiveMode(), option.WithWorkloadIdentity(option.WorkloadIdentity{ IdentityProviderID: "wip_...", Provider: workloadidentity.GitHubActions(""), }), ) ``` ```java Java theme={null} import com.dodopayments.api.client.DodoPaymentsClient; import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient; import com.dodopayments.api.workloadidentity.SubjectTokenProviders; import com.dodopayments.api.workloadidentity.WorkloadIdentity; DodoPaymentsClient client = DodoPaymentsOkHttpClient.builder() .workloadIdentity(WorkloadIdentity.builder() .identityProviderId("wip_...") .provider(SubjectTokenProviders.githubActions()) .build()) .build(); ``` ```kotlin Kotlin theme={null} import com.dodopayments.api.client.DodoPaymentsClient import com.dodopayments.api.client.okhttp.DodoPaymentsOkHttpClient import com.dodopayments.api.workloadidentity.SubjectTokenProviders import com.dodopayments.api.workloadidentity.WorkloadIdentity val client: DodoPaymentsClient = DodoPaymentsOkHttpClient.builder() .workloadIdentity( WorkloadIdentity.builder() .identityProviderId("wip_...") .provider(SubjectTokenProviders.githubActions()) .build() ) .build() ``` ```ruby Ruby theme={null} client = Dodopayments::Client.new( environment: "live_mode", workload_identity: Dodopayments::WorkloadIdentity::Config.new( identity_provider_id: "wip_...", provider: Dodopayments::WorkloadIdentity.github_actions ) ) ``` ```php PHP theme={null} use Dodopayments\Client; use Dodopayments\WorkloadIdentity\Providers; use Dodopayments\WorkloadIdentity\WorkloadIdentity; $client = new Client( workloadIdentity: new WorkloadIdentity( provider: Providers::githubActions(), identityProviderId: 'wip_...', ), ); ``` ```csharp C# theme={null} using DodoPayments.Client; using DodoPayments.Client.Core; DodoPaymentsClient client = new() { BaseUrl = EnvironmentUrl.LiveMode, WorkloadIdentity = new() { IdentityProviderID = "wip_...", Provider = WorkloadIdentityProviders.GitHubActions(), }, }; ``` ```rust Rust theme={null} use dodopayments::workload_identity; use dodopayments::{Client, ClientConfig, WorkloadIdentity}; let client = Client::new( ClientConfig::new("https://live.dodopayments.com").with_workload_identity( WorkloadIdentity::new(workload_identity::github_actions(None)) .with_identity_provider_id("wip_..."), ), )?; ``` > [!WARNING] > > Do not set an API key (`bearerToken`) and `workloadIdentity` together. The SDK gives an error when you set the two options. ## Provider Helpers Each SDK has the same set of helpers. The name follows the style of the language, for example `githubActions()` in TypeScript and `github_actions()` in Python. | Helper | Use it for | How it gets the JWT | | - | - | - | | `githubActions()` | GitHub Actions | Requests a new token from the GitHub OIDC endpoint for each exchange. | | `gitlab()` | GitLab CI/CD | Reads the ID token that your `.gitlab-ci.yml` defines. | | `terraformCloud()` | HCP Terraform runs | Reads `TFC_WORKLOAD_IDENTITY_TOKEN`. | | `gcp()` | Cloud Run, GCE, GKE | Requests an identity token from the metadata server. | | `vercel()` | Vercel functions | Reads the Vercel OIDC token and exchanges it at Vercel for a token with the Dodo Payments audience. Refer to the [Vercel guide](/developer-resources/workload-identity/providers/vercel#token-audience) for the SDK versions. | | `kubernetes()` | Kubernetes and EKS | Reads the projected service account token file. | | `file()` | Any platform that writes a JWT to a file | Reads the file in `DODO_PAYMENTS_IDENTITY_TOKEN_FILE`. | | `aws(fn)` | AWS IAM outbound federation | Calls your function, which returns a JWT from AWS STS. | | `static(token)` | Tests | Returns the JWT that you give. Java uses the name `staticToken(token)`, and Rust uses `static_token(token)`. | | `auto()` | Code that runs on more than one platform | Finds the platform from the environment. | The guide for each platform shows the configuration that the helper needs. ## Environment Variables | Variable | Use | | - | - | | `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` | The identity provider id. The SDK reads it when you do not set `identityProviderId`. If `DODO_PAYMENTS_API_KEY` is not set and this variable is set, the SDK uses workload identity with `auto()`. | | `DODO_PAYMENTS_IDENTITY_TOKEN_FILE` | The path of a file that holds the JWT. The `file()` helper reads it. | ## Refresh and Retry The SDK manages the Dodo token for you: * It does the first exchange before the first API call. * It does a new exchange when 5 minutes or less remain on the token. * When many requests run at the same time, the SDK does one exchange for all of them. * If an API call gets `401`, the SDK does one new exchange and tries the call one more time. ## Revoke the Token To stop the current token before it expires, for example at the end of a CI job, call revoke: ```typescript TypeScript theme={null} await client.workloadIdentity.revoke(); ``` ```python Python theme={null} client.workload_identity.revoke() ``` ```go Go theme={null} err := client.WorkloadIdentity.Revoke(ctx) ``` ```java Java theme={null} client.workloadIdentity().revoke(); ``` ```kotlin Kotlin theme={null} client.workloadIdentity()?.revoke() ``` ```ruby Ruby theme={null} client.workload_identity.revoke ``` ```php PHP theme={null} $client->workloadIdentity?->revoke(); ``` ```csharp C# theme={null} await client.RevokeWorkloadIdentityToken(); ``` ```rust Rust theme={null} client.revoke_workload_identity().await?; ``` ```bash cURL theme={null} curl -X POST https://live.dodopayments.com/workload-identity/token/revoke \ -H "Authorization: Bearer $DODO_TOKEN" ``` The revoke call stops the cached token and clears the cache. The next API call does a new exchange. ## Raw HTTP Exchange Without an SDK, send the JWT to `POST /workload-identity/token`. The request is an RFC 8693 token exchange and needs no API key. Use `https://test.dodopayments.com` for test mode. ```bash theme={null} curl -X POST https://live.dodopayments.com/workload-identity/token \ -H "Content-Type: application/json" \ -d '{ "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", "subject_token_type": "urn:ietf:params:oauth:token-type:jwt", "subject_token": "'"$PLATFORM_JWT"'", "identity_provider_id": "wip_..." }' ``` `subject_token_type` must be `urn:ietf:params:oauth:token-type:jwt`. A successful response: ```json theme={null} { "access_token": "", "issued_token_type": "urn:ietf:params:oauth:token-type:access_token", "token_type": "Bearer", "expires_in": 3600, "expires_at": "2026-10-28T10:00:00Z", "scope": " " } ``` Send `access_token` as `Authorization: Bearer ` on your API calls. There is no refresh token. Before `expires_at`, get a new JWT and do the exchange again. An error response uses the OAuth 2.0 format: ```json theme={null} { "error": "invalid_grant", "error_description": "" } ``` Refer to [Exchange Errors](/developer-resources/workload-identity/overview#exchange-errors) for the error codes. > [card] [GitHub Actions](/developer-resources/workload-identity/providers/github-actions) > > Use workload identity in a GitHub Actions workflow. > [card] [Kubernetes and EKS](/developer-resources/workload-identity/providers/kubernetes) > > Use a projected service account token. # Use Workload Identity with the Terraform Provider Source: https://docs.dodopayments.com/developer-resources/workload-identity/terraform Configure the Dodo Payments Terraform provider with a workload_identity block, so that plan and apply runs need no stored API key. The [Dodo Payments Terraform provider](/developer-resources/terraform-provider) accepts a `workload_identity` block in place of `api_key`. The provider gets a JWT from the platform that runs Terraform, exchanges it, and uses the Dodo token for the run. > [!NOTE] > > The `workload_identity` block is available from provider version 0.3.0. ## Provider Configuration ```hcl theme={null} provider "dodopayments" { environment = "live_mode" workload_identity { identity_provider_id = "wip_..." token_source = "terraform_cloud" } } ``` `workload_identity` is a block, not an attribute. Do not write `workload_identity = { ... }`. | Attribute | Description | | - | - | | `identity_provider_id` | The identity provider id. If you do not set it, the provider reads `DODO_PAYMENTS_IDENTITY_PROVIDER_ID`. | | `token_source` | Where the provider gets the JWT. The default value is `auto`. Refer to [Token Sources](#token-sources). | | `token_file` | The path of the JWT file. Use it with `token_source = "file"`. | | `audience` | The audience of the JWT for the `github_actions` and `gcp` token sources. The default value is the origin of the API base URL. | > [!WARNING] > > Do not set `api_key` and `workload_identity` together. The provider gives an error when you set the two. If you set neither, the provider reads `DODO_PAYMENTS_API_KEY`. If `DODO_PAYMENTS_API_KEY` is not set and `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` is set, the provider uses workload identity with the `auto` token source. ## Token Sources | `token_source` | How the provider gets the JWT | | - | - | | `auto` | Finds the platform from the environment. This is the default value. | | `github_actions` | Requests a token from the GitHub OIDC endpoint (`ACTIONS_ID_TOKEN_REQUEST_URL`). A long apply can get a new token. | | `gitlab` | Reads the ID token of the GitLab job. | | `terraform_cloud` | Reads `TFC_WORKLOAD_IDENTITY_TOKEN`. The provider does one exchange at the start of the plan or apply phase. | | `gcp` | Requests an identity token from the Google Cloud metadata server. | | `vercel` | Reads the Vercel OIDC token. | | `kubernetes` | Reads the projected service account token. | | `file` | Reads the file in `token_file`. | ## HCP Terraform **1. Create the provider and the mappings** In the dashboard, create a `terraform_cloud` provider. Then add mappings that pin `terraform_organization_id` and `terraform_workspace_id`. Refer to [Terraform Cloud](/developer-resources/workload-identity/providers/terraform-cloud). **2. Set the workspace variables** In the HCP Terraform workspace, add these environment variables: | Variable | Value | | - | - | | `TFC_WORKLOAD_IDENTITY_AUDIENCE` | `https://live.dodopayments.com` (or `https://test.dodopayments.com`) | | `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` | `wip_...` | **3. Configure the provider** Set `token_source = "terraform_cloud"` in the `workload_identity` block. Remove `DODO_PAYMENTS_API_KEY` from the workspace. ### Split Plan and Apply HCP Terraform adds the `terraform_run_phase` claim (`plan` or `apply`) to the JWT. Use it to give the plan phase read access only: | Mapping | Conditions | Scopes | | - | - | - | | Plan | `terraform_organization_id`, `terraform_workspace_id`, `terraform_run_phase = plan` | Read scopes | | Apply | `terraform_organization_id`, `terraform_workspace_id`, `terraform_run_phase = apply` | Read and write scopes | Each JWT matches one mapping only, because the two mappings have different `terraform_run_phase` values. A `terraform_cloud` Dodo token lives until the end of the run phase, with a maximum of 24 hours. Pin `terraform_run_phase` to keep write access in the apply phase only. ## GitHub Actions Give the job the `id-token: write` permission. The provider requests the JWT. If you do not add a `workload_identity` block and `DODO_PAYMENTS_API_KEY` is not set, the `auto` token source finds GitHub Actions. ```yaml expandable theme={null} jobs: apply: runs-on: ubuntu-latest permissions: id-token: write contents: read env: DODO_PAYMENTS_IDENTITY_PROVIDER_ID: wip_... steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 - run: terraform init - run: terraform apply -auto-approve ``` ```hcl theme={null} provider "dodopayments" { environment = "live_mode" workload_identity { token_source = "github_actions" } } ``` ## Environment Variables | Variable | Use | | - | - | | `DODO_PAYMENTS_IDENTITY_PROVIDER_ID` | The identity provider id, when the block does not set `identity_provider_id`. | | `TFC_WORKLOAD_IDENTITY_AUDIENCE` | HCP Terraform workspace variable. Set it to the Dodo Payments audience. | | `TFC_WORKLOAD_IDENTITY_TOKEN` | Set by HCP Terraform. The `terraform_cloud` source reads it. | > [card] [Terraform Provider](/developer-resources/terraform-provider) > > Manage your catalog as code. > [card] [Terraform Cloud Guide](/developer-resources/workload-identity/providers/terraform-cloud) > > Provider and mapping setup for HCP Terraform. # Atlas Demo Product Source: https://docs.dodopayments.com/features/atlas-demo-website Explore Atlas, an open-source AI art generation demo that runs prepaid credits, credit-based plans, subscriptions, and one-time purchases on Dodo Payments checkout. ![Atlas Demo Product - AI art generation platform with integrated billing](https://mintcdn.com/dodopayments/kx9B5HGzBgLxFWey/images/atlas/atlas-demo-product.png?fit=max\&auto=format\&n=kx9B5HGzBgLxFWey\&q=85\&s=df07b04779a208c9e7a6a81e19c97f58) Atlas is a working demo application by Dodo Payments: an AI art generation platform where every purchase flow runs on Dodo Payments checkout in test mode. It shows **credit-based billing**, **subscriptions**, and **one-time payments** from plan selection to the post-purchase dashboard. > [!NOTE] > > **Live Demo**: Visit [atlas.dodopayments.com](https://atlas.dodopayments.com/) to explore the platform and test every billing flow. ## Overview Atlas simulates an AI art generation platform where users create images from text prompts. Its **Pricing** page offers four plans, each a different billing model: * **Starter Credits** (prepaid credits): \$10 for 10 credits that never expire. * **Credit Pack** (credit-based subscription): \$10 per month for 25 credits per month, with 50% credit rollover and low-balance alerts. * **Unlimited Pro** (subscription): \$20 per month for unlimited image generation. * **Special Downloads** (one-time purchase): \$12 for a pack of 12 artworks. Yearly billing lowers the Credit Pack to \$8 per month and Unlimited Pro to \$16 per month. A **Checkout Mode** selector on the Pricing page opens checkout as a redirect, an overlay, or inline on the page. After a purchase, signed-in users land on the **Atlas Studio dashboard**, where they generate artwork and track their credits or plan status. ## Purchase Flows The three flows follow the same pattern. Each one uses a different billing model and product type. > [tab] Credit-Based Billing > > **1. Select the Credit Pack** > > On the **Pricing** page, click **Buy credits** on the **Credit Pack** plan (\$10 per month for 25 credits). Each image a customer generates uses credits from a monthly allowance, and unused credits partly roll over. > > **2. Sign In or Continue as a Guest** > > Atlas asks whether to sign in, which saves the purchase to an account, or to continue as a guest. > > **3. Complete Checkout** > > The checkout process includes: > > * **Branded checkout page**: The Dodo Payments checkout page shows the merchant's brand name and logo. > > * **Customer information**: The customer enters their details and billing address. > > * **Tax calculation**: Tax is calculated after the customer confirms their address. > > * **Payment**: The customer enters test card details to complete the transaction. > > > [!TIP] > > > > Use test card `4242 4242 4242 4242` with expiry `06/32` and CVV `123` to simulate a successful payment. See [Testing Process](/miscellaneous/testing-process) for more test cards. > > **4. View Confirmation** > > After the payment succeeds, Atlas confirms the purchase. A signed-in user goes to the dashboard. A guest sees a payment summary with the plan and payment status. > > **5. Access Dashboard** > > Signed-in users land on the **Atlas Studio dashboard**, which shows the credits left this month and deducts credits as they generate artwork. > [tab] Subscription > > **1. Select Subscription Plan** > > On the **Pricing** page, click **Get started** on the **Unlimited Pro** plan (\$20 per month) for unlimited AI art generation. > > **2. Sign In or Continue as a Guest** > > Atlas asks whether to sign in, which saves the purchase to an account, or to continue as a guest. > > **3. Complete Checkout** > > The subscription checkout includes: > > * **Branded checkout page**: Merchant branding appears throughout checkout. > > * **Customer information**: The customer enters their details and billing address. > > * **Tax calculation**: Tax is calculated from the billing address. > > * **Payment**: The customer enters test card details to start the subscription. > > > [!NOTE] > > > > The subscription renews automatically at the end of each billing period, monthly or yearly. > > **4. View Confirmation** > > After the payment succeeds, Atlas confirms the subscription. A guest sees a payment summary with the plan and payment status. > > **5. Access Dashboard** > > Signed-in users land on the **Atlas Studio dashboard** with unlimited image generation. > [tab] One-Time Purchase > > **1. Select a One-Time Plan** > > On the **Pricing** page, choose **Starter Credits** (\$10 for 10 credits that never expire) and click **Buy credits**, or choose **Special Downloads** (\$12 for 12 artworks) and click **Get Art Pack**. Each is a single payment with no renewal. > > **2. Sign In or Continue as a Guest** > > Atlas asks whether to sign in, which saves the purchase to an account, or to continue as a guest. > > **3. Complete Checkout** > > The one-time purchase checkout includes: > > * **Branded checkout page**: Dodo Payments checkout with the merchant's branding. > * **Customer information**: The customer enters their details and billing address. > * **Tax calculation**: Tax is calculated after the customer confirms their address. > * **Payment**: The customer enters test card details to complete the purchase. > > **4. View Confirmation** > > After the payment succeeds, Atlas confirms the purchase. A guest sees a payment summary with the plan and payment status. > > **5. Access Dashboard** > > Signed-in users land on the **Atlas Studio dashboard**. Starter Credits are available to generate artwork as soon as the payment succeeds. ## Post-Purchase Dashboard Experience The Atlas Studio dashboard shows how to build billing-aware features after checkout: it reads what the customer bought and unlocks the matching access. ### Dashboard Features * **Immediate access**: Users start generating artwork right after the purchase. * **Usage tracking**: The dashboard shows the credits left on credit plans, or unlimited status on Unlimited Pro, next to the images the user generated. * **Plan status**: The dashboard names the active plan, such as **Unlimited Pro (Subscription)** or **Credit Pack (Credit-Based)**. * **Return to your app**: The flow shows how to send customers back to your application after checkout and grant the access they paid for. > [!TIP] > > The dashboard follows good practice for post-purchase flows: it verifies the purchase before it grants access, and it shows usage in the app. ## Technical Implementation Atlas is a Next.js application. Its route handlers call the Dodo Payments API directly, for example `POST /checkouts` to create a checkout session, and the `dodopayments-checkout` package opens checkout as an overlay or inline on the page. To build the same flows with a typed client, use the [Dodo Payments TypeScript SDK](/developer-resources/sdks/typescript). > [card] [Integration Guide](/developer-resources/integration-guide) > > Integrate Dodo Payments checkout flows into your application. > [card] [TypeScript SDK](/developer-resources/sdks/typescript) > > TypeScript SDK documentation and API reference. ## Open Source Atlas is open source. Read the code to see how each billing flow is implemented in a real application. > [card] [View on GitHub](https://github.com/dodopayments/dodo-checkout-demo.git) > > Browse the Atlas source code. # Bypassing App Store & Play Store Fees Using Dodo Payments Source: https://docs.dodopayments.com/features/bypassing-app-store-fees Where Apple and Google let apps sell digital goods outside in-app purchase, what each option costs, and how Dodo Payments handles web checkout as Merchant of Record. ## The Platform Tollbooth Problem Apple and Google have long required apps that sell digital goods to take payment through the store's own billing system: Apple In-App Purchase (IAP) on iOS and Google Play Billing on Android. Both stores charge a commission of up to 30% on those sales. Large app developers such as Spotify, Epic Games, and Netflix criticized this commission as excessive and anti-competitive. Apple's anti-steering rules also stopped apps from telling users that a cheaper option existed outside the app, so the stores controlled both distribution and payment for digital goods. > [!WARNING] > > A 30% commission takes a large share of revenue from digital businesses, especially subscription and SaaS apps that pay it on every renewal. ## The Epic Games Catalyst Epic Games, led by CEO Tim Sweeney, ran a legal and public campaign called Project Liberty to challenge the app store commissions of Apple and Google. The goal was to open app distribution and payments to developers. On August 13, 2020, Epic updated Fortnite with a direct payment option that bypassed Apple IAP. Apple removed Fortnite from the App Store the same day, and Epic filed a lawsuit against Apple that day. The Epic Games v. Apple case started a global debate about app store rules. ## The Epic v. Apple Verdict On September 10, 2021, a U.S. District Court judge ruled: * **Apple was not found to be a monopolist under federal antitrust law**, so it kept control of app distribution on iOS. * **Apple's anti-steering rules violated California's Unfair Competition Law.** The court issued a permanent injunction: Apple must let developers add buttons and links that direct users to other ways to pay. The injunction took effect in January 2024. After further appeals and a 2025 contempt ruling, Apple updated its App Store Review Guidelines in May 2025 to allow external purchase links in apps on the U.S. storefront. > [!TIP] > > The U.S. ruling added to regulatory pressure and legal action in South Korea, Japan, the EU, and other regions. Together with the EU's Digital Markets Act (DMA), these changes gave developers more ways to take payments outside the app stores. ## Global Overview: Where Developers Can Legally Bypass Fees The table shows what each store allows by region. Rules change often, so check the store's current terms before you launch. | Region | Apple Policy | Google Policy | | - | - | - | | **USA** | External links allowed (no Apple commission set)² | Alternative billing and external links allowed (service fees apply)³ | | **EU (EEA)** | Alt payments/links allowed (link out: flat 15%; in-app alt payments: 20%; 10% for eligible programs)¹ | UCB allowed for apps and games | | **South Korea** | Apple-approved PSPs (26% fee) | Alternative billing required by law (4% fee reduction: 26% or 11%) | | **Netherlands** | EU terms apply; separate program for dating apps | UCB allowed | | **Japan** | Alt payments and links allowed under the MSCA⁴ | UCB allowed for apps and games | | **India** | No change | UCB allowed (4% fee reduction) | | **Other** | No change | UCB allowed in select countries | | **China** | No external billing allowed | Google Play not relevant | > [!NOTE] > > UCB stands for User Choice Billing, Google's alternative billing system that allows developers to use third-party payment processors. > [!NOTE] > > **¹ EU update (effective October 1, 2026):** Following [Apple's August 18, 2026 announcement](https://www.apple.com/newsroom/2026/08/apple-announces-changes-for-apps-in-the-european-union/), Apple replaced the previous stacked EU commission model (which produced an effective 10–17% cut) with unified business terms. Apps that **link out** to complete purchases now pay a flat **15%** commission (**10%** for developers in the App Store Small Business Program, Mini Apps Partner Program, or Video Partner Program). Apps using **in-app alternative payment processing** pay **20%** (**10%** for those same programs). The Core Technology Fee is replaced by a **5%** Core Technology Commission for apps distributed outside the App Store. > > **² United States:** App Store Review Guideline 3.1.1(a) lets apps on the U.S. storefront include buttons and links to other purchase methods without an entitlement. In December 2025, the Ninth Circuit allowed Apple to seek a commission on linked-out purchases limited to its genuine costs, and the district court has not set that rate. > > **³ Google Play in the United States:** Since October 29, 2025, Google Play has allowed U.S. apps to use other billing systems and to link to purchases outside the app. Google charges service fees on these transactions starting October 1, 2026. > > **⁴ Japan:** Under the Mobile Software Competition Act (MSCA), in force since December 18, 2025, [Apple allows iOS apps in Japan](https://www.apple.com/newsroom/2025/12/apple-announces-changes-to-ios-in-japan/) to use alternative in-app payment processing and to link out to web purchases, and Google Play opened User Choice Billing to games. ## Pre-2025 Loopholes: How Apps Circumvented App Store Rules Before the rules changed, some apps found workarounds to avoid the 30% commission. Most of these workarounds were risky and not fully compliant with store rules. ### Reader App Loophole Under the reader app rule, apps such as Kindle and Netflix let users access content they had already bought elsewhere. Apple allows apps to give access to previously purchased content. As long as the app didn't link to an external payment page or offer an in-app purchase, it was allowed on the App Store. ### Hidden Payment Redirections Other apps hid payment redirections in their code. Some sent emails after download that asked users to pay outside the app. > [!NOTE] > > Spotify took the web-payment approach. If you use Spotify on iOS in India, you can't buy the Premium plan inside the app. You pay on the web instead. These methods were risky and fragile, and the stores usually removed the apps once they found them. They showed that developers wanted control over their margins and their customer data. ## The Payment Gateway Trap: What Developers Often Miss A payment gateway (PG) such as Stripe or Razorpay looks like the obvious alternative. For in-app purchases, it isn't enough. > [!WARNING] > > On iOS, outside the regions where Apple allows other payment methods (for example, India or China), adding a PG directly to your app violates Apple's policies and risks removal from the App Store. Where a PG is allowed, it still leaves work with you: tax compliance in each country, invoicing, refund management, and regulatory filings. A Merchant of Record (MoR) such as Dodo Payments covers that work. As the legal seller, Dodo Payments handles payments, tax, invoicing, refunds, disputes, and billing support. You collect payment globally without putting your App Store listing at risk. ## Two Legal Workarounds for Developers ### 1. App-to-Web Redirect (Link Out Flow) **What it is:** The app sends users to a web checkout, hosted by Dodo Payments or by you. The customer pays outside the app, and the app then grants access. **Legal Status:** * **iOS:** Allowed on the U.S., EU (including the Netherlands), and Japan storefronts. Reader apps in any storefront can link to account management with Apple's External Link Account Entitlement. * **Android:** Allowed in markets where Google permits alternative billing or external links **Advantages:** * Short integration: the app opens a checkout URL * Follows store rules in the regions listed * No card data passes through your app, which keeps PCI scope out of the app **Drawbacks:** * Slight friction: the user leaves the app to pay ### 2. In-App SDK Integration (Third-Party SDK) **What it is:** A third-party payment UI, such as a native SDK, runs inside your app so users pay without leaving it. **Legal Status:** * **iOS:** Allowed in the EU (under DMA terms), in Japan (under the MSCA), and in South Korea (through an Apple-approved Korean PSP, in a native flow, in a separate Korea-only binary). Elsewhere, it violates Apple's rules. Dodo Payments checkout is a web flow, so it doesn't qualify for the South Korea program. * **Android:** Allowed in UCB markets when you follow Google's UX and reporting requirements **Advantages:** * Smooth checkout * The user stays in the app * Can match the IAP experience **Drawbacks:** * More integration work * Compliance risk outside allowed regions ## Developer Strategy: Combine Legal Compliance with Revenue Efficiency A global rollout can follow this plan: **1. U.S. Users** Use App-to-Web. Apple doesn't charge a commission on U.S. link-outs while the court sets a rate. **2. EU Users** Use In-App SDK or App-to-Web. Under Apple's unified EU terms (effective October 1, 2026), App-to-Web link-outs incur a flat 15% Apple commission, while in-app alternative payments incur 20% (both drop to 10% for eligible small-business/partner programs). **3. Android Users in UCB Markets** Use In-App SDK with a checkout that follows Google's UX rules. **4. Other iOS Markets** Use Apple IAP, or don't sell digital goods in the app. **5. Other Android Markets** Use Google Play Billing, or distribute through alternative app stores. ## The Biggest Opportunity The U.S. App Store is the largest single opportunity. Since the May 2025 guideline update that followed Epic v. Apple, apps on the U.S. storefront can include external links to a web checkout. For U.S. customers, this means **no required Apple IAP, no 30% commission today, and direct control of the customer relationship and revenue.** The U.S. is the largest app market by consumer spending, so this change can raise margins for subscriptions, SaaS tools, media apps, and learning apps. For many businesses, it recovers up to 30% of revenue in their largest market. > [!TIP] > > The U.S. market is the largest opportunity for revenue recovery. With compliant external payment links, developers avoid the 30% Apple commission on those purchases. ## How Dodo Payments Enables This As your Merchant of Record, Dodo Payments handles: * **Global tax compliance** (VAT/GST) * **Payment processing** (cards, UPI, wallets) * **Invoicing, refunds, fraud prevention** * **SDK & hosted checkout integration** You get fewer compliance and operations tasks, and lower fees where the store rules allow payment outside the app. > [card] [Get Started](/introduction) > > Begin your integration with Dodo Payments > [card] [Mobile Integration](/developer-resources/mobile-integration) > > Learn how to integrate payments in your mobile app ## Conclusion: A Developer-Friendly Future Is Here For years, developers had to accept the 30% store commission or leave the store. After Epic v. Apple, new regulation, and public pressure, the stores can no longer enforce that model everywhere. Developers can now choose how they take payment in many regions. With compliant App-to-Web flows or SDK integrations and a Merchant of Record such as Dodo Payments, you keep more revenue and more control while following the rules. The app stores didn't open these options by choice, but the options exist now in many regions. > [!TIP] > > In the regions covered above, you can take payment outside the app store and pay a lower commission, or none, while you stay compliant. # Feature Request and Roadmap Source: https://docs.dodopayments.com/features/feature-request Submit feature requests, vote on ideas from other merchants, and follow the Dodo Payments public roadmap on the feedback portal. Submit feature requests, vote on ideas from other merchants, and track what Dodo Payments is building on the [feedback portal](https://feedback.dodopayments.com/). The portal hosts the public roadmap and a **Bug Reports** board for reporting issues. To open it from the dashboard, select the support icon in the dashboard header, then select **Feature Requests**. > [card] [Visit Our Public Roadmap](https://feedback.dodopayments.com/) > > View all feature requests, vote on ideas, and track the product roadmap on the feedback portal. ## **Request a New Feature** To suggest a feature that would improve your experience with Dodo Payments, submit a feature request on the feedback portal. ![Dodo Payments feedback portal with the list of feature requests, sort options, and the button for creating a new post](https://mintcdn.com/dodopayments/Mb_I33HpIv4r5G-9/images/feature-request/Feature.png?fit=max\&auto=format\&n=Mb_I33HpIv4r5G-9\&q=85\&s=a9aa693881a2c59368f05a07b233583b) To submit a request: 1. Go to the [feedback portal](https://feedback.dodopayments.com/). 2. Select the **What's your idea?** field at the top of the board and enter a short title for your idea. 3. In **Add more details...**, explain what the feature does, why it matters, and how it helps your business. 4. Select **Submit**. Other merchants can then find it and vote for it. To make your request easier to evaluate: * Keep it clear and concise. * Describe the business impact of the feature. * Add examples where they help. * Include use cases that show the value. ## **Vote for Existing Feature Requests** Dodo Payments prioritizes the features that benefit the most merchants. Before you post a new idea, browse the existing requests and vote for the ones you find valuable: 1. Go to the [feedback portal](https://feedback.dodopayments.com/). 2. Browse the submitted requests, or sort them by **Trending**, **Top**, or **New**. 3. Select the upvote button next to each request you support. Voting helps you: * Influence the development priority of the features you care about. * Show the team which features have widespread demand. * Get notified when a feature you voted for changes status, including when it's released. ## **View the Product Roadmap** The public roadmap shows the development status of each feature. Features appear in these status columns: * **Planned**: Features that are approved and scheduled for development. * **In Progress**: Features the team is working on. * **Complete**: Features that are implemented and live. * **Closed**: Requests the team closed without marking them complete. To view the roadmap: 1. Go to the [feedback portal](https://feedback.dodopayments.com/). 2. Open the **Roadmap** tab to see features by status. 3. Browse the feature categories and their statuses. 4. Use **Search** and **Filter** to find specific features, or narrow the list by status or category. > [!TIP] > > Bookmark the [feedback portal](https://feedback.dodopayments.com/) to follow new features and vote on the ideas that matter to you. # Mobile & Desktop Apps Source: https://docs.dodopayments.com/features/mobile-app Run your Dodo Payments business from the iOS, Android, macOS, Windows, and Linux apps, with the full dashboard, push notifications, and home screen analytics widgets on mobile. ## Introduction [Mobile App | Dodo Payments](https://www.youtube.com/embed/EWhkIUf36_Y) The **Dodo Payments apps** put the Dodo Payments dashboard on your phone and your desktop. You can track payments, subscriptions, customers, and payouts from wherever you work, with the same account you use on the web. The mobile apps run on iOS and Android. The desktop apps run on macOS, Windows, and Linux. ## Key Features > [card] Real-time Notifications > > Get push notifications on your phone for payments, payouts, refunds, subscriptions, and disputes. > [card] Dashboard Anywhere > > View revenue, transaction history, customer statistics, and performance charts on mobile or desktop. > [card] Subscription Management > > Monitor active subscriptions and open each customer's details. > [card] Product Management > > Create and manage products from your phone or desktop. > [card] [Home Screen Widgets](#home-screen-analytics-widgets) > > See revenue, subscriptions, customers, and other analytics on your iOS or Android home screen. ## Parity with the Web Dashboard Every feature of the web dashboard is available in the mobile and desktop apps, including: * The **Live Mode** switch between test mode and live mode * Verification progress and document submission * Developer settings, including API keys * Pricing and discount configuration ## Home Screen Analytics Widgets The mobile apps include native analytics widgets for the iOS and Android home screen. Each widget shows one metric from your dashboard analytics, with the change against the previous period and a trend chart. ![Dodo Payments analytics widgets showing Gross Volume, MRR, Active Customers, Payment Success Rate, Recovery Overview, and Net Revenue Retention](https://mintcdn.com/dodopayments/G6L1zm0K36thlk0x/images/mobile-app/analytics-widgets.png?fit=max\&auto=format\&n=G6L1zm0K36thlk0x\&q=85\&s=f09e7625d41ca373f7b623ef0cb613c8) ### Available Widgets There are six widgets, one for each analytics category. Each widget instance shows the metric and time range you choose for it. | Widget | Metrics | | - | - | | **Revenue Analytics** | Gross Volume, Net Volume, Average Order Value, Payments Count, Payouts Received, Refunds, Disputes, Revenue by Country, Revenue by Product, Payments Breakdown | | **Subscriptions Analytics** | MRR, Active Subscriptions, New MRR, Expansion MRR, Contraction MRR, Churned MRR, Net New MRR, MRR Overview, Projected ARR | | **Customers Analytics** | Active Customers, New Customers, New vs Returning, ARPU, LTV | | **Retention Analytics** | Net Revenue Retention, Gross Revenue Retention, Revenue Churn Rate, Customer Churn Rate, Revenue Metrics, Cohort Retention, Trial Conversion | | **Recovery Analytics** | Recovery Overview, Retries, Dunning, Abandoned Cart, Recovery by Flow | | **Success Rate Analytics** | Payment Success Rate, Refund Success Rate, Checkouts, Payment Outcomes, Success Rate by Method, Failure Reasons | The time range can be **Today**, **Last 7 days**, **Last 4 weeks**, **Month to date**, **Quarter to date**, or **All time**. The change shown on the widget compares the selected range with the period before it. **All time** has no previous period, so it shows no change. ### Add a Widget Sign in to the Dodo Payments app before you add a widget. The widgets use the business and mode (test or live) that are active in the app. > [tab] iOS > > The widgets require iOS 17 or later and come in small, medium, and large sizes. > > **1. Open the widget gallery** > > Touch and hold an empty area of the home screen, then tap **Edit** → **Add Widget**. > > **2. Choose a Dodo Payments widget** > > Search for **Dodo Payments**, select a widget such as **Revenue Analytics**, choose a size, and tap **Add Widget**. > > **3. Pick a metric and time range** > > Touch and hold the widget, tap **Edit Widget**, then choose the metric and time range. > [tab] Android > > The widgets can be resized horizontally and vertically on the home screen. > > **1. Open the widget list** > > Touch and hold an empty area of the home screen, then tap **Widgets**. > > **2. Choose a Dodo Payments widget** > > Find **Dodo Payments**, then drag a widget such as **Revenue Analytics** onto the home screen. > > **3. Pick a metric and time range** > > On the configuration screen that opens, choose the metric and time range, then save. To change them later, touch and hold the widget and open its settings. > [!TIP] > > Add the same widget more than once to track several metrics. For example, add two **Revenue Analytics** widgets to show **Gross Volume** and **Refunds** side by side. ### Updates and Behavior * Widgets refresh about every 30 minutes. The operating system decides the exact schedule. * Widgets follow the light and dark appearance of your device. On iOS 18 and later, they also support the tinted home screen style. * Tapping a widget opens the matching tab of **Analytics** in the app. For every time range except **Last 4 weeks**, the page opens on the same time range and compares it with the previous period. For **Last 4 weeks**, the page opens on the time range you last used. * When a widget cannot reach Dodo Payments, it shows the last data it loaded and marks it as not current. > [!NOTE] > > If a widget asks you to reconnect, open the Dodo Payments app. This happens when the widget's access expires or is revoked, for example after you switch business on another device or lose access to a business. When the dashboard loads in the app, it gives the widgets new access and they update. ## Download Now ### Mobile Download the mobile app for your phone, and pair it with the desktop app on your computer. > [card] [iOS](https://apps.apple.com/in/app/dodo-payments/id6743651329) > > Download from the Apple App Store > [card] [Android](https://play.google.com/store/apps/details?id=com.dodopayments.app) > > Download from Google Play ### Desktop The desktop app has native installers for macOS, Windows, and Linux. > [card] [macOS](https://dodopayments.com/downloads) > > Apple Silicon and Intel builds > [card] [Windows](https://dodopayments.com/downloads) > > Setup installer and MSI > [card] [Linux](https://dodopayments.com/downloads) > > AppImage, .deb, and .rpm > [!TIP] > > Download the latest version of each app from [dodopayments.com/downloads](https://dodopayments.com/downloads), which links to the installer for every platform. # Introduction Source: https://docs.dodopayments.com/features/mor-introduction Dodo Payments is your Merchant of Record: the legal seller that calculates, collects, and remits sales tax and handles payments and compliance for you. Dodo Payments operates as your **Merchant of Record (MoR)**. We are the legal seller of your digital products, so we take responsibility for payment processing, sales tax, and compliance while you build and sell your product. > [card] 220+ Regions > > Accept payments from 220+ countries and regions > [card] 40+ Payment Methods > > Cards, wallets, and local methods > [card] No Sales Tax Filing > > We file and remit sales taxes ## What Is a Merchant of Record? A **Merchant of Record** is the legal entity that sells to your customer, appears on the customer's card statement, and is responsible for the transaction. When Dodo Payments is your MoR: * **We are the legal seller.** Dodo Payments appears on bank statements and receipts. * **You are the product creator.** You build, price, and deliver your product. * **We run the back office.** We handle sales tax, compliance, billing, and the dispute process with card networks. * **You receive net payouts.** Your revenue, after tax and fees, is paid to your bank account. ```mermaid theme={null} flowchart LR A[Customer] -->|Pays| B[Dodo Payments] B -->|Tax| C[Tax Authority] B -->|Payout| D[You] ``` > [!NOTE] > > A Merchant of Record works like an outsourced global finance team: it issues invoices, collects and files sales taxes, and runs billing for every sale. ## Why Use a Merchant of Record? Selling digital products worldwide means following VAT rules in Europe, GST in Australia, sales tax in the US, and requirements in many other jurisdictions. Each jurisdiction has its own rules, rates, thresholds, and filing deadlines. | Your Responsibility | Without MoR | With Dodo as MoR | | - | :-: | :-: | | VAT/GST Registration | You | Dodo | | Tax Calculation | You | Dodo | | Tax Filing & Remittance | You | Dodo | | Chargeback Liability | You | You, with Dodo's dispute tools | | PCI Compliance | You | Dodo | | Multi-Currency Support | Complex | Built-in | | Local Payment Methods | Integrate Each | 40+ Included | > [!TIP] > > **Example**: You sell a €50/month subscription to a customer in France. > > **Without MoR**: You register for French VAT, charge €60 (€50 plus 20% VAT), file French VAT returns, and answer French tax audits. > > **With Dodo**: We collect €60, remit €10 VAT to France, and pay you €50 minus fees. ## PSP vs. MoR: Key Differences A **Payment Service Provider** (such as Stripe) and a **Merchant of Record** both process payments. They differ in who is the legal seller. ### Payment Service Provider (PSP) A PSP processes transactions, and you remain the legal seller: ```mermaid theme={null} flowchart LR A[Customer] --> B[Your Site] B --> C[PSP] C --> D[Your Bank] D -.->|You Handle| E[Taxes] D -.->|You Handle| F[Disputes] D -.->|You Handle| G[Compliance] ``` > [!WARNING] > > With a PSP, **you** are responsible for tax registration, collection, filing, and remittance in every jurisdiction where you have customers. ### Merchant of Record (Dodo) An MoR becomes the legal seller and handles tax and compliance end to end: ```mermaid theme={null} flowchart LR A[Customer] --> B[Dodo Checkout] B --> C[Dodo Payments] C --> D[Your Wallet] C -.->|Handled| E[Taxes] C -.->|Dispute Tools| F[Disputes] C -.->|Handled| G[Compliance] ``` > [!TIP] > > With Dodo as your MoR, we handle sales tax and compliance, and give you tools to prevent and respond to disputes. You receive net payouts without filing sales tax returns. ### Side-by-Side Comparison | Aspect | PSP (Stripe, etc.) | MoR (Dodo) | | - | :-: | :-: | | Legal Seller | Your Company | Dodo | | On Customer Statement | Your Name | Dodo (with your brand name) | | Tax Registration | You | Dodo | | Tax Calculation | You | Dodo | | Tax Remittance | You | Dodo | | Chargeback Risk | You | You, with Dodo's dispute tools | | PCI Compliance | You | Dodo | | Setup for Global | Complex | Simple | > [!NOTE] > > **Important**: Both PSPs and MoRs process payments. The key difference is **who is legally responsible** for tax compliance on each sale. > [!NOTE] > > Chargebacks stay your responsibility with an MoR. When a dispute opens, the disputed amount and a dispute fee are deducted from your balance, and you accept or challenge the dispute from your dashboard. Dodo Payments provides Visa RDR, Ethoca alerts, and deflections to prevent disputes. See [Disputes](/features/transactions/disputes). ## How Tax Compliance Works Dodo handles the tax lifecycle for every sale: **1. Customer Location** We use the customer's country and postal code to determine which tax rules apply, such as VAT, GST, or sales tax. **2. Rate Calculation** The tax rate depends on the product's tax category, the customer's location, and whether the customer is a business. For example, EU business customers with a valid VAT number get reverse charge applied. **3. Collection at Checkout** Checkout shows the tax and collects it with the payment, so customers see exactly what they pay. **4. Filing & Remittance** We file returns and pay the collected taxes to the relevant authorities. You do not file sales tax returns for these sales. ## Revenue Flow This example follows a \$200 sale to a customer outside the US with 15% VAT: ```mermaid theme={null} flowchart LR A[Customer
Pays $230] -->|incl. $30 tax| B[Dodo Payments] B -->|$30| C[Tax Authority] B -->|$186.95| D[You] ``` ### Example Payout Breakdown | Line Item | Amount | | - | -: | | Customer Payment (incl. tax) | \$230.00 | | Sales Tax (15% VAT) | −\$30.00 | | Dodo Transaction Fee (4% of \$230) | −\$9.20 | | International Fee (1.5% of \$230) | −\$3.45 | | Fixed Fee per Transaction | −\$0.40 | | **Your Payout** | **\$186.95** | > [!NOTE] > > Transaction fees are calculated on the total amount including tax, using standard pricing. The international fee applies because the customer's card is issued outside the US. Subscription payments add 0.5%. A payout fee is deducted per payout, not per sale. See the [pricing page](https://dodopayments.com/pricing) and [Payouts Process](/features/payouts/payout-structure). ## When to Choose MoR vs. PSP > [tab] Choose Dodo (MoR) > > **Dodo Payments suits you if you:** > > * Sell digital products, SaaS, or subscriptions > * Have customers in multiple countries > * Want to avoid registering for sales tax in each country > * Prefer outsourced, predictable tax compliance > * Value speed to market over full control > * Want fraud screening and dispute prevention built in > [tab] Consider a PSP > > **A PSP might suit you if you:** > > * Operate mainly in one country > * Have in-house finance and compliance teams > * Need full control over checkout UX > * Work with very thin margins > * Sell physical goods (MoRs focus on digital products) > [!NOTE] > > Many businesses start with a PSP and move to an MoR as they grow internationally. Dodo Payments offers migration support for this move. See [Migrate to Dodo Payments](/migrate-to-dodo). ## Frequently Asked Questions > [accordion] What appears on my customer's credit card statement? > > Dodo Payments appears as the merchant. By default, the statement descriptor is `DODOPAY_` followed by up to 14 letters of your business name, for 22 characters in total. You can customize it in your business profile. Customers also receive receipts that show your product information. > [accordion] Do I still own the customer relationship? > > Yes. You control pricing, branding, product delivery, and direct communication. Dodo handles billing, and your brand appears in checkout, emails, and invoices, so customers know they are buying from you. > [accordion] How does B2B VAT reverse charge work? > > Business customers can enter their tax ID, such as an EU VAT number, at checkout. We validate it, and where reverse charge applies, no tax is collected: the buyer accounts for the VAT in their own return. > [accordion] Can I use my own payment processor? > > Yes. With [Bring Your Own Processor (BYOP)](/features/byop) you can connect your own Stripe or Adyen account and route payments from selected countries through it, while Dodo Payments continues to power products, subscriptions, invoicing, and analytics. Countries you do not explicitly route keep flowing through Dodo Payments as your full-service Merchant of Record, so we remain responsible for tax on those routes. > [accordion] How do refunds work? > > Start refunds from your dashboard. The refund goes back to the customer's original payment method, and the ledger records it in the currency of the original payment. The tax on the refunded amount is reversed automatically. > [accordion] What about my income tax? > > Dodo handles **sales taxes** (VAT, GST, and sales tax) on customer transactions. You remain responsible for your business's income tax, corporate tax, and any tax obligations on the payouts you receive. > [accordion] Which countries can I sell to? > > We accept payments from 220+ countries and regions. See the full list: > > > [card] [Supported Regions](/miscellaneous/list-of-countries-we-accept-payments-from) > > > > View all 220+ countries and regions where we accept payments. ## Get Started > [card] [Create Account](https://app.dodopayments.com/signup) > > Sign up for free and start accepting global payments. > [card] [MoR vs PG Deep Dive](/features/mor-vs-pg) > > Detailed comparison with examples and use cases. > [card] [Acceptance Policy](/miscellaneous/merchant-acceptance) > > Learn which businesses we support. > [card] [Talk to Us](mailto:founders@dodopayments.com) > > Get personalized guidance from our team. # MoR vs PG Source: https://docs.dodopayments.com/features/mor-vs-pg Compare the Merchant of Record (MoR) and Payment Gateway (PG) models for selling globally, and see which tax and compliance tasks Dodo Payments takes on. ## Introduction Digital businesses and SaaS companies that sell globally choose between two models: a **Merchant of Record (MoR)** or a **Payment Gateway (PG)**. Dodo Payments operates as a Merchant of Record. This guide compares the two models so you can decide which one fits your business. ## The Core Difference | Feature | MoR (Dodo Payments) | Payment Gateway (Traditional PG) | | - | - | - | | Legal Seller | Dodo Payments (MoR) | Your Company | | Tax Collection & Remittance | Handled by Dodo | You are responsible | | Compliance & Regulatory Burden | Dodo handles tax and payment compliance | You handle local laws and chargebacks | | Settlement Currency | USD, EUR, or GBP | Depends on your merchant account | | Risk Management | Built-in fraud screening, plus Visa RDR, Ethoca alerts, and deflections to prevent chargebacks | You set up your own tools (e.g. Stripe Radar) | | Payouts | Aggregated payouts on a fixed schedule | Direct from PG to you, with bank setup | ## What It Means For You With **Dodo as your MoR**, we are the legal seller to your customers, so you can: * Sell in new countries without setting up local entities * Skip VAT, GST, and sales tax registration and filing * Offer more payment methods worldwide * Reduce your tax and regulatory exposure * Launch in new markets faster > [!NOTE] > > Suppose you sell a digital subscription to a customer in France. Dodo Payments collects the payment, charges and remits French VAT, and pays you the net revenue. You do not register for VAT or file returns in France. The MoR model also simplifies your back office. As your MoR, Dodo handles PCI compliance, fraud screening, currency conversion, and customer billing support, so your team can focus on product and growth. ## Visual Comparison **Revenue Flow: Payment Gateway** ```mermaid theme={null} flowchart LR A[Customer] --> B[Your Website] B --> C["Payment Gateway (e.g. Stripe)"] C --> D[Your Bank] D -.-> E["You handle: tax, support, refunds, fraud"] ``` **Revenue Flow: Merchant of Record (Dodo)** ```mermaid theme={null} flowchart LR A[Customer] --> B[Dodo Checkout] B --> C[Dodo Payments] C --> D[Your Wallet] C -.-> E["Dodo handles: Tax, Compliance, FX, Fraud, Invoicing"] ``` ## Why It Matters for SaaS & Digital Businesses As your business grows, taxes, compliance, and local payment preferences take more work. With a payment gateway, you are responsible for: * VAT/GST registration and filing in multiple jurisdictions * Currency conversion and chargebacks * Localized checkout and payment methods With Dodo Payments as your MoR: * You expand globally without setting up local entities * We calculate, collect, and remit taxes on your behalf * You offer payment methods suited to each customer's country * We act as the legal seller and run billing operations for you > [!TIP] > > A payment gateway moves the money. A Merchant of Record moves the money and also takes on the legal sale, tax, and billing work around it. ## Who Should Use MoR? Dodo Payments suits: * SaaS and digital product companies * Independent creators and solo founders * Businesses with customers in many countries * Companies that do not want to manage taxes and compliance in-house If you are expanding internationally, selling subscriptions, or want less operational work, an MoR is usually the better fit. ## When to Use a Payment Gateway Instead A payment gateway alone can make sense when: * Your business operates in only one country * You already have internal finance and compliance resources * You need complete control over the customer billing experience * You are highly cost-sensitive with thin margins at scale > [!NOTE] > > For many startups, a gateway is enough at first. As complexity grows, moving to an MoR can save time, reduce risk, and speed up international growth. ## Why Choose Dodo Payments Dodo Payments offers: * Payments, tax, and compliance in one platform * Multi-currency pricing and payouts in USD, EUR, or GBP * Access to 40+ payment methods * Seat-based billing, subscriptions, and one-time payments * Automated tax handling in 220+ countries * Built-in fraud prevention and PCI compliance Whether you are a solo founder or a growing SaaS team, Dodo Payments handles the tax and compliance work of selling globally. ## Learn More > [card] [Adaptive Currency Support](/features/adaptive-currency) > > Learn how Dodo shows prices in your customers' local currencies > [card] [Supported Payment Methods](/features/payment-methods) > > See the 40+ payment methods available through Dodo Payments ## Ready to Switch? Join the digital businesses that use Dodo Payments to sell globally. > [card] [Sign Up Free](https://app.dodopayments.com/signup) > > Create your Dodo Payments account and start selling globally > [card] [Talk to Sales](mailto:founders@dodopayments.com) > > Get personalized guidance from our team > [!TIP] > > Dodo Payments handles tax, compliance, and billing, so you can focus on building your product. # Figma Plugin Source: https://docs.dodopayments.com/integrations/figma-plugin Build a paid Figma plugin from an example that validates and activates Dodo Payments license keys before it unlocks your plugin's features. The Dodo Payments Figma example is a boilerplate plugin that unlocks its features only for users with a valid Dodo Payments [license key](/features/license-keys). Use it as the starting point for a premium Figma plugin: it includes a license key input, validation and activation against the Dodo Payments API, and a component for your premium features. ## Features * **License Key Validation**: Validates license keys against the Dodo Payments API. * **License Key Activation**: Activates license keys with an instance name, for keys that have an activation limit. * **Environment Support**: Configurable for both test mode and live mode. * **TypeScript Support**: Fully typed implementation with error handling. ## Getting Started Before you start, you need the Figma desktop app and a Dodo Payments product that issues license keys. **1. Create Base Plugin** Create your own Figma plugin project with [Figma's plugin quickstart guide](https://www.figma.com/plugin-docs/plugin-quickstart-guide/). Figma generates a scaffold with a `manifest.json` file. > [!TIP] > > You need this step only to get a unique name and ID for your plugin. After you copy the name and ID into the example's `manifest.json` in the next step and commit them to your Git repository, you can delete the generated files. **2. Clone the Example Implementation** Clone the [dodopayments-figma repository](https://github.com/dodopayments/dodopayments-figma): ```bash theme={null} git clone https://github.com/dodopayments/dodopayments-figma.git cd dodopayments-figma ``` In the cloned `manifest.json`, replace `name` and `id` with the values from your generated plugin's `manifest.json`. This example is your starting point for the integration. > [!TIP] > > Change the remote origin URL to your own repository for version control, for example with `git remote set-url origin `. **3. Install Dependencies** In the project root, run: ```bash theme={null} npm install ``` **4. Configure Environment** Set `API_MODE` in `src/ui/api.ts`: ```typescript theme={null} const API_MODE: "test_mode" | "live_mode" = "test_mode"; // for development // const API_MODE: "test_mode" | "live_mode" = "live_mode"; // for production ``` `API_MODE` selects the API host: `https://test.dodopayments.com` for `test_mode`, or `https://live.dodopayments.com` for `live_mode`. > [!WARNING] > > Use `test_mode` during development to avoid processing real payments. **5. Customize Components** Customize the plugin components in `src/ui/components/` to match your needs: * Update `Authenticated.tsx` to expose functionality for users with valid license keys. * Customize `LicenseKeyInput.tsx` to match your design. > [!NOTE] > > `Authenticated.tsx` is where you add your plugin's premium features. The plugin shows it only after a license key is validated or activated. ## Configuration **1. Configure Network Access** The example sends every license key request through a CORS proxy at `https://dodo-payments-proxy.aagarwal9782.workers.dev`, and its `manifest.json` allows network access only to that proxy. The proxy isn't available, so call the Dodo Payments API directly. The API accepts cross-origin requests from any origin, including the `null` origin of the plugin UI. In your `manifest.json`, replace the proxy domain with the Dodo Payments API hosts: ```json theme={null} { "networkAccess": { "allowedDomains": ["https://test.dodopayments.com", "https://live.dodopayments.com"] } } ``` In `src/ui/api.ts`, replace `fetch(proxyReq)` with `fetch(req)` in `validateLicenseKey` and `activateLicenseKey`, so each request goes to the API directly. This allows the plugin to validate and activate license keys with the Dodo Payments API. **2. Configure API Mode** In `src/ui/api.ts`, configure the API mode: ```typescript theme={null} const API_MODE: "test_mode" | "live_mode" = "test_mode"; // or "live_mode" ``` > [!TIP] > > Switch to `live_mode` only when you're ready for production and have tested thoroughly in test mode. ## Development **1. Import Plugin** Import the plugin into the Figma desktop app: 1. Open a design file. 2. Open the Figma menu and select **Plugins**. 3. Under **Development**, select **Import new plugin from manifest...**, then select the `manifest.json` file in the project root. The manifest loads the plugin from the built files in `dist/`, so start the development server or run `npm run build` before you run the plugin. > [!NOTE] > > You need the Figma desktop app to develop and test plugins locally, because Figma reads the plugin code from local files. **2. Start Development Server** ```bash theme={null} npm run dev ``` This starts the development server with file watching for automatic rebuilds. It also type-checks the code as you change it. > [!TIP] > > Your plugin rebuilds automatically when you change the source code. ## Build Commands The project includes these npm scripts: | Command | Description | | - | - | | `npm run build` | Build the plugin for production | | `npm run dev` | Start development server with file watching | | `npm run lint` | Check code style and errors | | `npm run format` | Format code with Prettier | ## License Key Integration The example implementation checks a license key before it unlocks the plugin. You can customize each step: 1. **User Input**: Users enter their license key in the plugin UI. 2. **Validation**: By default, the plugin validates the key with [Validate License](/api-reference/licenses/validate-license) (`POST /licenses/validate`). 3. **Activation**: If your license keys have an activation limit, set `needsActivation` to `true` in `src/ui/components/Unauthenticated.tsx`. The plugin then activates the key with [Activate License](/api-reference/licenses/activate-license) (`POST /licenses/activate`) instead of validating it, and names the instance `Figma Plugin`. 4. **Access Control**: For a valid key, the plugin saves the key with `figma.clientStorage` and shows `Authenticated.tsx`. The next time the plugin opens, it validates the saved key again. ## Publishing When your plugin is ready: 1. Build for production: `npm run build` 2. Test thoroughly in both test mode and live mode. 3. Follow [Figma's plugin publishing guidelines](https://developers.figma.com/docs/plugins/publishing/). 4. Submit the plugin for review through the Figma Community. ## Repository The complete example implementation is available at [github.com/dodopayments/dodopayments-figma](https://github.com/dodopayments/dodopayments-figma). Use it as your starting point to build a premium Figma plugin with Dodo Payments license keys. # Countries Eligible for Merchant Acceptance Source: https://docs.dodopayments.com/miscellaneous/accepted-countries-and-territories Full list of countries and territories where Dodo Payments supports merchant accounts and payouts. ## How Your Eligible Country Is Determined Eligibility is based on **the country that issued the government-issued identity document you verify with**, not on where your company is registered or where you pay tax. | Account Type | Whose Identity Document Decides Eligibility | | - | - | | **Individual** | Your own government-issued ID | | **Registered Entity** | The government-issued ID of every director and beneficial owner, in addition to the country of incorporation | > [!WARNING] > > Registering a company in a supported country does not by itself make an account eligible. If a director or beneficial owner can only verify with an ID issued in a country that is not listed below, the account cannot be onboarded. Tax residence, a residence permit, and a local bank account are all helpful, but none of them replace a government-issued ID from a listed country. > [!NOTE] > > Not sure how this applies to you? Contact [support@dodopayments.com](mailto:support@dodopayments.com) before you begin your integration, so you don't build against an outcome that cannot be approved. ## Accepted Countries & Territories 1. Albania 2. Andorra 3. Anguilla 4. Antigua and Barbuda 5. Argentina 6. Armenia 7. Aruba 8. Australia 9. Austria 10. Azerbaijan 11. Bahamas 12. Bahrain 13. Barbados 14. Belgium 15. Belize 16. Benin 17. Bermuda 18. Bhutan 19. Bolivia 20. Bosnia and Herzegovina 21. Botswana 22. Brazil 23. British Virgin Islands 24. Brunei Darussalam 25. Bulgaria 26. Burkina Faso 27. Cabo Verde 28. Cambodia 29. Canada 30. Cayman Islands 31. Chile 32. China 33. Colombia 34. Comoros 35. Cook Islands 36. Costa Rica 37. Croatia 38. Curacao 39. Cyprus 40. Czech Republic 41. Denmark 42. Djibouti 43. Dominica 44. Dominican Republic 45. Ecuador 46. El Salvador 47. Estonia 48. Eswatini 49. Ethiopia 50. Falkland Islands 51. Faroe Islands 52. Fiji 53. Finland 54. France 55. French Polynesia 56. Gabon 57. Gambia 58. Georgia 59. Germany 60. Ghana 61. Gibraltar 62. Greece 63. Greenland 64. Grenada 65. Guam 66. Guatemala 67. Guernsey 68. Guinea 69. Guinea-Bissau 70. Guyana 71. Honduras 72. Hong Kong 73. Hungary 74. Iceland 75. India 76. Indonesia 77. Ireland 78. Isle of Man 79. Israel 80. Italy 81. Jamaica 82. Japan 83. Jersey 84. Jordan 85. Kazakhstan 86. Kiribati 87. Kyrgyzstan 88. Latvia 89. Lesotho 90. Liberia 91. Liechtenstein 92. Lithuania 93. Luxembourg 94. Madagascar 95. Malawi 96. Malaysia 97. Maldives 98. Mali 99. Malta 100. Mauritania 101. Mauritius 102. Mexico 103. Moldova 104. Monaco 105. Mongolia 106. Montenegro 107. Montserrat 108. Mozambique 109. Namibia 110. Nepal 111. Netherlands 112. New Caledonia 113. New Zealand 114. Niger 115. North Macedonia 116. Norway 117. Oman 118. Palau 119. Panama 120. Paraguay 121. Peru 122. Philippines 123. Poland 124. Portugal 125. Puerto Rico 126. Qatar 127. Republic of Korea 128. Romania 129. Rwanda 130. Saint Kitts and Nevis 131. Saint Lucia 132. Saint Martin 133. Saint Pierre and Miquelon 134. Saint Vincent and the Grenadines 135. Samoa 136. San Marino 137. Sao Tome and Principe 138. Saudi Arabia 139. Senegal 140. Serbia 141. Seychelles 142. Sierra Leone 143. Singapore 144. Sint Maarten 145. Slovakia 146. Slovenia 147. Solomon Islands 148. South Africa 149. Spain 150. Sri Lanka 151. Suriname 152. Sweden 153. Switzerland 154. Taiwan 155. Tajikistan 156. Tanzania 157. Thailand 158. Timor-Leste 159. Togo 160. Tonga 161. Trinidad and Tobago 162. Tunisia 163. Türkiye 164. Turkmenistan 165. Turks and Caicos Islands 166. Uganda 167. United Arab Emirates 168. United Kingdom 169. United States 170. Uruguay 171. Uzbekistan 172. Vanuatu 173. Vietnam 174. Virgin Islands 175. Wallis and Futuna 176. Zambia 177. Zimbabwe > [!NOTE] > > This policy applies to all country designations made on or after March 23, 2026. Merchants who were receiving services in a country before it was added to the prohibited list will not be affected, and may continue transacting under enhanced monitoring — **unless the relevant country is subject to active sanctions or regulatory restrictions**, in which case Dodo Payments reserves the right to discontinue support. > > **Countries currently grandfathered under this provision:** Bangladesh, Egypt, Equatorial Guinea, Eritrea, Marshall Islands, Micronesia, Morocco, Nauru, Nigeria, Tuvalu, and Ukraine. > > Merchants domiciled in any other country on the prohibited list are not covered by this provision and are not eligible to onboard or continue transacting. > [!NOTE] > > This list is regularly updated to reflect FATF, OFAC, UN, and EU AML/CFT directives. All merchants are responsible for ensuring ongoing compliance. > > Payouts are supported only in the countries and regions listed above. If your country is not included, payouts are not currently available from that location. > > This list may change over time in line with regulatory and compliance requirements, and we're unable to offer payouts outside of the supported regions. > > Merchant accounts are supported only where KYC documentation is issued in the countries listed above. # Request a Card Data Export Source: https://docs.dodopayments.com/miscellaneous/card-data-export Move your customers' saved cards from Dodo Payments to your new PCI DSS Level 1 payment processor in an encrypted export, at the account owner's request. When you move to a new payment processor, we can transfer your customers' saved cards to it, so your customers don't enter their cards again. We send the cards only to a processor that meets the requirements below, in a file that only that processor can decrypt. We export the saved cards and nothing else. You stay in control of your subscriptions: you cancel them on Dodo Payments, you stop sending customers to Dodo Payments checkout, and you choose when your new processor starts charging. We never cancel anything on your behalf. To start an export, see [Request an Export](#request-an-export). ## Requirements Your new processor must meet all of these before we export any card: * **PCI DSS Level 1**: The processor is a PCI DSS Level 1 Service Provider. It sends us its current Attestation of Compliance (AOC), or we find it listed on Visa's Global Registry of Service Providers. We review this before the export. * **PGP public key**: An RSA PGP public key of 4096 bits or more. The processor sends it to us as a file, or serves it over HTTPS on a domain named in its AOC or registry listing. We encrypt the file to this key, and a second person on our team checks its fingerprint against what the processor sent. * **SSH public key**: An `ssh-ed25519` key, or an `ssh-rsa` key of 3072 bits or more. The processor uses it to sign in to our SFTP server and download the file. ## Request an Export 1. **Email [support](mailto:support@dodopayments.com) from the account owner's email address.** We accept a request only from the owner of the Dodo Payments account. 2. **Name your new processor** and give us a contact on its migration team. 3. **Confirm your responsibilities in writing.** We ask you to acknowledge that you cancel your Dodo Payments subscriptions, stop sending customers to Dodo Payments checkout, and time the switch so no customer is charged twice. ## What's Exported The export holds your customers and the saved cards behind their subscriptions, in JSON, in the format most processors already import. Each card appears once, even when several subscriptions use it. ```json expandable theme={null} { "customers": [ { "id": "cus_...", "email": "jenny.rosen@example.com", "name": "Jenny Rosen", "metadata": {}, "default_payment_method": "pm_...", "cards": [ { "id": "pm_...", "number": "4242424242424242", "name": "Jenny Rosen", "exp_month": 1, "exp_year": 2030, "address_line1": "123 Main St.", "address_line2": null, "address_city": "Springfield", "address_state": "MA", "address_zip": "01101", "address_country": "US", "network_transaction_id": "..." } ] } ] } ``` * `id` on a customer is the Dodo Payments customer ID. `id` on a card is the Dodo Payments payment method ID. * `cards` holds every card that one of the customer's subscriptions charges. `default_payment_method` is the `id` of one of them. When a customer's subscriptions use different cards, find each subscription's card by its `payment_method_id` (see [What's Not Exported](#whats-not-exported)). * `network_transaction_id` is included when we hold one for the card. * A missing value is `null`, never an empty string. * **Expired cards are included**, with their real expiry date, so your new processor can refresh them through its card updater. * The file never contains a CVC. We don't store one. ## What's Not Exported | Data | Exported | Notes | | - | - | - | | Saved cards | Yes | Including expired cards | | Apple Pay, Google Pay, UPI, and other non-card payment methods | No | Can't move between processors. These customers add a card at your new processor. | | Subscriptions | No | Read them with [List Subscriptions](/api-reference/subscriptions/get-subscriptions-1) | | Payment history | No | Read it from your dashboard or the API | Each subscription returned by `GET /subscriptions` carries a `payment_method_id`, which is the card's `id` in the export, and a `customer` object whose `customer_id` is the customer's `id` in the export. Use these fields to link each subscription to its card at your new processor. ## How the Transfer Works **1. Request** The account owner emails support and names the new processor. **2. Processor review** We review the processor's AOC or registry listing and check its PGP and SSH public keys. A second person on the Dodo Payments team signs off on the review. **3. Counts before the export** We can share the counts of what will move and what won't, such as how many cards are included, how many of them are expired, and how many customers use a non-card payment method. **4. Approval** A second person on the Dodo Payments team approves every export before it runs. **5. Export** We write the file, encrypt it to the processor's PGP key, sign it with the Dodo Payments export key, and place it on `sftp.dodopayments.com` with a manifest beside it. **6. Download** The processor downloads the file as many times as it needs within 30 days of when we place it on the server. **7. Removal** 30 days after we place the file on the server, it's deleted automatically. ## For Your New Processor Send this section to your new processor's migration team. It covers what they need to download and check the export. 1. **Send us an SSH public key.** We sign in with keys only, not passwords. Send an `ssh-ed25519` key, or an `ssh-rsa` key of 3072 bits or more. Never send the private key. Your SFTP username comes with the hand-over notice, and the account works only while a file is waiting for you. 2. **Check our host key** on the first connection. It must match one of the fingerprints below. 3. **Download the file and its manifest.** Your account can download files but can't upload or delete them. 4. **Check the manifest.** It lists the number of cards, the number of customers, and the SHA-256 digest of the encrypted file. Compare the digest with the file you downloaded before you import it. 5. **Check the signature.** The file is signed with the Dodo Payments export key. Support sends you its public key and fingerprint when we hand over the export. Confirm the fingerprint with us before you trust the key. 6. **Decrypt and import** the file in your own cardholder data environment. | Setting | Value | | - | - | | Host | `sftp.dodopayments.com` | | Port | `22` | | Authentication | SSH public key (`ssh-ed25519`, or `ssh-rsa` of 3072 bits or more) | | Host key (ED25519) | `SHA256:bNVJEIvQDpdVCqGBTNnwg7VQ92zHJAetTgU3yjH4Kzw` | | Host key (RSA) | `SHA256:c6ZtiU/pYkUouo636wygbqy/e0LpCw53l4I3Jwy8lVc` | | File name | `dodo-card-export-.json.gpg` | | Availability | 30 days from when the file is placed, any number of downloads, then deleted automatically | | PCI DSS | Level 1 service provider, [AOC](https://pub-2a89184e4c954b599464449d23f506bb.r2.dev/dodo-payments-pci-dss-aoc.pdf) | Your processor can check the host key before connecting: ```bash theme={null} ssh-keyscan -t ed25519,rsa sftp.dodopayments.com | ssh-keygen -lf - ``` ## After the Export > [!WARNING] > > **Cancel your Dodo Payments subscriptions before your new processor's first charge.** The export doesn't change your subscriptions on Dodo Payments, and we don't cancel them for you. If they stay active, your customers are charged twice: once by Dodo Payments and once by your new processor. > > Cancel each subscription in your dashboard or with [Update Subscription](/api-reference/subscriptions/patch-subscriptions), setting `status` to `cancelled`. Stop sending new customers to Dodo Payments checkout before your new processor starts charging. * You receive a completion summary, including how many of your subscriptions are still active on Dodo Payments, so you can act on them. * You keep access to your dashboard and the API while your account is open. ## Timeline | Phase | When it ends | | - | - | | Processor review and key check | When your processor has sent its AOC and keys. This depends on its response times. | | Counts, approval, and export | Agreed with support once the review is complete | | Download window | 30 days after the file is placed on the server | ## Get Started > [card] [Contact Support](mailto:support@dodopayments.com) > > Request a card data export from the account owner's email address. > [card] [Subscription Migration](/miscellaneous/subscription-migration) > > Move saved cards and subscriptions from another processor to Dodo Payments. # FAQs Source: https://docs.dodopayments.com/miscellaneous/faq Answers to common Dodo Payments questions on onboarding, verification, payments, subscriptions, payouts, refunds, webhooks, and technical integration. ## Getting Started & Account Setup > [accordion] Q1: How do I login to Dodo Payments Dashboard? > > A: Visit our dashboard and enter your account email. Dodo Payments uses passwordless login — we send a **6-digit one-time code (OTP)** to your email, which you enter to sign in. No password is required. If you face any issues, reach out to our support team. > [accordion] Q2: What documents do I need to complete the verification process? > > A: The documents required for verification include a valid government-issued ID (for identity verification) and business registration documents (for business verification). For details check the [verification process page](/miscellaneous/verification-process). > [accordion] Q3: What happens if my verification is rejected? > > A: If your verification is rejected, you will receive an email with the reason for rejection. You can contact our support team to resolve any issues, correct documentation, and reapply. The resubmit option will be enabled by our verification team if necessary. > [accordion] Q4: How long does the verification process take? > > A: The verification process typically takes **24-72 working hours**. However, if additional documents are required, the process may take longer. > [accordion] Q5: I currently do not have a website for my business. Can I submit my company's linkedin page instead? > > A: We need your website to understand the kind of products you are selling and verify your business for live access. If you do not have a website or are in the process of building one, reach out to us at [support@dodopayments.com](mailto:support@dodopayments.com). > [accordion] Q6: I am an individual and I do not have a registered business. Can I still use Dodo Payments? > > A: Yes, we support unregistered businesses as well. You do not need a registered business to use Dodo Payments. > > * You can onboard as an individual and start receiving international payments > * You will still need to submit Identity Verification and Business Verification forms as an unregistered business for us to onboard you > [accordion] Q7: I want to integrate my other business with Dodo Payments. Should I create a new account? > > A: No, you can manage multiple businesses through a single account. To add a new business, click the **+** icon in the top-left corner of the dashboard next to your current business name, select **Add New**, then **Add New Business**. > You can refer to [Managing Multiple Businesses](/miscellaneous/accounts#managing-multiple-businesses) for more details. > [accordion] Q177: How many businesses can I create under one account? > > A: You can own up to 10 businesses under a single account. [Archived businesses](/features/archive-business) don't count toward this limit. > [accordion] Q8: Should I wait for verification to complete before integrating Dodo Payments in my system? > > A: No, there is no need for you to wait. You can start integrating using the Test mode and once your verification is successful you can start making Live payments in production. Learn more about [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). > [accordion] Q9: How do I get live mode access? > > A: Once your account is created, you will automatically get access to live mode. > [accordion] Q10: Does Dodo Payments have an affiliate program? > > A: Yes — you can run your own affiliate program through our integrations with affiliate partners **[Affonso](https://affonso.io)**, **[Dub Partners](https://dub.co)**, and **[Rekomi](https://rekomi.com)**. These integrations handle commission attribution, real-time reporting, and referral tracking on top of your Dodo Payments checkout. See the [affiliates documentation](/features/affiliates) for setup steps. > [accordion] Q11: How can I delete the products/customers that I have created? > > A: You cannot delete products or customers, as they must be retained for future compliance. However, you can archive products, which removes them from the active products list while keeping the records for compliance purposes. > [accordion] Q12: How can I have a custom UI for the payments page? > > A: You can add your business logo and your business name to the payment page. To upload them, visit the business profile page on your dashboard. > [accordion] Q13: Can I update the branding on the checkout page? > > A: Yes. You can: > > * Go to **Settings → Business**. > * Update your logo, brand name, and support email. > * Changes will reflect on both static and dynamic links. > [accordion] Q14: Can I embed Dodo Checkout in an iframe? > > A: No. The hosted checkout flow does not support embedding in an iframe. > > Instead: > > * Redirect users to the Dodo checkout URL > * Or use our Overlay Checkout Feature. [Overlay Checkout Docs](/developer-resources/overlay-checkout) > [accordion] Q15: Can I create a one-time hosted checkout payment without adding products to Dodo Payments? > > A: No. Products are mandatory in the Dodo Payments system. > [accordion] Q16: Do you support e-commerce websites? > > A: No, we do not support e-commerce websites. > [accordion] Q17: Can I switch between brands in Dodo Payments? > > A: Yes, you can switch between brands for products. You can select the desired brand when creating or editing products in your dashboard. > [accordion] Q18: Can I delete a brand in Dodo Payments? > > A: Brands cannot be hard-deleted. Archive the brand with [Archive Brand](/api-reference/brands/archive-brand), which moves its products, live subscriptions, and product collections to another brand. If a brand is not in use, you can also ignore it — it won't affect your account or operations. > [accordion] Q19: Can I integrate Dodo Payments with Shopify to sell physical products? > > A: No, Dodo Payments does not support physical goods and does not offer a Shopify plugin. > [accordion] Q20: My INR subscription product is showing USD on checkout. How do I fix that? > > A: You can set a product's base price in any currency Dodo Payments can charge, so check that the product's base currency is INR. Customers outside your base currency are billed via [Adaptive Currency](/features/adaptive-currency), so enable Adaptive Currency to display prices in the customer's local currency and unlock the corresponding payment methods. > [accordion] Q21: How many brands can I create under one business? > > A: There is no maximum. You can create as many brands as you need under a single business. > [accordion] Q22: Can I change the primary brand in Dodo Payments? > > A: No, changing the primary brand is not supported. As a workaround, you can swap the brand names — update your secondary brand's name to the one you want as primary, and vice versa. ## Verification, Tax & Compliance > [accordion] Q23: Why is my verification taking so long? > > A: Dodo Payments typically takes 24–72 working hours to process verifications. However, delays can occur due to: > > * High volume of applications > > * Weekends and public holidays > > * Incomplete or incorrect submissions > > * Manual reviews for risk or compliance > > > [!NOTE] > > > > If it's been more than 72 hours, check your email or Dodo Payments dashboard for any required action. You can also DM your registered email to the team on Discord for a follow-up. > [accordion] Q24: I chose the wrong registration type (business vs individual). How can I fix it? > > A: If you selected the wrong entity type (e.g., chose "Organization" but you're an individual or a Sole Prop with GST), your verification might be On-hold, requiring you to change or update the documentation. > > Steps to fix: > > 1. Contact support, who will help you enable resubmission for the Payout Compliance form. > 2. Choose the right registration type, and resubmit the required documents. > [accordion] Q25: Can I use a different name (like my parent's) to sign up and get verified? > > A: Yes, this is allowed. However, KYC, bank details, and ownership must be under the parent's name. > > If your parent is the actual business owner: > > * They should sign up using their email and mobile number. > > * All KYC documents, bank details, and ownership records must be in their name. > > > [!NOTE] > > > > All verification documents and bank account details must match the name used for sign-up. > [accordion] Q26: How do I check the reason for verification rejection? > > A: You can find the reason in the Dodo Payments dashboard, under the verification section. > > > [!TIP] > > > > If it's not visible, contact [compliance@dodopayments.com](mailto:compliance@dodopayments.com) for assistance. > [accordion] Q27: Can I create a new business account if my previous one was declined? > > A: Yes — but only if: > > * You've fixed the issues that led to rejection. > > * You're not attempting to bypass risk decisions (e.g., deboarding for fraud concerns). > > > [!NOTE] > > > > Creating multiple accounts without resolving the underlying issue will likely result in the new account being rejected as well. > [accordion] Q28: I've been told my account was previously deboarded. What does this mean? > > A: If you see a message stating your account was previously deboarded by the risk team: > > * It means Dodo Payments found significant compliance or risk issues with your activity or business. > > * Attempting to create new accounts using the same identity or business details will likely be rejected again. > > > [!NOTE] > > > > If you believe this is a mistake, email [compliance@dodopayments.com](mailto:compliance@dodopayments.com) and request a review — include clear evidence to support your case. > [accordion] Q29: How do I get my payout verification cleared faster? > > A: To avoid delays: > > * Submit clear, properly formatted documents > > * Avoid repeated messages/tags in Discord — this slows the queue > > * Mention if you've crossed the payout threshold or have urgent timelines > > * DM your registered email ID if asked > > > [!TIP] > > > > Most payout reviews are completed within 72 working hours, unless there's an issue with your submission. > [accordion] Q30: I have a GST with a trade name. Is that considered an organization? > > A: Indian sole proprietors who have a GSTIN should switch your business type to "Registered Entity" and complete the Business Verification form. This allows you to submit your GST document and helps us cross-verify the business details with the bank account, which is usually held under the business name. > [accordion] Q31: How does Dodo Payments handle GST for Indian SaaS merchants? > > A: Dodo Payments automatically calculates and applies **GST** for Indian merchants based on your customer's location. > [accordion] Q32: Does Dodo Payments handle international sales? > > A: Yes, Dodo Payments supports international sales and manages all associated compliances. > [accordion] Q33: Are address data such as city, state, zipcode fields mandatory? Can I exclude requesting those values from my customer? > > A: Only the billing `country` is mandatory at the API level — `billing_address` requires just `country`, and `city`, `state`, `street`, and `zipcode` are all optional. On Checkout Sessions you can also set `minimal_address: true` so only `zipcode` is required when `confirm` is true. As we are the Merchant of Record, we still use the address data that is available to: > > * Generate invoices > * File taxes > * Ensure all purchases are compliant > > You can implement our API-based checkout flow to pre-fill customer details if you have already collected them, ensuring a smoother experience. If you omit the optional fields, Dodo Payments collects the remaining address details on the hosted checkout page. > [accordion] Q34: Do I need to file taxes in the US if I sell there? > > A: Not directly. Dodo Payments acts as the Merchant of Record, handles customer-side tax, and remits where applicable. We no longer require tax forms. You still need to file income tax in your home country (e.g., India). > [accordion] Q35: Do I need a PAN or GST to receive payments? (For Indian Nationals Only) > > A: **For Indian Individuals:** > > * PAN is mandatory (for KYC and tax purposes) > > **For registered businesses:** > > * Either Business PAN or GSTIN can be submitted > * GST is optional unless you exceed the registration threshold or want input credit > > **For foreign nationals:** > > * Equivalent identity and tax documentation from your country of residence will be required during the verification process > [accordion] Q36: I have a Udyam/MSME certificate. How does this affect my registration? > > A: A Udyam/MSME certificate is applicable for both individuals and private entities. Having a Udyam/MSME certificate does not automatically make you an Organization. The registration type depends on your bank account type: > > * **If you operate with a personal bank account** (even with Udyam/MSME certificate): You're considered an **Individual** > > * **If you operate with a company bank account** (registered entity): You're an **Organization** > > > [!NOTE] > > > > The key factor is whether your bank account is in your personal name or your company's name, not whether you have business registration certificates. > [accordion] Q37: Can I create an account if I am below 18? > > A: Yes, Dodo Payments does support merchants who are under 18, provided that your business is signed up with a parent or guardian's details. All documents and bank account details must belong to a parent or guardian, and all payouts will be disbursed to their bank account. Once you turn 18, you can update the account details to your own information. > > To proceed with verification, the following documents are required: > > * **Proof of Identity of the Minor:** Passport, Birth Certificate, Aadhaar Card, or any valid government-issued ID > * **Proof of Identity of the Parent/Guardian:** A valid government-issued ID (e.g., Passport, Aadhaar Card, National ID Card, or Driver's License) > * **Proof of Relationship with the Parent/Guardian:** Birth Certificate, Aadhaar Card, Passport, or equivalent official document > * **Website Domain Registration Certificate or Invoice:** The domain registration must be transferred to the assigned parent or guardian's name > > For any questions, reach out to [support@dodopayments.com](mailto:support@dodopayments.com). > [accordion] Q38: Why is my ID verification form failing? > > A: Ensure you are using a physical ID document (not a screenshot or photocopy) and capturing a live photo. Try switching browsers or devices, and make sure you are in a well-lit environment so the system can accurately capture your details. > > You get three Identity Verification attempts. After a failed attempt the dashboard shows the reason it failed, along with how many attempts you have left, and a **Try again** button to resubmit straight away. Once all three attempts are used, email [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email address to have the form re-enabled. See [If Identity Verification Fails](/miscellaneous/verification-process#if-identity-verification-fails) for the full list of causes and what to prepare before retrying. > [accordion] Q39: Is there any tax form I need to submit? > > A: The only mandatory tax form is the **W-8BEN-E**, and it is required only if you are a registered entity in the UK. > [accordion] Q40: What details are required in the Product Verification Form (PVF)? > > A: All details in the PVF must accurately match the information on your website. Ensure that your website is live, accessible, and reflects the same information provided in the form. > > Your site also needs to publicly show your pricing, Terms of Service, Privacy Policy, Refund and Cancellation Policy, and a contact route. See [Preparing Your Website](/miscellaneous/verification-process#preparing-your-website) for the full checklist. > [accordion] Q41: What happens if my form is rejected? > > A: You can view the reason for rejection on your dashboard. If you believe the rejection was incorrect, you may file an appeal (only once). > [accordion] Q42: How do I file an appeal? > > A: Follow the dashboard navigation to file an appeal. Ensure your explanation is detailed and not a one-liner. For additional clarification, you may contact [support@dodopayments.com](mailto:support@dodopayments.com). > [accordion] Q43: How long does it take for an appeal to be reviewed? > > A: Appeals typically take more than **48 working hours** to be reviewed. > [accordion] Q44: What happens if my appeal is rejected? > > A: An appeal rejection is considered final. Rejections usually occur if the product violates merchant acceptance policies, is incomplete, or still under development. You may create a new account after addressing the issues identified. For further clarification, contact [support@dodopayments.com](mailto:support@dodopayments.com). > [accordion] Q45: Can I change or update my registration type (Individual ↔ Business)? > > A: Yes. You can switch between Individual and Business account types at any time. To do this, contact support and request resubmission access. Once enabled, go to the verification section on your dashboard, select the correct registration type, and resubmit your documents. This change will not impact your existing subscriptions or payments. > [accordion] Q46: My verification is On-Hold — what does that mean? > > A: On-Hold means our compliance team needs additional information or documents from you before it can finish the review. It is not a rejection. > > We email you to ask for additional verification and raise an additional verification form in the **Verification** section of your dashboard. Complete that form to move the review forward — the form you originally submitted stays locked, so your dashboard may show that resubmissions are temporarily paused. See [If a Form Is Placed On Hold](/miscellaneous/verification-process#if-a-form-is-placed-on-hold) for the full steps. > > If your dashboard shows a hold but no additional verification form, contact [support@dodopayments.com](mailto:support@dodopayments.com) with your registered email for clarification. > [accordion] Q47: What happens to my existing subscriptions and payments if I get deboarded? > > A: If your account is deboarded, only live payments will be disabled — you will no longer be able to receive new payments. Existing subscriptions and historical payment data will not be affected. ## Payments & Transactions > [accordion] Q48: What types of payments can I accept with Dodo Payments? > > A: Dodo Payments supports a variety of payment methods, including **credit cards**, **debit cards**, and **digital wallets**. We also support one-time payments and recurring subscription payments for digital products. > [accordion] Q49: Why was the first payment marked successful with an amount of \$0 for subscription? > > A: If a product has a trial period, the first payment automatically becomes a mandate payment of \$0. This is expected behavior and confirms that the mandate has been created successfully. > [accordion] Q50: After the trial period ends, does the customer need to pay (product price(e.g \$25)) again manually? > > A: No. Once the trial ends, the system automatically generates the product price (e.g., \$25) for the customer. They do not need to pay it manually. > [accordion] Q51: What if the trial period shows differently on my app vs. the Dodo Payments dashboard? > > A: This usually indicates a setup or implementation issue on your end. Test the trial + subscription flow in test mode first, confirm it's working, and then switch to live mode. > [accordion] Q52: Do I need to test the trial feature before going live? > > A: Yes. It's recommended to fully implement and test the feature in test mode to ensure everything works correctly before switching to live mode. > [accordion] Q53: How can I track payment statuses? > > A: You can track the status of payments from the **Payments** section of your dashboard. Each transaction is listed with a status indicator: **In Progress**, **Failed**, or **Successful**. > [accordion] Q54: What should I do if a payment fails? > > A: If a payment fails, check the **Payment Details Page** for more information. Common reasons include incorrect payment details, insufficient funds, or network issues. You can resend the payment link to your customer to retry the payment. > > Look up the specific decline code in the [Transaction Failures](/api-reference/transaction-failures) reference for its meaning and recommended action, and see [Handle Payment Failures](/developer-resources/handle-payment-failures) to handle failures programmatically. > [accordion] Q55: Do merchants get notified when a user's payment fails? > > A: Yes. Dodo Payments notifies the merchant when a user's payment fails through multiple channels in live mode: > > * Email notifications > * Webhook events > * Mobile notifications > * Dashboard notifications > > This ensures merchants stay informed about failed transactions. > [accordion] Q56: What happens to a subscription if a payment fails? > > A: The subscription is not cancelled immediately. By default, it is moved to on-hold status until a successful payment is made. If you enable a [grace period](/features/subscription#grace-period), a failed renewal moves the subscription to `past_due` instead, and Dodo Payments sends the `subscription.past_due` webhook with the deadline in `past_due_ends_at`. When the grace period ends without a successful payment, the subscription moves to `on_hold` or `cancelled`. > > If you have an issue with the card, you can update the payment method by: > > * Clicking on the subscription in your dashboard and using the **Update Payment Method** button > * Or using the [Update Payment Method API](/api-reference/subscriptions/update-payment-method) > > Dodo Payments can recover these failures for you automatically: [Subscription Payment Retries](/features/recovery/payment-retries) re-attempt soft declines, and [Subscription Dunning](/features/recovery/subscription-dunning) emails the customer to update their payment method. > [accordion] Q57: If I retry payments myself, do I need the failed payment ID? > > A: It depends on what you want to do. To retry the specific failed payment, use `POST /payments/{payment_id}/retry` — that route needs the failed payment's ID. To raise a fresh charge on the subscription, use `POST /subscriptions/{subscription_id}/charge`, which needs only the subscription ID. If you would rather not manage retries yourself, enable [Subscription Payment Retries](/features/recovery/payment-retries) to recover failed renewals automatically. > [accordion] Q58: How can a subscription payment fail with INCORRECT\_NUMBER if previous cycles were successful? > > A: A subscription payment can fail with `INCORRECT_NUMBER` if the customer's card was: > > * Cancelled > * Replaced > * Deactivated > * Flagged by their bank or payment provider > > This can happen after the previous billing cycle. Dodo Payments displays the error message returned by the payment provider. See the [Transaction Failures](/api-reference/transaction-failures) reference for what `INCORRECT_NUMBER` and other decline codes mean and how to respond. > [accordion] Q59: Does the chargeback apply for business even if my business has a no refund policy? > > A: Yes. A "No refund" policy does not override the card network's dispute resolution process. Chargebacks are governed by the cardholder's bank and card network rules (e.g., Visa, Mastercard). > > If a customer files a dispute: > > * Your business is still subject to a chargeback investigation > > * You must respond with evidence (proof of delivery, usage logs, terms acceptance, etc.) > > * If the bank decides in favor of the cardholder, the chargeback fee and transaction reversal will apply regardless of your stated policy > > > [!TIP] > > > > We recommend having clear communications, tracking customer usage, and providing compelling evidence when chargebacks arise. > [accordion] Q60: Why is payment.status sometimes null? > > A: `payment.status` can be null for a short time: > > * Right after creation but before processing completes > * During subscription billing failures or retries > > Once set, it is one of: `succeeded`, `failed`, `cancelled`, `processing`, `requires_customer_action`, `requires_merchant_action`, `requires_payment_method`, `requires_confirmation`, `requires_capture`, `partially_captured`, or `partially_captured_and_capturable`. The terminal values are `succeeded`, `failed`, and `cancelled`. > > > [!NOTE] > > > > Use webhook events like `payment.succeeded` or `payment.failed` for more reliable status tracking. > [accordion] Q61: Why is product\_cart null even though it's a checkout in webhook payload? > > A: > > * For subscription payments, `product_cart` is empty because there's no one-time item being bought > * `product_cart` is only populated for one-time payments > [accordion] Q62: Why was my real card blocked during testing? > > A: You likely tested in Live Mode instead of Test Mode. > > Live payments: > > * Use real money > * Go through real banks > * May be flagged as suspicious if volume is low or inconsistent > > Always test using: > > * Test Mode in the dashboard > * Test card numbers provided in the documentation > [accordion] Q63: My customer completed payment but I didn't receive webhook? > > A: Checklist: > > * Confirm webhook is configured in **Developer → Webhooks** > * Check if webhook is failing silently due to non-2xx response > * Check logs: was a 429 or timeout returned? > * Check whether a firewall or source IP allowlist is blocking the request before it reaches your handler — deliveries are sent from a pool of addresses that changes over time, so a rule that once worked can start dropping them. See [Source IP Addresses](/developer-resources/webhooks#source-ip-addresses). > [accordion] Q64: Why is my dashboard showing success, but my app didn't update? > > A: It's likely you're relying solely on `return_url` query params and not handling: > > * Webhooks > * API confirmation call > > To fix this: > > * Always listen for the `payment.succeeded` webhook > * Or query the API to confirm transaction after redirect > [accordion] Q65: I'm not seeing UPI as a payment option — why? > > A: UPI may not appear as a payment option for several reasons: > > * The billing country is not set to India (IN). > > * Adaptive Currency is disabled. > > > [!NOTE] > > > > If you are a non-Indian merchant and Adaptive Currency is not enabled, UPI will not be available for your customers. > [accordion] Q66: Does Dodo support UPI for subscriptions? > > A: Yes, UPI subscriptions are supported with RBI-compliant mandates. UPI subscriptions operate under RBI (Reserve Bank of India) regulations with specific requirements: > > * **Mandate Limits**: > * Charges below Rs 15,000: An on-demand mandate for Rs 15,000 INR is created > * Charges Rs 15,000 or above: A subscription mandate for the exact subscription amount is created > > * **48-Hour Processing Delay**: Charges are initiated on the scheduled date, but the actual deduction occurs 48 hours after initiation (may extend up to 2-3 additional hours) > > * **Mandate Cancellation**: Customers can cancel mandates via their banking apps during the 48-hour window > > > [!NOTE] > > > > UPI subscriptions have the same RBI-compliant mandate requirements as Indian card subscriptions. For detailed information, see the [Payment Methods documentation](/features/payment-methods/india). > [accordion] Q67: How do I enable Google Pay / Apple Pay on static payment links? > > A: Google Pay and Apple Pay automatically appear on static payment links in live mode. You do not need to take any additional steps to enable them. > [accordion] Q68: How can I enable 3DS in Dodo Payments? > > A: You can enable 3DS directly from the Dodo Payments dashboard. Go to **Settings → Pricing** and turn on **3D Secure**. > [accordion] Q69: How do I collect billing details without passing them in API? > > A: If you want users to enter billing info themselves: > > * Use static links, which automatically collect billing > * For dynamic flows, create a [Checkout Session](/api-reference/checkout-sessions/create) and omit `billing_address`. Only `product_cart` is required, and the hosted checkout page collects the billing details from the customer > [accordion] Q70: What's the difference between static and dynamic payment links? > > A: **Static payment links** are no-code options meant for quick use. They: > > * Are configured from the dashboard > * Automatically collect billing info > * Cannot be customized per customer/session > > **Dynamic payment links** are created via API with [Checkout Sessions](/api-reference/checkout-sessions/create). They: > > * Accept optional billing and customer details to pre-fill checkout > > * Can be customized in real-time (price, user ID, redirect URL, etc.) > > > [!TIP] > > > > If you don't want to write code, go with static links. If you need flexibility or want to build custom workflows, use dynamic links. > [accordion] Q71: How many webhook events do I get when someone starts a subscription? > > A: On the first successful subscription payment, you will typically receive these three webhooks if no trial period is involved: > > * `subscription.active` webhook > * `payment.succeeded` webhook > * `subscription.renewed` webhook > [accordion] Q72: What does subscription.cancelled\_at mean? Is it a scheduled cancellation? > > A: Dodo supports both immediate and scheduled cancellations. > > When a cancellation request is made: > > * **Immediate cancellation**: The `subscription.cancelled_at` timestamp is set immediately and the subscription ends at that moment > * **Scheduled cancellation**: Use the `cancel_at_next_billing_date` parameter in the subscription patch API to cancel at the end of the current billing period > [accordion] Q73: When does a subscription get charged? > > A: Dodo Payments charges the customer immediately upon subscription creation if the product does not have a trial period. > > > [card] [India Payment Methods](/features/payment-methods/india) > > > > Detailed information about RBI regulations and processing delays for Indian cards and UPI subscriptions. > [accordion] Q74: Why does the Change Plan API sometimes return an empty response body? > > A: The Change Plan API returns `200` with a JSON body that can contain `payment_id`, `payment_link`, `client_secret`, `expires_on`, `invoice_id`, and `refund_id`. All of these fields are nullable, so the body can serialize as `{}` when the change settles off-session against the customer's saved card and no hosted checkout is needed — the plan change is still successful. `payment_link`, `client_secret`, and `expires_on` are populated only when the change requires a customer-facing payment, such as when you set `collect_via_payment_link`. `invoice_id` is set only for an invoice-led subscription, and `refund_id` only for a downgrade with `credit: refund`. > [accordion] Q75: Why wasn't a new payment prompted when switching from a monthly to an annual plan? > > A: When changing plans, Dodo Payments charges the saved payment method off-session, so the customer does not see a payment page. If the charge fails, the result depends on `on_payment_failure`: with `apply_change`, the new plan applies and the subscription can move to `on_hold`; with `prevent_change`, the subscription stays on its current plan. To have the customer pay on a hosted checkout page instead, send `collect_via_payment_link: true` together with `effective_at: immediately` and `on_payment_failure: prevent_change`. See [Collecting Payment via a Checkout Link](/developer-resources/subscription-upgrade-downgrade#collecting-payment-via-a-checkout-link). > [accordion] Q76: Why does my product price (Rs 100) show a higher amount (Rs 104) during checkout? > > A: This happens when Adaptive Currency is enabled. By default the conversion fee is added on top of your price and borne by the customer, on a tiered scale — 4% for orders under \$500, 3% for \$500 to \$1,500, and 2% above \$1,500. A Rs 100 order falls in the first tier, hence Rs 104. Enable **Fees Inclusive** under **Settings → Pricing** if you would rather absorb the fee yourself so the customer sees the unchanged price. See [Adaptive Currency](/features/adaptive-currency). > [accordion] Q77: Why does checkout ignore existing active subscriptions and create a new one? > > A: Checkout always creates a new subscription. It does not check whether the customer already has an active subscription. Your application must block existing subscribers from starting a checkout session to avoid duplicate charges. > [accordion] Q78: Why am I seeing a TRANSACTION\_NOT\_ALLOWED error during a subscription upgrade/downgrade? > > A: This error comes from the card issuer, not Dodo Payments. The bank is blocking the transaction due to restrictions on that card. > > Common reasons: > > * Card not allowed for online, international, or recurring payments > * Merchant category (MCC) is blocked > * Bank's fraud rules prevented the charge > * Prepaid or restricted cards may not support these payments > [accordion] Q79: Is there a way to test in live mode without making real payments? > > A: Yes. You can test live-mode checkout flows by creating a 100% discount code. This allows you to complete the full payment and redirect flow without being charged. > [accordion] Q80: What is the \$0 payment method? > > A: A \$0 payment occurs when the total payable amount becomes zero (e.g., by applying a 100% discount). In such cases, no actual payment is processed, but the checkout and subscription flow still work normally. > [accordion] Q81: It seems my account appears to be suspended, but compliance says everything is fine. What should I do? > > A: In most cases, this happens because you've accidentally switched to an old or inactive business account. Switch back to your active business account in the Dodo Payments dashboard. If the issue continues after switching, contact Dodo Payments Support for assistance. > [accordion] Q82: Do you support ACH payments? > > A: Yes. ACH Direct Debit is supported for one-time payments from customers with a US billing address paying in USD. It is not available for subscriptions. ACH payments take 4 business days to clear, so only fulfill an order once the payment reaches a succeeded state rather than when the customer authorizes it. See the [ACH Direct Debit](/features/payment-methods/ach) page for setup and testing details. > [accordion] Q83: Is PayPal supported? > > A: PayPal is currently paused. We don't have an ETA for when it will be available. Once it's live, we'll update our docs. > [accordion] Q84: What currencies does Dodo Payments natively support? > > A: Dodo Payments natively supports three payout currencies: USD, GBP, and EUR. INR remains supported as a transaction currency (UPI, RuPay, Indian-card subscriptions) but is no longer a native payout wallet. For other currencies, you can enable [Adaptive Currency](/features/adaptive-currency) to automatically convert prices to your customer's local currency. > > If your linked bank account is credited in a currency other than the one the transfer is sent in, your bank performs that conversion on receipt at its own exchange rate and may apply its own receiving charges. Payout routes and currencies vary by country — contact [support@dodopayments.com](mailto:support@dodopayments.com) to confirm how your payouts will be sent and credited. > [accordion] Q85: How are FX conversion charges calculated? > > A: FX conversion charges are applied based on the exchange rate on the day the transaction is processed. Rates vary daily based on market fluctuations. > [accordion] Q86: Which countries does Dodo Payments accept payments from? > > A: See the full [list of supported countries](/miscellaneous/list-of-countries-we-accept-payments-from). > [accordion] Q87: How do I add an addon to an existing subscription? > > A: Use the Change Plan API with the same `product_id` and include the `addons` array. The base plan is unchanged and the customer is charged a prorated amount immediately. > > The `addons` array **replaces** the subscription's addon list — it is not an append. Send every addon you want the subscription to keep, including ones it already has; leaving it empty removes all existing addons. > > Example: > > ```http expandable theme={null} > POST /subscriptions/{subscription_id}/change-plan > { > "product_id": "pdt_current_product", > "quantity": 1, > "proration_billing_mode": "prorated_immediately", > "addons": [ > { "addon_id": "adn_your_addon", "quantity": 1 } > ] > } > ``` > [accordion] Q88: How long can a subscription stay in On-Hold state? > > A: A subscription stays On-Hold until the customer updates their payment method and a successful payment is made. The payment method can be updated at any time — from the Customer Portal or via the [Update Payment Method API](/api-reference/subscriptions/update-payment-method) — whether or not a payment has failed. > [accordion] Q89: Can I make tax inclusive in the product price? > > A: Yes. Go to **Products → Edit Product → Pricing** and enable **Tax Inclusive Pricing**. Taxes are automatically calculated based on the customer's location — there's no fixed tax list to manage. > [accordion] Q90: Can addons have their own brand? > > A: No. Add-ons cannot be purchased standalone and don't support branding directly. The brand is defined on the base product. Attach the brand to the main product and then add your add-ons to it. > [accordion] Q91: Can I switch a product to a different brand? > > A: Yes. While the brand cannot be switched during product creation, you can edit an existing product and change its brand from the product edit page. > [accordion] Q92: How does seat-based billing pricing work for subscriptions? > > A: Seat-based billing combines a base subscription with a per-seat addon. For example, a Team Pro subscription costs \$99/month and includes 5 seats — if you have more than 5 users, you pay an additional \$15/month for each extra seat. > > See the [Seat-Based Pricing guide](/developer-resources/seat-based-pricing) for how to configure this. > [accordion] Q93: How do I charge less in price-sensitive countries like India or Brazil? > > A: Use [Purchasing Power Parity](/features/purchasing-power-parity). You set one percentage per country, turn it on for the product prices you choose, and Dodo Payments applies it automatically at checkout based on the customer's billing country. It requires [Adaptive Currency](/features/adaptive-currency), which you enable under **Settings → Pricing**. If you would rather set an exact price per country, use [Localized Pricing](/features/localized-pricing) instead. > [accordion] Q94: How do I show clean prices like 49.99 instead of converted amounts like 52.37? > > A: Enable [Charm Pricing](/features/charm-pricing) under **Settings → Pricing**. It rounds the converted price to a clean ending in each currency, so customers see a familiar number instead of a raw conversion. It runs after currency conversion and also requires [Adaptive Currency](/features/adaptive-currency). ## Payouts & Bank Integration > [accordion] Q95: How do payouts work with Dodo Payments? > > A: Payouts are the transfer of your collected sales revenue to your linked bank account. Dodo Payments supports multiple payout cycles: > > * **Bi-Monthly (Default)**: > * Billing Period 1: 1st to 15th → Payout on 18th of same month > * Billing Period 2: 16th to end of month → Payout on 4th of following month > * **Weekly**: Available for businesses with higher transaction volumes (contact support to request) > * **Monthly**: > * Billing Period: 1st to end of month → Payout on 11th of following month > > Payouts are only initiated if all verifications are successful and the payout threshold is met. It typically takes 1-2 business days for funds to appear in your bank account after the payout is initiated. > > > [!NOTE] > > > > Delays may occur if payout processing dates fall on weekends or bank holidays. The default payout cycle for all businesses is bi-monthly. > [accordion] Q96: What is the minimum threshold amount after fees and taxes to process payouts? > > A: The minimum payout threshold after platform fees and taxes deduction is: > > * **USD**: \$50 > > Payouts are only initiated when the overall wallet balance across all currencies exceeds **\$50 USD**. If your balance doesn't meet the threshold, it will carry forward to the next payout cycle. > > You can customize your USD wallet threshold to any amount of **\$50 or above** directly from your dashboard. You can see the exact wallet amount and manage your payout threshold under **Settings → Payouts** in your dashboard. See [How to Edit Your Threshold](/features/payouts/payout-structure#how-to-edit-your-threshold). > > > [!NOTE] > > > > The flexible threshold feature is available for the USD/EUR/GBP wallets. Support for the INR native wallet has been discontinued. > [accordion] Q97: How do I link my bank account to receive payouts? > > A: To link your bank account, go to **Settings → Payouts** in your dashboard, or click **Manage Accounts** on the **Linked Bank Accounts** card of the **Payouts** page. You'll need to enter your bank details and verify the account. > [accordion] Q98: Can I track the status of my payouts? > > A: Yes, you can track your payout status from the **Payouts** section of the dashboard. > [accordion] Q99: Why is my payout delayed? > > A: Most payout delays have one of three causes: a bank holiday, international bank processing time, or extra checks by your bank. Check the status of each payout in the **Payouts** section of your dashboard, which shows the date, amount, and status. > > **When is my payout initiated?** > > Dodo Payments initiates the payout on the payout date shown in the **Payouts** section of your dashboard. If the scheduled date falls on a bank holiday or weekend, the payout is initiated on the next business day. > > The default payout cycle is bi-monthly, with payouts initiated on the **4th** and **18th** of every month. After a payout is initiated, it can take 1 to 5 business days to reach your bank. > > **How long does a payout take to reach my bank account?** > > International bank transfers usually take 1 to 5 business days after the payout is initiated. Weekends and bank holidays are not counted as business days. > > **Reasons for Delayed Payouts** > > | Reason | What happens | What you can do | > | - | - | - | > | Bank holiday | The payout is initiated on the next business day. | Check the updated date in your dashboard. | > | International bank processing | The transfer can take 1 to 5 business days to arrive. | Allow 1 to 5 business days from initiation. | > | Recipient bank review | Your bank holds the transfer for additional checks. | Contact your bank with the payout reference. You can also contact support for the required details, or Dodo Payments may reach out if additional information is needed. | > > **Why was my payout not initiated on the scheduled date?** > > Your payout may have been delayed because of: > > * A bank holiday > * An issue with your bank information > * Incomplete account details > * The selected bank account not being marked as **ACTIVE** in your dashboard > > Depending on the reason, the payout is initiated on the next business day or on the next payout cycle date. The exact payout date is shown in your dashboard. > > **My payout was initiated. Why hasn't it reached my bank account yet?** > > International banks usually take 1 to 5 business days to process an incoming payout. Bank holidays in either country can extend this. > > **Can my own bank delay the payout?** > > Yes. Your bank (the recipient bank) may apply additional scrutiny to an incoming international transfer before crediting it. This decision is made by your bank, not by Dodo Payments. To get more information to track your payout, email [support@dodopayments.com](mailto:support@dodopayments.com). > > **Who should I contact if my payout is still delayed?** > > If more than 5 business days have passed since your payout was initiated and your bank has no record of it, email [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email address. Include your business ID. > [accordion] Q100: What are payout fees and how much are they? > > A: Payout fees are the transaction costs for transferring collected revenue to your bank account. > > * We constantly work to reduce fees by partnering with local partners in your country > * Separately from our fees, your own bank and any intermediary banks may charge for receiving a cross-border transfer, reducing the amount credited to your account > * Refer to the [pricing page](https://dodopayments.com/pricing) for detailed information > [accordion] Q101: I received a "payout processed" email — when will the funds arrive? > > A: Payouts usually take 1–2 business days to reflect in your bank account. > > > [!NOTE] > > > > Transfers don't settle on weekends or bank holidays. If your payout was processed on Friday, expect it by Monday or Tuesday. > [accordion] Q102: How do I add Payoneer as a payout account? > > A: Enter your Payoneer bank details in the Bank Info Form under your dashboard. There's no separate Payoneer integration yet. > [accordion] Q103: Can I receive payouts to a Payoneer account? > > A: Yes. You can receive payouts via Payoneer by: > > * Entering your Payoneer account details in the Bank Info Form on the Dodo dashboard > * Ensure your account is approved and supports USD or the currency you're withdrawing > > There is no dedicated Payoneer integration — it is treated as a regular bank account. > [accordion] Q104: My bank info is still in review — what should I do? > > A: No compliance form is required anymore. For bank info review, no action is needed from you. Our team typically reviews bank details within 1–2 working days. If it's urgent: > > * Email [support@dodopayments.com](mailto:support@dodopayments.com) > [accordion] Q105: What happens if my payout day falls on a Friday or weekend? > > A: If your payout day is on a Friday, it is usually processed on the same day. However: > > * If there's a bank holiday or weekend, it may be delayed to the next working day (usually Monday). > > * The exact timing may depend on your bank's processing rules. > > > [!NOTE] > > > > If in doubt, check your dashboard or ask support with your registered email. > [accordion] Q106: How can I expedite payout compliance if I have an urgent launch or ad campaign planned? > > A: If you've submitted everything and are awaiting payout compliance: > > * Mention your urgency clearly in support chats (e.g., live launch, paid campaigns). > * Include your business ID and email. > * Avoid spamming or tagging multiple team members — this may slow down the queue. > [accordion] Q107: I submitted the wrong bank account details. How do I update them? > > A: Go to the **Payouts** page and open the account under **Linked Bank Accounts**. Accounts placed on hold or marked failed show the reason inline and offer a **resubmit** action, so you can correct the details yourself. You can also add a new payout account and activate it instead. > > > [!NOTE] > > > > If the account is not resubmittable from the dashboard, contact support by chat or email and the compliance team will reopen the section for you. See [Payout Accounts](/features/payouts/payout-structure#payout-accounts). > [accordion] Q108: Can I use my personal bank account if I have a registered company? > > A: No. If you're registered as a company or legal entity, you must use the entity's bank account. > [accordion] Q109: My country doesn't use SWIFT codes. How will that affect my verification? > > A: If your country does not issue SWIFT codes, this will not block your verification. > > What to do: > > * Contact support and explain that your country doesn't issue SWIFT codes > > * Submit official bank documents that confirm: > * Your account number > * Account holder name > * That no SWIFT code is issued in your country > > * In some cases, a generic placeholder SWIFT may be used based on your country > > > [!NOTE] > > > > For faster processing, write to [compliance@dodopayments.com](mailto:compliance@dodopayments.com) for escalation. > [accordion] Q110: What alternative documentation can I provide if my country doesn't use SWIFT codes? > > A: If your country doesn't use SWIFT codes, provide the following alternative documentation: > > * Official bank statement or certificate showing your account details > > * Bank letter confirming your account number, holder name, and that SWIFT codes are not issued > > * Any government-issued document that confirms your bank's routing information format > > > [!TIP] > > > > Contact [support@dodopayments.com](mailto:support@dodopayments.com) before submitting to ensure you provide the correct documentation format for your country. > [accordion] Q111: Can I set a payout threshold lower than \$50? > > A: No. The minimum payout threshold is **\$50** and cannot be lowered. > > * You **can** increase the threshold above \$50 > * You **cannot** set it below \$50 > [accordion] Q112: Do you support daily payouts? > > A: No, daily payouts are not available. The available payout cycles are bi-monthly (default), weekly (for high-volume businesses), and monthly. See [Payout Cycles](/features/payouts/payout-structure#payout-cycles) for full details. > [accordion] Q176: Why does my dashboard say Payouts Inactive? > > A: **Payouts Inactive** means no payout is scheduled. Most often payouts are not enabled yet: live payments and payouts are enabled by two separate gates, so you may be taking live payments while payouts are still inactive. > > Payouts additionally require: > > * **Bank Verification** approved — plus **Business Verification** for registered entities > * The **Monitoring Review** completed > > Open the **Verification** section of your dashboard and check each form. A form still in draft, under review, or on hold is the usual reason, and completing it is what moves your account forward. If every form is approved and payouts remain inactive, email [support@dodopayments.com](mailto:support@dodopayments.com) from your registered email address. > > Payouts that were already running can also return to inactive — for example while an information request is outstanding or a compliance review is in progress. See [If Payouts Were Previously Active](/features/payouts/payout-structure#if-payouts-were-previously-active). > > > [!NOTE] > > > > Payouts being active is not the same as a payout being sent. Once payouts are enabled, a payout is initiated only when your eligible balance meets your threshold and your next payout date arrives. See [Why Payouts Show as Inactive](/features/payouts/payout-structure#why-payouts-show-as-inactive). ## Invoicing & Reports > [accordion] Q113: Does Dodo Payments generate invoices automatically? > > A: Yes, Dodo Payments automatically generates **invoices** for every successful transaction. These invoices include all necessary details such as tax breakdowns, customer information, and product details. > [accordion] Q114: Can I customize the invoices? > > A: Yes, you can customize the look of your invoices by adding your **company logo and brand name.** You can manage these settings in the Business Profile section of your dashboard. > [accordion] Q115: How do I access or download an invoice? > > A: You can view or download invoices from the **Invoices** section of the dashboard. Each payment will have an associated invoice that can be downloaded as a **PDF**. > [accordion] Q116: How do I view reports on my transactions and payouts? > > A: You can generate detailed reports from the **Reports** section of your dashboard. These reports include data on transactions, refunds, and payouts, which you can filter by date and export in CSV format. > [accordion] Q117: Can I change the billing address on my invoice? > > A: Yes. Go to the Customer Portal, download the invoice, and select **Download with full address details**. You can then update the billing address. > > This option is available for the following countries: AU, BR, CA, FR, DE, IT, NL, PT, ES, GB, and US. > [accordion] Q118: If I change the billing address, will it update all my existing invoices? > > A: No. The address change applies only to the specific invoice you are downloading. It will not update the billing address on your other existing invoices. ## Refunds & Disputes > [accordion] Q119: How do I issue a refund? > > A: To issue a refund, go to the **Payment Details Page** of the transaction you want to refund and click the **Initiate Refund** button. You can issue a **full** or **partial** refund, provided the payment meets the refund eligibility rules. > [accordion] Q120: How long does it take for a customer to receive their refund? > > A: Once a refund is initiated, the customer will typically receive the refunded amount within **3-15 business days**, depending on the payment method and their bank. > [accordion] Q121: I'm facing a dispute or chargeback. What can I do? > > A: If a chargeback is filed against you: > > * You may lose both the transaction amount and a dispute fee > > * You can submit evidence of product delivery, usage logs, or customer communication > > * However, the final decision lies with the customer's issuing bank > > > [!NOTE] > > > > Email [support@dodopayments.com](mailto:support@dodopayments.com) with: > > > > * Dispute ID > > * Payment ID > > * Relevant proof > [accordion] Q122: The customer disputed the charge after using the service. Can I appeal this? > > A: Yes — you can: > > * Share documentation (chat logs, usage records, delivery confirmation) > > * Explain that the service was fulfilled > > * Request a waiver of the dispute fee if it's a first-time issue or if fraud is provable > > > [!TIP] > > > > There's no guarantee the fee will be waived, but our team reviews each case on merit. > [accordion] Q123: Why is my refund failing with an 'insufficient funds' error? > > A: Refunds are checked against your available account balance, not your scheduled payout amount. If payouts are already scheduled, that amount is not counted as available. If your available balance is too low, the refund will fail. Wait for your next payout cycle to build up balance, or contact support. ## Webhooks & Integration > [accordion] Q124: How is proration calculated — on the product price or the total amount? > > A: Proration is calculated on the **total amount paid**, not just the base product price. > This means if a discount is applied, the proration is calculated on the **final amount after the discount**. > [accordion] Q125: Why do we use the `subscription.renewed` webhook for the first subscription? > > A: After the first payment succeeds, the subscription enters its first billing period and the next billing date is set. > The `subscription.renewed` webhook is sent to indicate that a billing period is now active and the next billing cycle has been scheduled. > This webhook is used for every billing period—including the first one—so billing logic can be handled consistently each time. > [accordion] Q126: Can I manually verify Dodo Payments webhooks in Python? > > A: Yes. Manual verification is possible, but it must strictly follow the correct signing steps. For an easier and more reliable approach, Dodo Payments recommends using the `standardwebhooks` package: > > ```python expandable theme={null} > from standardwebhooks.webhooks import Webhook > > wh = Webhook(webhook_secret_key) > payload = request.get_data(as_text=True) > headers = request.headers > > if not wh.verify(payload, headers): > return jsonify({'error': 'Invalid webhook signature'}), 401 > ``` > > Then parse the payload as needed. > [accordion] Q127: Where can I find official docs on manual webhook verification? > > A: You can refer to the official Dodo Payments documentation on [manual webhook verification](/developer-resources/webhooks#manual-verification-alternative). > [accordion] Q128: My webhook isn't receiving a POST request, only a GET. Why? > > A: You're likely confusing the redirect URL with the webhook URL. A redirect URL is where the user is sent after a payment, and it may contain `?subscription_id=...&status=active` in a GET request. This is not your webhook. > > To receive structured POST payloads from Dodo Payments: > > * Set up a webhook under **Developer → Webhooks** > > * Ensure the URL accepts POST requests and verifies the signature > > > [!NOTE] > > > > You can have both a webhook and a redirect URL — they serve different purposes. > [accordion] Q129: I get a 401 Unauthorized error using the Python SDK. Why? > > A: You likely forgot to pass the correct environment when initializing the DodoPayments client. > > > [!TIP] > > > > **Fix:** > > > > ```python theme={null} > > client = DodoPayments( > > bearer_token="dodo_live_...", # a test mode key needs "test_mode" > > environment="live_mode" # or "test_mode" > > ) > > ``` > [accordion] Q130: Is there a way to manually trigger a webhook event for testing? > > A: You can do it through the webhook dashboard. Go to **Developer → Webhooks**. > [accordion] Q131: What's the difference between webhook and redirect URL? > > A: > > * **Webhook URL**: Configured in dashboard. Receives POST payloads about events. > > * **Redirect URL**: Sent in the payment API request. Sends user back to your app with query params (`?status=success`). > > > [!TIP] > > > > Use webhooks to automate things like DB updates, and redirects to show thank-you screens. > [accordion] Q132: Why didn't I receive the product id in the payment.succeeded webhook for a subscription product? > > A: The `payment.succeeded` webhook event for subscription products does not include a `product_id`. Instead, it provides the `subscription_id` associated with the subscription, along with other relevant details. For a [multi-subscription cart](/developer-resources/checkout-session#multi-subscription-cart), `subscription_id` is `null` and `is_multi_subscription` is `true`. Read the subscriptions from `subscription_ids`. > [accordion] Q133: How do I verify the webhooks I receive are actually from Dodo Payments and not from any malicious actors? > > A: To verify webhook authenticity, follow these steps: > > 1. **Check the Signature**: Each webhook includes a unique signature in the `webhook-signature` header, generated using your secret key and the payload > > 2. **Retrieve the Secret Key**: Found in your Dodo Payments dashboard under Webhooks settings > > 3. **Recompute the Signature**: Use HMAC-SHA256 with your webhook secret key and the payload > > 4. **Compare Signatures**: If they match, the webhook is authentic; if not, reject it > > 5. **Use HTTPS**: Ensure your endpoint uses HTTPS to prevent tampering during transmission > > > [!TIP] > > > > We recommend using packages provided by StandardWebhooks to verify the signature rather than constructing it yourself. > [accordion] Q134: Why am I receiving a subscription.renewed webhook even for the first month payment? > > A: For subscriptions, `subscription.renewed` will be triggered whenever the subscription amount is deducted. So yes, this is expected behavior. > [accordion] Q135: How can I test webhooks locally? > > A: To test webhooks locally, you can follow these steps: > > 1. **Use a Tunneling Tool**: Tools like [ngrok](https://ngrok.com/), [LocalTunnel](https://localtunnel.github.io/www/), or [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/) can expose your local server to the internet. This provides a public URL that Dodo Payments can use to send webhook events to your local environment. > 2. **Set Up the Webhook Endpoint**: Create a webhook endpoint in your local application to handle incoming webhook events. Ensure it listens for HTTP POST requests. > 3. **Configure the Webhook in Dodo Payments**: Go to your Dodo Payments dashboard, navigate to the Webhooks settings, and update the webhook URL to the public URL generated by the tunneling tool. > [accordion] Q136: Why is my webhook not being called after payment? > > A: Check the following: > > * You did not confuse the webhook URL with redirect URL > * The webhook is configured under **Developer → Webhooks** > * Your URL accepts POST requests and responds with 2xx > * Signature validation (if enabled) is implemented correctly > > If you only see `GET` requests with `?status=success`, you are debugging the redirect URL, not the webhook. > [accordion] Q137: Is it safe to rely on status=success in URL query params? > > A: No. While it's a quick win, URL query params can be tampered with. > > If you're using `return_url?status=success`: > > * Double-validate the transaction with an API call > > * Or wait for the `payment.succeeded` webhook > > > [!TIP] > > > > Treat redirects as user-facing confirmations, not proof of payment. > [accordion] Q138: Can I integrate Dodo Payments with my existing website or platform? > > A: Yes, Dodo Payments offers **API integration** and **SDK support** for integration with your website or platform. You can find API documentation, SDK guides, and integration resources in the **Developer Section** of your dashboard. > [accordion] Q139: Why are my webhooks always failing? > > A: Common causes: > > * Your endpoint is unreachable or returning a non-2xx status code > * The endpoint is timing out before responding > * The webhook URL in your dashboard is incorrect > > Ensure your endpoint is publicly accessible, returns a 200 promptly, and the URL is correctly configured in the Dodo Payments dashboard. > > ![Message attempts table on an endpoint with failed payment.succeeded deliveries that returned HTTP 500](https://mintcdn.com/dodopayments/DL_ADtkdH7ph5YST/images/webhooks/webhook-failed.png?fit=max\&auto=format\&n=DL_ADtkdH7ph5YST\&q=85\&s=dc126e91d9998ad1d17753857d4f8a5d) > [accordion] Q140: Where do I find my API key? > > A: Go to **Developer → API Keys**. Make sure you're in the correct mode (Test or Live) before copying the key. > [accordion] Q141: What are the base URLs for the Dodo Payments API? > > A: The base URLs are: > > * **Live Mode:** `https://live.dodopayments.com` > * **Test Mode:** `https://test.dodopayments.com` ## Testing & Local Development > [accordion] Q142: Can I test subscriptions in Test Mode? > > A: Yes — subscriptions can be tested fully in Test Mode. > > Don't use real card numbers. > [accordion] Q143: How do I switch between Test and Live Mode? > > A: > > * In the dashboard sidebar, use the **Test Mode** / **Live Mode** toggle. > * Select **Test Mode** to use test API keys and simulate payments, or **Live Mode** to accept real payments. Until live mode is activated for your business, the dashboard stays in Test Mode. > > In Test Mode, a "You are in Test Mode." bar appears across the top of the dashboard. Make sure to use the corresponding API key or environment when switching. > [accordion] Q144: Can I use real customer data in Test Mode? > > A: Yes, but keep in mind: > > * No real money will be transferred > * You can simulate webhooks and flows > * Card details should still be test cards > > This helps debug flows end-to-end without any financial impact. > [accordion] Q145: Can I advance the next billing date in test mode? > > A: Yes. Use the Update Subscription API and set the `next_billing_date` field to the date you want. See [Update Subscription](/api-reference/subscriptions/patch-subscriptions#body-next-billing-date). > [accordion] Q146: Are customer emails sent in Test Mode? > > A: Yes, by default. Customer emails in Test Mode go to the real recipient, and each subject starts with `[TEST MODE]`. > > **What this means:** > > * The **Test Mode Emails** switch under **Settings → Communication → Email** controls this. It is on by default. > * A business can send up to 100 Test Mode emails per week. > * If you turn the switch off, no customer emails are sent in Test Mode. Webhook events are still triggered. > > See [Test Mode Emails](/features/communication-preferences#test-mode-emails) for details. ## Support & Communication > [accordion] Q147: How do I contact support? > > A: You can contact our support team by sending an email to [**support@dodopayments.com**](mailto:support@dodopayments.com). We are here to assist you with any issues or questions you may have. > [accordion] Q148: My support messages are getting no response. What should I do? > > A: If you've messaged in: > > * Support chat with no response > * Discord without acknowledgement > > Then: > > * Escalate via [compliance@dodopayments.com](mailto:compliance@dodopayments.com) or [support@dodopayments.com](mailto:support@dodopayments.com) with subject line Urgent: No Response – \[Your Email] > [accordion] Q149: How do I unsubscribe a customer from Dodo Digest emails? > > A: Share the customer's email address with us via support chat or email and we'll unsubscribe them from our end. ## Security & Fraud Prevention > [accordion] Q150: How does Dodo Payments protect my business from fraud? > > A: Dodo Payments uses **real-time fraud detection** to monitor suspicious transactions. We also comply with **PCI-DSS standards** to ensure that all payment information is encrypted and secure. > [accordion] Q151: Is my customer data secure with Dodo Payments? > > A: Yes, Dodo Payments uses **data encryption** and **tokenization** to protect sensitive information. We ensure that customer payment data is never stored directly and remains secure during transactions. > [accordion] Q152: I found a security vulnerability in Dodo Payments. How should I report it? > > A: Report any discovered vulnerabilities directly to our security team at [pt-team@dodopayments.com](mailto:pt-team@dodopayments.com). > [accordion] Q153: Does Dodo Payments offer bug bounties? > > A: We currently do not offer monetary bounties, but we do provide Dodo Payments merchandise as a token of appreciation. > [accordion] Q154: How are customers protected from fraud on Dodo Payments? > > A: Dodo Payments uses real-time fraud detection to analyze and block suspicious transactions before they occur. All payments are also protected through standard card network safeguards — customers can raise disputes or chargebacks for unauthorized charges. We are PCI compliant, ensuring all payment data meets the highest security standards. ## Payments Failures > [accordion] Q155: Why is my payment status showing 'Not Initiated'? > > A: This means the payment link was created, but the user never opened the payment page or attempted the payment. > [accordion] Q156: Why is my payment status showing 'Requires Payment Method'? > > A: This means the user opened the payment page and entered customer details but exited before adding card or payment details. > [accordion] Q157: Why am I getting an 'Invalid authorization details' error? > > A: This usually happens when the 3D Secure (3DS) authentication fails or is not completed by the user. > [accordion] Q158: Why am I getting an 'Authentication failure' error for payments? > > A: The payment failed due to an authentication error. Check with your bank regarding this issue. Unfortunately, there is nothing further we can do from our side. We recommend trying a different card or a different payment method. > [accordion] Q159: I'm seeing a 500 INTERNAL\_SERVER\_ERROR ("Internal Server Error") in test mode. How do I fix it? > > A: This typically happens when the test card does not match the billing country: > > * **US billing country** → Use a US test card > * **India billing country** → Use an INR test card > > Refer to the [test card numbers documentation](https://docs.dodopayments.com/miscellaneous/testing-process#test-cards). > [accordion] Q160: Why am I getting PAYMENT\_METHOD\_UNSUPPORTED ("mode not enabled for merchant") in test mode? > > A: The selected payment method is not enabled for your merchant account. Ensure you are using the correct test card for your billing country: > > * **US billing country** → Use a US test card > * **India billing country** → Use an INR test card > > Refer to the [test card numbers documentation](https://docs.dodopayments.com/miscellaneous/testing-process#test-cards). > [accordion] Q161: What does the requires\_customer\_action status mean? > > A: The payment requires additional action from the customer — such as 3D Secure authentication, OTP verification, or UPI approval. The customer must complete the required action before the payment can be processed. > [accordion] Q162: Why am I getting a SUBSCRIPTION\_NOT\_ACTIVE error? > > A: This error occurs when the customer has cancelled the mandate (recurring payment authorization) from their UPI app. The subscription can no longer process payments because the underlying mandate has been revoked by the customer. > [accordion] Q163: Why am I getting a payment failure with UNKNOWN\_ERROR? > > A: Your payment failed with error code `UNKNOWN_ERROR`. The payment was initially processed, but your bank later reversed the transaction and refunded the amount, so it was marked as failed. This issue is not from our side. > > Try making the payment again. If it fails again, try using a different card or payment method. You may also contact your bank for further clarification. > [accordion] Q164: I'm getting: "You must provide a mandate for off-session card payments" > > A: It means: > > * An Indian Card is used to make the payment but the billing country is not set as IN. > * You likely passed an incorrect billing country. ## Developer & Technical Integration > [accordion] Q165: Is the Customer Portal tied to a specific customer? > > A: Yes. The portal is customer-specific. You can either send a magic link for a specific customer (one-time, expires in 24 hours) or use the static email login where the customer enters their purchase email to get a secure link. When you create a portal session via API (`client.customers.customerPortal.create('cus_123')`), it's bound to that customer. > [accordion] Q166: Can I use Laravel with Dodo Payments? > > A: Yes, Laravel is supported. See the [PHP/Laravel SDK docs](/developer-resources/sdks/php#laravel). > [accordion] Q167: Does Dodo Payments support WHMCS? > > A: WHMCS is not officially supported. You can either build a custom payment module using our API (payments + webhooks), or use Dodo checkout links in invoices as a temporary workaround. > [accordion] Q168: Can I integrate Dodo Payments in an Android or mobile app? > > A: Yes. Refer to the [mobile integration guide](/developer-resources/mobile-integration). > > You can also use the [Dodo Agent Plugin](/developer-resources/build-with-ai-coding-agents) for AI-assisted integration. > [accordion] Q169: How do I find my live publishable key (pk\_live\_...)? > > A: Switch to Live Mode in the dashboard. Go to the Developer section → click Other → you'll see the Publishable Key. Click View to reveal it. > [accordion] Q170: Does Dodo Payments support WooCommerce blocks (WordPress block editor)? > > A: Not currently. The WooCommerce plugin is open source — if you'd like this feature, you're welcome to raise a pull request to implement it. > [accordion] Q171: Why can't I see the upgrade/downgrade button in my Customer Portal? > > A: There are two things you need to do: > > * Go to **Settings → Subscriptions → Allow Subscription Updates** and turn this toggle on. > * Add the products you want customers to be able to upgrade or downgrade to a **Product Collection**. > > Once this is enabled and the products are added to the collection, customers will be able to upgrade or downgrade their subscription through the Customer Portal. > [accordion] Q172: How many discount codes can be applied in one checkout? > > A: Up to 20 codes can be stacked via the `discount_codes` array (max 20 entries). The older singular `discount_code` field is deprecated and cannot be used together with `discount_codes`. > [accordion] Q173: How do I change my login email? > > A: You can change your login email from your account settings. The new email will be updated across all your businesses. > > To complete the change, you'll need to: > > * Verify your current email. > * Verify your new email. > [accordion] Q174: Why am I getting the business\_id as my brand\_id? > > A: When a business is created, a primary brand is automatically created for it. For this primary brand, the `brand_id` is the same as the `business_id`. > > If you create additional brands under the same business, each of them will have a unique `brand_id`. > [accordion] Q175: What are the limitations when adding Notion content? > > A: Notion pages cannot be added if they exceed the supported file size limit. We also do not support Notion databases. # Help and Support Source: https://docs.dodopayments.com/miscellaneous/help-support Get help with Dodo Payments from the dashboard support menu: AI chat, the Discord community, chat or email support, and the documentation. Dodo Payments offers several support channels, from instant AI answers to direct help from the support team. Pick the channel that fits the complexity of your question and how fast you need an answer. ## **Dodo Payments Centralized Support System** The Dodo Payments Centralized Support System brings every support channel into one menu in the dashboard. To open it, select the support icon in the dashboard header. The **Help and support** menu lists these options: * **Ask Dodo AI**, the AI assistant, for answers to common questions * **Join Our Discord Community** * **Chat Support**, or **Email Support** when chat is not available * **Feature Requests**, which opens the feedback portal (see [Feature Request and Roadmap](/features/feature-request)) * **Visit Docs**, which opens this documentation ## 1. AI-Powered Chat Assistance **Ask Dodo AI** opens Dodo AI, the Dodo Payments AI assistant. It answers common questions, so you need direct human support less often. It helps you by: * Answering technical and business questions * Guiding you through API integration and setup * Pointing you to the right pages in the product documentation **Best for:** Instant self-serve help and general troubleshooting. > [!TIP] > > For AI help while you write integration code, install the Dodo Agent Plugin in your coding agent. See [Build with AI Coding Agents](/developer-resources/build-with-ai-coding-agents). ## 2. Community Support via Discord The [Dodo Payments Discord community](https://discord.gg/bYqAp4ayYh) connects you with other merchants and the Dodo Payments team. On Discord, you can: * Discuss best practices and share experiences * Get peer-to-peer help from other merchants * Talk with the Dodo Payments support team **Best for:** Peer support, longer questions, and networking with other merchants. ## 3. Dedicated Chat Support Chat Support gives you a direct line to the Dodo Payments support team for complex or account-specific questions: * Submit detailed questions through **Chat Support** in the dashboard's **Help and support** menu. * The team responds within 24–48 business hours. * Unresolved tickets close automatically after 72 hours without a reply from you. If chat is not available, the menu shows **Email Support** instead, which opens an email to [support@dodopayments.com](mailto:support@dodopayments.com). Use this channel for critical issues that need a person to review your account. **Best for:** Account-related concerns, technical escalations, and personalized troubleshooting. ## **4. Self-Service Documentation** The Dodo Payments documentation covers products and integrations in detail, so you can find answers at your own pace. It includes: * Detailed feature explanations * Step-by-step implementation guides * The [API reference](/api-reference/introduction) and integration guides * [Frequently Asked Questions (FAQs)](/miscellaneous/faq) **Best for:** In-depth learning, implementation guidance, and technical documentation. ## **Support Options Overview** This table compares the support channels by purpose and response time: | **Support Channel** | **Purpose** | **Response Time** | | - | - | - | | **AI-Powered Chat** | Automated responses, documentation guidance | Instant | | **Discord Community** | Peer support, community discussions | Community-driven | | **Chat Support** | Personalized assistance for complex issues | 24–48 business hours | | **Self-Service Docs** | Product guides, API reference, tutorials | Self-paced | Choose a channel based on the complexity of your question and the response time you need. For more help, open the **Help and support** menu in the dashboard. # Countries Eligible for Payment Acceptance Source: https://docs.dodopayments.com/miscellaneous/list-of-countries-we-accept-payments-from The countries and territories, with ISO codes, from which Dodo Payments accepts customer payments for SaaS and digital products. | # | ISO Code | Country Name | | - | - | - | | 1 | AD | Andorra | | 2 | AE | United Arab Emirates | | 3 | AG | Antigua and Barbuda | | 4 | AI | Anguilla | | 5 | AL | Albania | | 6 | AM | Armenia | | 7 | AO | Angola | | 8 | AR | Argentina | | 9 | AS | American Samoa | | 10 | AT | Austria | | 11 | AU | Australia | | 12 | AW | Aruba | | 13 | AX | Åland Islands | | 14 | AZ | Azerbaijan | | 15 | BA | Bosnia and Herzegovina | | 16 | BB | Barbados | | 17 | BD | Bangladesh | | 18 | BE | Belgium | | 19 | BF | Burkina Faso | | 20 | BG | Bulgaria | | 21 | BH | Bahrain | | 22 | BI | Burundi | | 23 | BJ | Benin | | 24 | BL | Saint Barthélemy | | 25 | BM | Bermuda | | 26 | BN | Brunei Darussalam | | 27 | BO | Bolivia | | 28 | BQ | Caribbean Netherlands | | 29 | BR | Brazil | | 30 | BS | Bahamas | | 31 | BT | Bhutan | | 32 | BV | Bouvet Island | | 33 | BW | Botswana | | 34 | BZ | Belize | | 35 | CA | Canada | | 36 | CC | Cocos (Keeling) Islands | | 37 | CG | Republic of the Congo | | 38 | CH | Switzerland | | 39 | CI | Côte d'Ivoire | | 40 | CK | Cook Islands | | 41 | CL | Chile | | 42 | CM | Cameroon | | 43 | CN | China | | 44 | CO | Colombia | | 45 | CR | Costa Rica | | 46 | CV | Cape Verde | | 47 | CW | Curaçao | | 48 | CX | Christmas Island | | 49 | CY | Cyprus | | 50 | CZ | Czech Republic | | 51 | DE | Germany | | 52 | DJ | Djibouti | | 53 | DK | Denmark | | 54 | DM | Dominica | | 55 | DO | Dominican Republic | | 56 | DZ | Algeria | | 57 | EC | Ecuador | | 58 | EE | Estonia | | 59 | EG | Egypt | | 60 | EH | Western Sahara | | 61 | ER | Eritrea | | 62 | ES | Spain | | 63 | ET | Ethiopia | | 64 | FI | Finland | | 65 | FJ | Fiji | | 66 | FK | Falkland Islands | | 67 | FM | Micronesia | | 68 | FO | Faroe Islands | | 69 | FR | France | | 70 | GA | Gabon | | 71 | GB | United Kingdom | | 72 | GD | Grenada | | 73 | GE | Georgia | | 74 | GF | French Guiana | | 75 | GG | Guernsey | | 76 | GH | Ghana | | 77 | GI | Gibraltar | | 78 | GL | Greenland | | 79 | GM | Gambia | | 80 | GN | Guinea | | 81 | GP | Guadeloupe | | 82 | GQ | Equatorial Guinea | | 83 | GR | Greece | | 84 | GS | South Georgia and the South Sandwich Islands | | 85 | GT | Guatemala | | 86 | GU | Guam | | 87 | GW | Guinea-Bissau | | 88 | GY | Guyana | | 89 | HK | Hong Kong | | 90 | HM | Heard Island and McDonald Islands | | 91 | HN | Honduras | | 92 | HR | Croatia | | 93 | HU | Hungary | | 94 | ID | Indonesia | | 95 | IE | Ireland | | 96 | IL | Israel | | 97 | IM | Isle of Man | | 98 | IN | India | | 99 | IO | British Indian Ocean Territory | | 100 | IQ | Iraq | | 101 | IS | Iceland | | 102 | IT | Italy | | 103 | JE | Jersey | | 104 | JM | Jamaica | | 105 | JO | Jordan | | 106 | JP | Japan | | 107 | KE | Kenya | | 108 | KG | Kyrgyzstan | | 109 | KH | Cambodia | | 110 | KI | Kiribati | | 111 | KM | Comoros | | 112 | KN | Saint Kitts and Nevis | | 113 | KR | South Korea | | 114 | KW | Kuwait | | 115 | KY | Cayman Islands | | 116 | KZ | Kazakhstan | | 117 | LA | Laos | | 118 | LB | Lebanon | | 119 | LC | Saint Lucia | | 120 | LI | Liechtenstein | | 121 | LK | Sri Lanka | | 122 | LR | Liberia | | 123 | LS | Lesotho | | 124 | LT | Lithuania | | 125 | LU | Luxembourg | | 126 | LV | Latvia | | 127 | MA | Morocco | | 128 | MC | Monaco | | 129 | ME | Montenegro | | 130 | MF | Saint Martin | | 131 | MG | Madagascar | | 132 | MH | Marshall Islands | | 133 | MK | North Macedonia | | 134 | MP | Northern Mariana Islands | | 135 | MQ | Martinique | | 136 | MR | Mauritania | | 137 | MS | Montserrat | | 138 | MT | Malta | | 139 | MU | Mauritius | | 140 | MV | Maldives | | 141 | MW | Malawi | | 142 | MX | Mexico | | 143 | MY | Malaysia | | 144 | MZ | Mozambique | | 145 | MN | Mongolia | | 146 | MO | Macau | | 147 | NA | Namibia | | 148 | NC | New Caledonia | | 149 | NE | Niger | | 150 | NF | Norfolk Island | | 151 | NG | Nigeria | | 152 | NI | Nicaragua | | 153 | NL | Netherlands | | 154 | NO | Norway | | 155 | NP | Nepal | | 156 | NR | Nauru | | 157 | NU | Niue | | 158 | NZ | New Zealand | | 159 | OM | Oman | | 160 | PA | Panama | | 161 | PE | Peru | | 162 | PF | French Polynesia | | 163 | PG | Papua New Guinea | | 164 | PH | Philippines | | 165 | PK | Pakistan | | 166 | PL | Poland | | 167 | PM | Saint Pierre and Miquelon | | 168 | PN | Pitcairn Islands | | 169 | PR | Puerto Rico | | 170 | PT | Portugal | | 171 | PW | Palau | | 172 | PY | Paraguay | | 173 | QA | Qatar | | 174 | RE | Réunion | | 175 | RO | Romania | | 176 | RS | Serbia | | 177 | RW | Rwanda | | 178 | SA | Saudi Arabia | | 179 | SB | Solomon Islands | | 180 | SC | Seychelles | | 181 | SE | Sweden | | 182 | SG | Singapore | | 183 | SH | Saint Helena | | 184 | SI | Slovenia | | 185 | SJ | Svalbard and Jan Mayen | | 186 | SK | Slovakia | | 187 | SL | Sierra Leone | | 188 | SM | San Marino | | 189 | SN | Senegal | | 190 | SR | Suriname | | 191 | ST | São Tomé and Príncipe | | 192 | SV | El Salvador | | 193 | SX | Sint Maarten | | 194 | SZ | Eswatini | | 195 | TC | Turks and Caicos Islands | | 196 | TD | Chad | | 197 | TF | French Southern Territories | | 198 | TG | Togo | | 199 | TH | Thailand | | 200 | TJ | Tajikistan | | 201 | TK | Tokelau | | 202 | TL | Timor-Leste | | 203 | TM | Turkmenistan | | 204 | TN | Tunisia | | 205 | TO | Tonga | | 206 | TR | Turkey | | 207 | TT | Trinidad and Tobago | | 208 | TV | Tuvalu | | 209 | TW | Taiwan | | 210 | TZ | Tanzania | | 211 | UG | Uganda | | 212 | UM | United States Minor Outlying Islands | | 213 | US | United States | | 214 | UY | Uruguay | | 215 | UZ | Uzbekistan | | 216 | VA | Vatican City | | 217 | VC | Saint Vincent and the Grenadines | | 218 | VG | British Virgin Islands | | 219 | VI | U.S. Virgin Islands | | 220 | VN | Vietnam | | 221 | VU | Vanuatu | | 222 | WF | Wallis and Futuna | | 223 | WS | Samoa | | 224 | YT | Mayotte | | 225 | ZA | South Africa | | 226 | ZM | Zambia | > [!TIP] > > You can only accept payments from the 226 countries listed above. We regularly update this list as we expand support to more countries. # Merchant Acceptance Policy Source: https://docs.dodopayments.com/miscellaneous/merchant-acceptance This policy will help you understand the types of businesses we support, the types we restrict or prohibit, and how we enforce our standards. ## Introduction Dodo Payments operates as a Merchant of Record (MoR), providing an all-in-one platform for digital businesses for merchants by acting as their official reseller. As MoR, Dodo Payments assumes responsibility for payment processing, tax compliance, and chargeback handling. To protect the integrity of our platform and our global partnerships, we maintain strict standards for the products we resell on our platform. This policy outlines the kinds of businesses we support, the types we restrict or prohibit, and how we enforce our standards. It is intended to help builders understand how to align with our platform requirements from the start. ## Businesses We Love! We're excited to support legit builders creating digital-first products that are valuable, trustworthy, and easy to deliver. In general, we welcome: 1. SaaS & AI products 2. Digital goods 3. Templates, Plugins & Apps > [!NOTE] > > We assess "value" based on what a customer actually gets and experiences after they buy the product. In general, we're excited about products that do what they promise, are genuinely useful, and feel worth the price to a reasonable customer. Clear functionality, honest descriptions, and a solid end-user experience go a long way. > > On the flip side, products that rely mostly on hype, vague claims, artificial urgency, or heavily repackaged free content create poor customer experiences. If something feels designed to extract payment rather than solve a real problem, we may take a closer look or decide not to support it. > > Our goal here isn't to police creativity, but to ensure our customers walk away feeling safe and satisfied, not misled. We want to back builders who care about what they're putting into the world. If you're ever unsure whether your product fits, please feel free to reach out! We're always happy to talk it through. ## What We Look For If your product is digital, delivered easily, and meets these qualities, we'd love to work with you: * **Legally Compliant:** Your product complies with relevant laws (like consumer protection and data privacy) in the regions you operate. * **Honest and Helpful:** We appreciate products that provide real value to users - things that are helpful, not deceptive or exploitative. * **Community-friendly:** Products should adhere to our policies and ensure a smooth experience for everyone. ## Businesses We Can't Support > [!WARNING] > > This is not an exhaustive list. Dodo Payments reserves the right to update or enforce this policy at any time. We may place your account under review or suspend it immediately if we determine your business model is deceptive, harmful, high-risk, generates excessive refunds or chargebacks, or has been flagged by our payment partners. As your MoR, we're legally and reputationally responsible for what's being sold through our platform. That means we must stay clear of anything that's: 1. **NSFW, Intimacy & Adult content or services** – This includes explicit or suggestive content whether real or AI-generated (e.g., OnlyFans-style platforms, NSFW chatbots, webcam streams, erotic games, sex toys, escort-style services). 2. **Manual Digital Services** – Selling non-automated services via digital platforms. So, selling custom design, development, coaching, freelancing or consulting services via digital platforms isn't allowed. In essence, if the majority of the value sits in the human labour rather than digital systems, it will not be accepted. 3. **Digital products with limited or unclear value** – For example, AI-generated PDFs with little value, thin templates marked up heavily, or clearly unfinished websites sold at premium prices which may lead to customer dissatisfaction. This also includes placeholder or pre-launch offerings such as holding pages, teaser sites, waitlists, or "coming soon" products that do not provide immediate, usable value after purchase. 4. **Physical goods** – We only support digital delivery. Physical goods include merchandise packaged with digital bundles. No T-shirts, mugs, books, supplements, or computer hardware. In-person services: Any service that is delivered in person, even if booking or payment happens online. So no personal training, coaching delivered physically, beauty treatments, repair or maintenance work performed at the customer's location, etc. 5. **Illegal or age-restricted** – Including but not limited to drugs, alcohol, tobacco, vapes, prescription medicines, or content that violates local laws in any region you're targeting. 6. **Restricted by payment and compliance partners** – Some business types may be subject to restrictions under the policies of our payment and compliance partners. If our financial and regulatory partners restrict certain categories, we cannot provide our support. 7. **Financial products, services & advice** – We can't support unlicensed financial tools, investment strategies, wealth-building courses, tax calculators, banking services, escrow services or anything involving stored value, lending, or managing funds. 8. **Official registration or incorporation services** – Services that process or facilitate company registration, government filings, licences, permits, or any other statutory/legal registrations. 9. **Tax Evasion, Shell Entities, or Regulatory Arbitrage** – We can't support products, services, or setups designed to evade taxes, mask ownership, or bypass financial or legal regulations—this includes using fake business entities, misleading jurisdictions, or "gray market" setups. 10. **Legal, accounting, medical, and professional services** – This includes any services that require licensing, certification or regulatory compliance. Examples include advisory work, diagnosis or treatment, document preparation, representation, financial or tax planning, or any expertise-based service that carries regulatory or liability risk. 11. **Travel, Immigration & Visa services** – This includes bookings for commercial airlines, cruises, charter or private flights, and timeshare offerings. Services that offer handling or facilitating Visa or citizenships. 12. **Health & wellness products** – Including diagnostics, weight-loss programs, supplements, or biohacking kits. This entire class of products is incompatible with our MoR obligations even if well-intentioned, or honestly marketed. 13. **Miracle, Misleading, or Unverifiable Claims** – No products making exaggerated or unverifiable claims – e.g., "cures cancer," "reverses aging," "burns fat while you sleep," "make money while you sleep." 14. **Social matching and interaction services** – This includes platforms for real-time person-to-person interactions, similar to random video- or chat-matching services, matchmaking services, dating platforms, AI-generated relationship companions. 15. **Religious or spiritual product or services** – This includes offerings of spiritual guidance, paid prayers, rituals, faith-based counselling, or similar services where users are paying for religious or spiritual interaction or access to a religious or spiritual authority. 16. **Gambling & games of chance** – Including casinos, lotteries, betting, sweepstakes, fantasy sports for cash prizes, or chance-based reward mechanics (such as loot boxes or spins). 17. **Gaming and virtual-goods environments** – This includes games of skill, online games, video games, in-game currencies, digital item sales, game boosters, or private servers - whether official or unofficial. 18. **Virtual asset services** – Crypto-related offerings, Digital wallets, NFTs, DeFi, crypto exchanges, or token launches aren't permitted. 19. **Piracy or IP violations** – Selling things you didn't create or license (e.g., pirated books, software licenses, copy-paste code packs, unauthorized media downloads). 20. **IPTV and streaming access services** – This includes IPTV subscriptions, reseller panels, or tools that provide access to third-party streaming content. 21. **Software resale or license flipping** – Including selling software licenses at a discount, or reselling AI APIs, datasets, or tools without clear rights or authorisation. 22. **Privacy Violations & Surveillance Tech** – We don't allow products that violate user privacy or enable unauthorized surveillance – this includes stalkerware, keyloggers, location tracking without consent, facial recognition tech, face-swap features or tools that scrape or collect personal data without a clear legal basis. 23. **Hosting, servers, and infrastructure services** – This includes VPN, VPS or dedicated servers, hosting plans, cloud compute credits, bandwidth reselling, or any product that provides users with persistent infrastructure or server-level access. 24. **Telecommunication services** – This includes services that offer call SPI, telecom routing, global calling to PSTN, SIM cards, e-SIMs, VoIP services, call/SMS termination, or related telecom operations (licensed or unlicensed). 25. **Spam, mass outreach or scraping tools** – Data privacy violations, including lead scraping, mass outreach or spam tools, and sensitive private information databases. 26. **Proxy, cloaking, or anti-terms tools** – Anything that helps users bypass API rate limits, captcha or authentication limits, platform terms, or geolocation restrictions. 27. **Cheating & manipulation tools** – That means hacks, mods, bots, engagement manipulation, fake reviews, or tools for bypassing platform restrictions, gameplay or API limits. 28. **Donations** – If you're collecting money without delivering something in return, for general support of your platform, we likely can't process it. 29. **Fundraising** – We don't support charity or NGO drives, political or religious donations, personal fundraisers, crowdfunding campaigns, and any contribution-based model without a defined product or service. 30. **Marketplaces, resale model** – If you're selling on behalf of others, operating a multi-vendor platform, or taking funds and forwarding them elsewhere, selling gift or other benefit cards, that's not supported under our MoR structure. 31. **Ticketing & bookings services** – Services that facilitate the sale, resale, or booking of tickets, reservations, or access to events, travel, accommodations. 32. **Weapons, Self-Defense & Violence-Oriented Content** – We don't allow content promoting weapons, combat training, DIY explosives, self-defense tools, or any content that glorifies violence or incites harm. > [!TIP] > > Even if your business isn't listed above, we may still decline to work with you if we believe it poses legal, financial, or reputational risk. This includes high refunds / chargebacks, low-effort, or exploitative offerings. We assess you holistically and reserve the right to refuse or revoke access at our discretion. ## When in Doubt… If your product is pushing boundaries or you're unsure whether it qualifies, we strongly recommend reaching out to us. We'd love to explore ways to help you stay compliant without compromising on your vision. And remember: just because something is technically digital doesn't mean it's automatically okay. If it feels shady, scammy, exploitative, or like something you wouldn't explain confidently to your mother, we probably can't support it. Some business types may fall into a restricted zone - not outright prohibited, but not immediately approved either. These cases will require enhanced due diligence, and we'll take a closer look before making a final decision. This is done on a case to case basis. ## Businesses We Might Support To meet our compliance obligations, some business types require additional review. If your business falls into one of the categories below, we may ask for extra details such as licenses or information about how you operate. While we aim to support a wide range of businesses, approval isn't guaranteed. If approved, access may be limited or adjusted over time in line with the Terms & Conditions, and this policy. Some types of businesses are not outright prohibited but do raise higher compliance or reputational risks. If you operate in one of these spaces, we may ask for extra details (like disclaimers, demo access, or policy links) before approving your account. ### Categories That Often Require Review 1. **AI Content Generation tools (text, image, video, voice)** – No impersonation, scraping, or deepfakes 2. **Marketing & outreach tools** – No spam, scraping, or fake engagement 3. **Resume, hiring, or exam tools** – No impersonation or cheating functionality 4. **Spiritual & Astrology services** – Entertainment only; no claims or predictions 5. **Audio / music / chatbot generators** – No voice cloning, NSFW, IP Infringements or fake claims 6. **E-books and written digital publications** – Including guides, playbooks, reports, or downloadable written content. 7. **Productised services** – A fixed, pre-defined digital product that is delivered the same way for every buyer. This may include limited, repeatable human operational work, as long as it is not customized or consultative. **Unsure if your business qualifies?** If your product operates near the edge of these categories, we encourage you to reach out before applying. We may still be able to support you, especially if you're transparent about your model, actively mitigate risks, and are willing to work within platform guidelines. You can reach out to [compliance@dodopayments.com](mailto:compliance@dodopayments.com) to check if you qualify. ## Fulfillment Channels & Access Delivery Some merchants use Dodo Payments to deliver access on purchase — for example, a license key, a downloadable file bundle, a Discord role, GitHub collaborator access, a Telegram chat or channel invite, a Notion template, or a Framer remix link. Where Dodo Payments fulfils that delivery, the standards in this policy apply both to what is sold on the storefront and to what is actually delivered through the channel. In particular: * Communities, files, repositories, templates, and other resources made available to customers through a Dodo-fulfilled channel must align with the merchant's disclosed product and with this policy. * A community, file bundle, repository, or template that delivers material misaligned with the disclosed product, or that contains content that would itself be ineligible under this policy (for example, adult content, piracy or unauthorised resale, deceptive claims, unlicensed financial advice, or weapons-related content), is treated as a policy breach regardless of how the storefront is positioned. * Continued use of these channels to deliver access is conditioned on ongoing alignment with this policy. Material drift between the advertised product and the gated content may result in account review, restriction, or closure under our enforcement process. This applies whether the channel is created and operated by the merchant or by a third party. ## Accepted Countries & Territories > [card] [Accepted Countries & Territories](/miscellaneous/accepted-countries-and-territories) > > View the full list of countries and territories where Dodo Payments supports merchant accounts and payouts. ## Enforcement We take violations of our merchant policy seriously. If we determine that a merchant has onboarded in breach of this policy or our terms — including by misrepresenting their business, attempting to bypass restrictions, or engaging in prohibited activities — Dodo Payments may take appropriate action. ### Enforcement Actions May Include: * Permanent account suspension * Immediate halt of transactions and platform access * Withholding of payouts or reversal of settled funds * Refunding all transactions processed * Fines or penalties in proportion to losses, reputational harm, or downstream risk (up to USD 425,000) * Reporting to card networks, financial partners, or regulators where required These measures may be taken without prior notice in cases of material breach or imminent platform risk. ### Examples of Policy Breach The following may trigger investigation or enforcement: 1. Misclassifying your business or products to bypass category restrictions. 2. Using proxy merchants, sub-accounts, or account takeovers to avoid enforcement. 3. Selling or promoting products that are deceptive, harmful, or violate our prohibited content rules. 4. Failing to disclose essential onboarding information (e.g., website mismatch, incorrect entity type). 5. Suspicious or unusual volume of transactions. 6. High volume of refunds, disputes, or customer complaints. 7. Actions or transactions that have been flagged by our payment, financial, or regulatory platforms. 8. Requests by legal authorities upon receipt of relevant legal order. 9. Reports of fraudulent activities flagged by our regulatory and compliance partners, and customer reports. 10. Any other material breaches of our platform policies or violations of law as applicable 11. Delivering, through a Dodo-fulfilled access channel (for example, a license key, downloadable file, Discord, Telegram, GitHub, Notion, or Framer integration), content or material that is misaligned with the disclosed product or that is otherwise ineligible under this policy. ### Appeals & Resolution If you believe enforcement was applied in error, you may submit a request for review. Please note that reviews are considered on a one-time basis only. The appeal review decision will be final. In some cases, we may allow corrective action or resubmission for review. Voluntary disclosure of potential issues may be considered favorably. You can reach out to **[compliance@dodopayments.com](mailto:compliance@dodopayments.com)** to initiate the review process. # Review & Monitoring Policy Source: https://docs.dodopayments.com/miscellaneous/review-monitoring-policy How Dodo Payments monitors merchant activity to protect customers, partners, and the payment ecosystem. ## Introduction At Dodo Payments, we act as a Merchant of Record (MoR), managing payment processing, invoicing, taxes, refunds, and disputes on behalf of the businesses that use our platform. To safeguard customers, businesses, and partners, we operate a structured monitoring program. This program ensures that accounts on our platform remain compliant with card network rules, applicable laws, and our [Merchant Acceptance Policy](/miscellaneous/merchant-acceptance). ## Purpose Our monitoring framework is designed to protect both businesses and customers. By identifying and addressing potential risks early, we help ensure a trusted and reliable payment environment. ## Monitoring Approach We combine automated checks with human review to maintain oversight of business activity. Reviews focus on: 1. Compliance with our [Merchant Acceptance Policy](/miscellaneous/merchant-acceptance) 2. Consistency between what is disclosed at onboarding and what is offered live 3. Compliance with card network rules, sanctions, and applicable laws 4. Customer experience signals such as refunds and disputes 5. Use of approved brands, domains, and product lines 6. Where merchants use Dodo Payments to deliver access on purchase — for example, via license keys, downloadable files, or invites to Discord, Telegram, GitHub, Notion, or Framer — alignment between the disclosed product and what is actually delivered through these channels. ## When Reviews Occur Reviews take place at key points in the lifecycle: 1. **Activation & First Transaction** – to confirm that products and checkout experiences match what was disclosed. 2. **Before First Payout** – to complete compliance checks and validate fulfillment. 3. **Ongoing Triggers** – when significant changes occur, such as new domains, product shifts, addition or material change to fulfillment channels (such as Discord, Telegram, GitHub, Notion, or Framer integrations), unusual transaction patterns, or rising disputes / refunds. 4. **Periodic Reviews** – regular monitoring to help ensure continued compliance. ## Outcomes of Reviews Following a review, possible outcomes include: 1. **Continued support** – your account remains active on the platform. 2. **Remediation** – we may ask you to correct issues or provide clarifications. 3. **Deboarding** – in cases of prohibited activity, policy violations, or non-response, the account may be closed and payouts withheld in line with our enforcement process. ## Customer Protection We take customer complaints, fraud alerts, and refund requests seriously. In such cases, we may contact both the customer and your business. If we don’t receive a response within reasonable timelines, refunds may be processed automatically and your account may be restricted or closed. ## Fulfillment Channel Checks Some merchants use Dodo Payments to provision access to communities, files, repositories, templates, or other resources after purchase. To verify that the product disclosed at onboarding remains aligned with what is actually delivered, we may carry out periodic or for-cause checks of these channels. Checks are scoped to compliance verification. Depending on the situation, a check may include: * Reviewing publicly visible information about the community, repository, or template. * Where the channel is private, requesting access for the limited purpose of confirming alignment with this policy and the Merchant Acceptance Policy. * Reviewing samples of content or materials made available to customers through the channel. These checks are scoped to verifying compliance. We do not monitor individual customers or their messages, do not retain personal data observed in these channels beyond what is necessary to record a compliance finding, and do not act as a content moderator on behalf of the merchant. Where access is required and is not provided within reasonable timelines, the matter is treated as unresolved under our enforcement process. Fulfillment channel checks are one input to our broader review program; they do not displace the customer protection, transparency, or enforcement provisions in this policy. ## Transparency & Communication If clarifications are required, we contact you at your registered email address. You’ll have the opportunity to respond and provide context. Where no response is received, accounts may be closed and funds held in line with card network and regulatory requirements. ## Enforcement Violations of our policies, card network rules, or applicable laws may result in: 1. Suspension of payments 2. Account closure 3. Notifications to card networks, partners, or regulators as required ## Commitment to Fairness Our monitoring standards are applied consistently across all businesses. We aim to work collaboratively to resolve issues where possible, while maintaining strong protections for customers and the payment ecosystem. # Security Reporting Policy Source: https://docs.dodopayments.com/miscellaneous/security-policy How to report a security vulnerability in Dodo Payments: what to include in your report, how our team handles it, and the responsible disclosure rules. ## Introduction At Dodo Payments, we take security seriously and appreciate responsible disclosure of vulnerabilities that help us improve our platform. If you discover a security vulnerability, we encourage you to report it to us following the guidelines below. ## Reporting Security Vulnerabilities If you identify a security vulnerability in our platform, contact us at **[pt-team@dodopayments.com](mailto:pt-team@dodopayments.com)** with the following details: * **Description**: A clear and concise explanation of the vulnerability. * **Steps to Reproduce**: Detailed steps to replicate the issue. * **Impact**: The potential risk or harm that could arise from the vulnerability. * **Suggested Mitigations**: (If available) Any recommendations on how to fix the issue. ## How We Handle Reports 1. **Acknowledgment**: Our team will confirm receipt of your report within a reasonable timeframe. 2. **Assessment**: We will review the report and prioritize it based on severity and impact. 3. **Resolution Timeline**: If the issue is already known and logged internally, we will provide an update on its expected resolution. 4. **Follow-up**: We may reach out for additional information or clarification as needed. ## No Monetary Rewards (Bug Bounty Program) Currently, **Dodo Payments does not have an official bug bounty program**. While we deeply appreciate security researchers' efforts, we **do not offer monetary rewards** for vulnerability disclosures. This ensures fairness for all individuals who have reported similar issues in the past. ## Recognition & Appreciation We highly value the contributions of ethical security researchers. While we do not offer financial compensation, we would be happy to send **Dodo Payments goodies/merch** as a token of appreciation for valid security reports. If you are interested, let us know after your report has been reviewed. ## Responsible Disclosure To ensure a responsible and ethical reporting process, adhere to the following: * **Do not publicly disclose** vulnerabilities until our team has had a reasonable time to address them. * **Do not exploit** the vulnerability beyond what is necessary to demonstrate the issue. * **Do not access, modify, or delete** data that does not belong to you. * **Do not perform** any activity that could disrupt our services. ## Contact Us If you have any security concerns or need further assistance, reach out to us at **[pt-team@dodopayments.com](mailto:pt-team@dodopayments.com)**. # Subscription Migration to Dodo Payments Source: https://docs.dodopayments.com/miscellaneous/subscription-migration Move your existing subscriptions and saved cards from Stripe, Paddle, or another processor to Dodo Payments without asking customers to re-enter their cards. A subscription migration moves your active subscribers and their saved cards from your current processor to Dodo Payments. Your customers keep their subscriptions. They don't enter their cards again, and their billing continues on schedule. You never handle card numbers yourself. Your current processor sends the cards to Dodo Payments in an encrypted export, and you send a subscriptions file that links each subscription to its product, customer, and next billing date. > [!WARNING] > > We migrate **saved cards only**. Apple Pay, Google Pay, and other wallet payment methods can't move between processors, so those customers need to add a card again. To start a migration, contact [support](mailto:support@dodopayments.com). A Solutions Engineer guides you through each step. ## Requirements * **PCI DSS compliance**: Your current processor must be able to export card data securely. Dodo Payments is PCI DSS Level 1 compliant. Share our [Attestation of Compliance (AOC)](https://pub-2a89184e4c954b599464449d23f506bb.r2.dev/dodo-payments-pci-dss-aoc.pdf) with your processor if they ask for it. * **Live integration**: Finish your Dodo Payments integration and send new customers to Dodo Payments checkout before the import. This keeps new sign-ups out of the old system. * **Authorization**: You can request a data export from your current processor. This usually needs the account owner. ## How Your Cards Move > [tab] Stripe > > You request a card export from Stripe to Dodo Payments. Stripe's support team handles this request, and Stripe delivers the encrypted export to a secure location that Dodo Payments then retrieves it from. Your Solutions Engineer gives you the details to include in the request. > > This also covers billing platforms that run on Stripe, such as Polar, Lemon Squeezy, and Chargebee. The cards live in the underlying Stripe account. > [tab] Paddle and other processors > > Ask your processor to encrypt the card export with the Dodo Payments PGP public key (see [PGP key](#pgp-key)) and upload it over SFTP to `sftp.dodopayments.com`. Your Solutions Engineer opens SFTP access for this migration as soon as your processor sends its SSH public key. Send your processor [For Your Processor](#for-your-processor); it has everything they need. > > Paddle stores cards with IXOPAY (TokenEx), so the export comes from IXOPAY. IXOPAY runs at most two exports per account: one for most of your customers, and one for the customers added while you switch over. Send new customers to Dodo Payments checkout before you request the first export, so the second one stays small. The card export usually takes around **2 weeks**, depending on your processor's response times. Prepare your products and subscriptions file while you wait. ## Set Up Your Products Make one subscription product in Dodo Payments for each plan and price you bill today, in the dashboard or with the API. Each product has a product ID of the form `pdt_...`, which goes in your subscriptions file. * Make monthly and yearly plans as two separate products. * Set the billing interval and trial on the product, not in the file. * **The import charges the full product price.** It doesn't apply coupons, discounts, or promotions. If a customer pays a reduced price today (a coupon, a legacy rate, or a discount), make a product at that exact price and use it for that customer. Tell your Solutions Engineer about these customers so they can confirm the amount. * **Set a long total subscription term**, for example 20 years (the maximum). The term starts on the original subscription start date (`started_at`), not on the import date. A short term makes the import refuse the subscription. ## Prepare `subscriptions.csv` Send one CSV file with one subscription per row. If a customer has two subscriptions, use two rows and repeat the customer's details on each. A column marked **Yes** is required. **Conditional** means it's required only in the case described. Keep every column in the header row, even optional ones, and leave the value empty when it doesn't apply. > [tab] Stripe > > | Column | Required | Description | > | - | - | - | > | `stripe_subscription_id` | Yes | Your Stripe subscription ID (`sub_...`). The final report maps it to the new Dodo Payments ID. | > | `stripe_customer_id` | Yes | Your Stripe customer ID (`cus_...`). This is how each subscription finds its card. Read the warning below if you bill through a platform on Stripe. | > | `product_id` | Yes | The Dodo Payments product ID (`pdt_...`) for this plan. | > | `customer_name` | Yes | Full name or company name. | > | `customer_email` | Yes | Email for receipts, invoices, and the customer portal. | > | `customer_phone` | No | E.164 format, for example `+14155550123`. It can improve card authorization. | > | `billing_country` | Yes | ISO 3166-1 alpha-2 code, for example `US`, `GB`, or `DE`. It controls tax and card authorization. | > | `tax_id` | No | The customer's tax ID, for example an EU VAT ID. When it's valid, invoices apply the reverse charge where applicable. See [B2B Payments](/features/b2b-payments). | > | `customer_business_name` | No | The company name shown on invoices. Requires `tax_id`. See [B2B Payments](/features/b2b-payments). | > | `first_billing_date` | Yes | The date of the first charge on Dodo Payments, which is the next renewal date. For a trial, use the date the trial ends. | > | `quantity` | Yes | Number of units or seats, `1` or more. | > | `status` | Yes | One of `active`, `trialing`, `past_due`, `unpaid`, `paused`, `canceled`. Subscriptions in `incomplete` or `incomplete_expired` can't be imported, because they never set up on Stripe. | > | `previous_billing_date` | Yes | The date of the last successful charge. | > | `started_at` | Yes | The date the subscription first started. Use the true date, even if it's years ago. | > | `card_last4` | Conditional | The last four digits of the card this subscription charges. Required only when the customer has more than one saved card. | > | `paused_at` | Conditional | Required when `status` is `paused`. | > | `cancelled_at` | Conditional | Required when `status` is `canceled`. | > > ```csv theme={null} > stripe_subscription_id,stripe_customer_id,product_id,customer_name,customer_email,customer_phone,billing_country,tax_id,customer_business_name,first_billing_date,quantity,status,previous_billing_date,started_at,card_last4,paused_at,cancelled_at > sub_01,cus_01,pdt_pro_monthly,Jane Doe,jane@example.com,+14155550123,US,,,2026-04-01T00:00:00Z,1,active,2026-03-01T00:00:00Z,2025-06-15T00:00:00Z,,, > sub_02,cus_02,pdt_pro_annual,Acme Inc,billing@acme.com,,US,,,2027-01-15T00:00:00Z,5,active,2026-01-15T00:00:00Z,2024-01-15T00:00:00Z,4242,, > sub_03,cus_03,pdt_pro_monthly,Muster GmbH,billing@example.com,,DE,DE123456789,Muster GmbH,2026-05-01T00:00:00Z,1,active,2026-04-01T00:00:00Z,2025-03-10T00:00:00Z,,, > ``` > > The first customer has one saved card, so `card_last4` is empty. The second has more than one, so `card_last4` picks the card the subscription charges. The third customer is a business, so the row has a `tax_id` and a `customer_business_name`. The first two have neither, so both columns are empty. > > > [!WARNING] > > > > **Use the Stripe customer ID, not a platform ID.** Polar, Lemon Squeezy, Paddle, Chargebee, and other platforms that run on Stripe give each customer their own ID. Cards are matched on the Stripe `cus_...` value, so a platform ID matches nothing. > > > > * Wrong (a platform ID, such as a raw UUID): `11111111-2222-3333-4444-555555555555` > > * Right (the Stripe ID): `cus_Qa1b2C3d4E5f6G7` > > > > Your platform can usually export the Stripe customer ID for each subscription. If you can't find it, ask your Solutions Engineer for help mapping it. > > ### `card_last4` Rules > > * Leave it empty when the customer has only one saved card. > * Fill it in when the customer has more than one saved card, so the import knows which card the subscription charges. > * Format the column as text in your spreadsheet. A card ending in `0042` loses its leading zero in a number column. A stripped leading zero still matches, but text keeps the value clear. > [tab] Paddle > > | Column | Required | Description | > | - | - | - | > | `paddle_subscription_id` | Yes | Your Paddle subscription ID (`sub_...`). The final report maps it to the new Dodo Payments ID. | > | `paddle_customer_id` | Yes | Your Paddle customer ID (`ctm_...`). It must match the customer in the card export. | > | `card_token` | Yes | The reference Paddle uses for this subscription's saved card. It must match the card export. | > | `product_id` | Yes | The Dodo Payments product ID (`pdt_...`) for this plan. | > | `customer_name` | Yes | Full name or company name. | > | `customer_email` | Yes | Email for receipts, invoices, and the customer portal. | > | `customer_phone` | No | E.164 format, for example `+14155550123`. It can improve card authorization. | > | `billing_country` | Yes | ISO 3166-1 alpha-2 code, for example `US`, `GB`, or `DE`. It controls tax and card authorization. | > | `tax_id` | No | The customer's tax ID, for example an EU VAT ID. When it's valid, invoices apply the reverse charge where applicable. See [B2B Payments](/features/b2b-payments). | > | `customer_business_name` | No | The company name shown on invoices. Requires `tax_id`. See [B2B Payments](/features/b2b-payments). | > | `first_billing_date` | Yes | The date of the first charge on Dodo Payments, which is the next renewal date. For a trial, use the date the trial ends. | > | `quantity` | Yes | Number of units or seats, `1` or more. | > | `status` | Yes | One of `active`, `trialing`, `past_due`, `paused`, `canceled`. | > | `previous_billing_date` | Yes | The date of the last successful charge. | > | `started_at` | Yes | The date the subscription first started. Use the true date, even if it's years ago. | > | `paused_at` | Conditional | Required when `status` is `paused`. | > | `cancelled_at` | Conditional | Required when `status` is `canceled`. | > > ```csv theme={null} > paddle_subscription_id,paddle_customer_id,card_token,product_id,customer_name,customer_email,customer_phone,billing_country,tax_id,customer_business_name,first_billing_date,quantity,status,previous_billing_date,started_at,paused_at,cancelled_at > sub_01,ctm_01,card_01,pdt_pro_monthly,Jane Doe,jane@example.com,+14155550123,US,,,2026-04-01T00:00:00Z,1,active,2026-03-01T00:00:00Z,2025-06-15T00:00:00Z,, > sub_02,ctm_02,card_02,pdt_pro_annual,Acme Inc,billing@acme.com,,US,,,2027-01-15T00:00:00Z,5,active,2026-01-15T00:00:00Z,2024-01-15T00:00:00Z,, > sub_03,ctm_03,card_03,pdt_pro_monthly,Muster GmbH,billing@example.com,,DE,DE123456789,Muster GmbH,2026-05-01T00:00:00Z,1,active,2026-04-01T00:00:00Z,2025-03-10T00:00:00Z,, > ``` > > The third customer is a business, so the row has a `tax_id` and a `customer_business_name`. The first two have neither, so both columns are empty. > > Each subscription is matched to its card by `paddle_subscription_id` first, then by `card_token`. A row is refused if its `card_token` differs from the card that matched, or if that card belongs to a different `paddle_customer_id`. These checks stop a charge on the wrong card. > > > [!WARNING] > > > > **Use the Paddle IDs, not your internal IDs.** Your own database may hold a different ID for the same customer, and that ID won't match the card export. > > > > * Wrong (an internal ID, such as a raw UUID): `11111111-2222-3333-4444-555555555555` > > * Right (the Paddle ID): `ctm_01hxyzab12cd34ef56gh78` > > > > Export the IDs from the same Paddle account that sends the cards. ### Format Rules * CSV, UTF-8 encoded, comma separated. * Use the exact column names above in the header row, lowercase `snake_case`. * Write dates in ISO 8601 UTC, for example `2025-04-01T00:00:00Z`. Paddle files also accept `2025-04-01` and `2025-04-01 00:00:00`. * `first_billing_date` must be in the future and after `previous_billing_date`. * Don't put the price or currency in the file. They come from the product. * Leave `customer_business_name` empty when `tax_id` is empty. A business name needs a tax ID, as described in [B2B Payments](/features/b2b-payments). * Wrap a value containing a comma, quote, or new line in double quotes, and write an embedded quote twice (`""`). * Don't put card numbers, expiry dates, or card tokens from Stripe in the file. ## How the Import Runs Your data goes through three checks before anything is written. Nothing is charged at import. **1. Card export check** The card export is decrypted and checked for structure and card validity. You get a summary of how many cards are ready and which ones are skipped, such as expired cards. **2. Card dry run** The full card import is rehearsed without saving any card. This confirms every card can be imported. **3. Subscriptions check and dry run** Your `subscriptions.csv` is checked against the format rules and joined to the cards, then every row is rehearsed against your products and account without creating anything. **4. Approval and import** A second person on the Dodo Payments team approves, and the cards and subscriptions are imported. > [!WARNING] > > **The import is all or nothing.** If any row fails a check, the import doesn't start. Your Solutions Engineer sends you the rows that failed and why. You correct the file and send it again, and it goes through every check again. If a row is refused during the import itself, the import stops at that row. Once the problem is fixed, it continues from where it stopped, and rows already imported aren't imported twice. ## Renewal Options You choose how migrated subscriptions renew. The choice applies to the whole import. | Option | What happens | | - | - | | **Renews automatically** | Each subscription is charged on its `first_billing_date`, then renews on the product's interval. Cancel the subscription at your old processor so it doesn't renew on this date (see [After the Import](#after-the-import)). | | **On demand** | No automatic charge. You charge each subscription yourself when you're ready. See [On-demand subscriptions](/developer-resources/ondemand-subscriptions). | ## After the Import > [!WARNING] > > **Stop billing at your old processor before the first Dodo Payments charge.** The import doesn't touch your subscriptions at Stripe, Paddle, or any other processor. If they stay active, your customers are charged twice: once by your old processor and once by Dodo Payments on each subscription's `first_billing_date`. > > Before the go-live date you agree with your Solutions Engineer, set every migrated subscription at your old processor to cancel at the end of its current billing period. The cancellation must take effect on or before the subscription's `first_billing_date`, so the old processor doesn't renew it that day. If a current period ends after `first_billing_date`, cancel that subscription at once, or ask your Solutions Engineer to move its date. Don't delete the customers or their saved cards. Cancelling the subscription is enough. * You receive a report that maps each old subscription ID (`stripe_subscription_id` or `paddle_subscription_id`) to its new Dodo Payments `subscription_id`. Use it to update your records. * You agree a go-live date with your Solutions Engineer, and the first billing cycle is monitored. * We recommend checking a sample of migrated subscriptions in your dashboard. ### Existing Customers If a customer already exists in your Dodo Payments account, for example from an earlier migration, the import may create a new customer record for the subscription, linked to the migrated card. You then see two records for that person. This is expected. The check before the import lists these customers, so tell your Solutions Engineer if you want them handled differently. ## Migratable Data | Data | Migrated | Notes | | - | - | - | | Card numbers and expiry dates | Yes | Sent by your processor in the encrypted export | | Customer name, email, phone, and country | Yes | From your subscriptions file | | Tax ID and business name | Yes | Optional columns in your subscriptions file. See [B2B Payments](/features/b2b-payments) | | Subscriptions | Yes | Product, quantity, status, and billing dates | | Apple Pay, Google Pay, and other wallets | No | Can't move between processors | | Coupons and discounts | No | Use a product at the discounted price | | Payment history | No | Export it from your current processor for your records | ## PGP Key Card exports sent over SFTP must be encrypted with the Dodo Payments PGP public key. Share it with your processor. > [accordion] Dodo Payments PGP Public Key > > ``` > -----BEGIN PGP PUBLIC KEY BLOCK----- > > mQINBGflFWEBEADA8IaeXNc9ekoyWGH6TBi3PvazDTXH9MeAIcq8tcXPjr+aDTA7 > QE0oJbnH+Zi6nP6Mh20c4bftzC890/QJmk6shdgpQuCd/80yC1TT5tyqKDV517WQ > B7A8CmbonuZ//jS+jWrekpbLFMzoro1ZkeCRDNbhF3KSrMv1UOugBHPAchtkTur8 > 2k+HtIFKVW8xQ3/nrnKGeNWdHMp3y6yATjXm0E2y9Oq83CQ1TkwwB+MI0Y/uZaXv > 3016pOos3lQFXqVAvShDRzMXxvPHc902QS47v0gSj5wsVWv3g5QP/TlAE6Pvua18 > 78xoROo9RLwovMmX372JeZdqKgIV+BmxlOrGCDcNOY4Flz+NRJuKbVk0UmD8f1tW > NL5x/r36ZNnBbzohqcwp5dktiRn0MDHUsvv8StOkbFqQ+HyYSzoO1dRYGkz5bkfI > urv4hd26I4rdu8GTpEaBcd0rx1NcNT2lbqrcTE7rux3c3Vf1QD6lSj+VbJBxxyxO > +fgeoVNpAi4Zfyls+VYCRolVHxxdjh/Zu6iAUrpubpgBxoxwzF3vMVWDPvZahUxY > gt340eRr6KQUpI2TK4iNhTzc4CpYP/eKyC8TavHzpuGap0f7ojNaD1yjPxKJ9HFF > eFde7jtoglvGrdW/GnoTVBFdN4wdcrJ6+Xthlqk5n0CZLKxZzCsnJ+Y00wARAQAB > tFlEb2RvIFBheW1lbnRzIEltcG9ydCBLZXkgKEltcG9ydCBrZXkgZm9yIGNhcmQg > dG9rZW4gbWlncmF0aW9uKSA8cHQtdGVhbUBkb2RvcGF5bWVudHMuY29tPokCVwQT > AQgAQRYhBAfnpp8sSFvzQCZA9mOB38/zSlnMBQJn5RVhAhsDBQkJZgGABQsJCAcC > AiICBhUKCQgLAgQWAgMBAh4HAheAAAoJEGOB38/zSlnMLm4QAK1sQxraYnV4OC9l > G0LNUDRKsayJ3+5uW6gbD72NhQ1Q7GpD6J1kmoXO95ZMSV4Ev+PAdBHVnhbl+LTk > JBZTrVszeZfmAr2D0HTdBsqlB8uUISXaffL/a0POWTLRdVzHJbTPtC23SHjW8XFu > 0ixomJxnIXu1iBccEPJTWpjYQbecfK6xMbHYvLQYBCLBWbDfr7hJ3ubnF8izo4W+ > cxYmFS5A4lKs6PHC+MlikFHtKKhDaKT+Zc5c5utcGpPEFUw1vxvQkgabOie6/ufc > EAfzHaFklDvyovfKJ3eOrTRlOG8T0TmoccxjTtx4vboaTcnKoANO0p1G5esjkAWU > 2Bpa/hTaW3YvKBlHEPovm+E4c7OieHIvw3+BS7uyWOmNHgzJcAEVkbJAvRl9X1lQ > LzcOqBIVMyLF5zswRBHtCWHuYsolIO8zMKHmYKV52jR7OkGcZ5ekaqIKVsOmpDCk > Rn7RWubhglOC6e+CNK+2LEQALpDLx05F4uUSmbo0KvQtgnXJHsVsesaO/CVxvdOw > nWv3MyZbhN+EGCKbO3eoTkaM7EHRPEsHa04a+T+TPFel1B7VlTdBikoyNQxyh4a2 > V/ERoKi1qI9DS158lkPkZt90PLhPMVyOFTmTt8ZbZhp1TndmIterWGlYFz8yXb7A > BDeo0Xmu2rmuoG7kEihSwt0UmfMSuQINBGflFWEBEACyXdG9SjXd7dRoJ5bcs64A > Cxea1NZ90x4NWdx0lTy8ruHBSzl2SYDGhDbAAOhVTxZHr1UeDfPBp/urYiENsFeA > Fx2V4Pt2Jj0oBJ6IIHnf1X0U+T6JzVYraaQBHUjXsq4GVoD0bWydQwE6+PSOOZ8R > d7GlsdDl0lM38krkN84BRI/OEfLJaUKFAN9COBnna3bpUwhrvk2o05ItYK/CPoEp > lQAI5mvO7x+kPSsWUCW905TrQuvYuJQvhCZN/2NMn7X5NzhVLLnPW+hyBfkjkWWm > 8GQoH54AADQOKAczkXuSUuLwji+TA2ImAw9FI/S5cIjxG3z4PaAg7zVeZEpjjTWN > 7QQXEMvzDLLXRSjXHsmtWmg//pgvkTxyuzPbNKK7KY9Q+Xyqb0bP5UQKrZ9nRn4l > MMZjC7Kj7eeMv3g/V6wH60Sle0/XW1zSX0djay/Hf99eXcfntlSW0DB2pn9fa8+W > vdmASrLwcYyGjIROxzHIW9uUs4kdJqWatzfT/0uWWwaLayEkd/lCzITn61UAYwVt > YIhY5u9lH0ZuQsxOm267TZrrgDbN9h+z5OVLxW9ylhvXZhMa0w87z8ZTp9wCycki > CNCM1dP0N+lxIPnDu3MztK8u/yelcKpruY5L+gMmVcyDPSYUHDO7g764IdUmSPh4 > VfIeXAsj2r5usa4/+OcxuQARAQABiQI8BBgBCAAmFiEEB+emnyxIW/NAJkD2Y4Hf > z/NKWcwFAmflFWECGwwFCQlmAYAACgkQY4Hfz/NKWcxoIA//edJGWP4Pu70M5IlQ > rLRhi0+hKe0l5VrR1XYcr0EA4qiRQIouab4QvHoxNpn5RGQ+C2agwraiIwIP/nqR > Wz1arWpea8BuSeAJCI0uVQURGexB9ZIJ4oiz8itAiHyjW6x+B4zC9RKe3xGO8KIt > FhtGMYGP+8bZyOUnIU9ZqO+mxHc/wnwCeICzE5TpITrEERbXh0XZJJCLotpss8o8 > 4F0Lb/9VwObCEdxpC6IkKW9GF5WJjmycfdcojaEr26qNSj1KsKRww7ukoVthD4aT > KRM0j3X0UFNz522hBCV/+0+cGMSc5lIRzE+gsXM8vpCW3rmWZj9pMyL5r/RH1FFL > 9N3nFvfjoiuEqQ/DRy3jdwCHXEijjo5ym1KU9AGuo42deI0nrpvzXYSSahKMOb0/ > PbF4YlrtSbXwhIsBfCUX6njvNomu2u4wDs7gv7gyimyetMZ8EwJ3aGvXlD4kHh15 > tIo5NVXXLfslGtoL+27iW4nmoAxV1lOU2c2Wei+lXEc7t6JgeI0NTdqBnYTNHsOZ > f+dti4KGC2Y+6QKhCgvTFHdHpBJj9DzG49C+4E5ZZL3bNdsU5eXaIuJf/KW+eVQB > EZgHVgBRCqwrDD6SpkOT2lzNxfKI5rBV+WCT+hbu83hk2Pd1K7N3JQs1fVFffF37 > 1OSDhXaPYtJnVApUzaCrC5PJCXU= > =nHcw > -----END PGP PUBLIC KEY BLOCK----- > > ``` Before encrypting, check that the key's fingerprint is `07E7 A69F 2C48 5BF3 4026 40F6 6381 DFCF F34A 59CC`. ## For Your Processor Send this section to your processor's migration team. It covers what they need to upload the card export to Dodo Payments. 1. **Send us an SSH public key.** We sign in with keys only, not passwords. Send an `ssh-ed25519`, `ecdsa-sha2-nistp256` (or `nistp384`, `nistp521`), or `ssh-rsa` public key of 2048 bits or more to your Solutions Engineer. Never send the private key. We reply with an SFTP username for this migration. 2. **Encrypt the export** with the [Dodo Payments PGP public key](#pgp-key). Check its fingerprint first. 3. **Check our host key** on the first connection. It must match one of the fingerprints below. 4. **Upload one file**, under its final name, in one session. Your account can upload files but can't download, rename, or delete them, so don't upload to a temporary name first. Then tell your Solutions Engineer. Your SFTP access is for this migration only. It closes as soon as your file arrives, or after 30 days if no file does. A file that isn't encrypted with our PGP key is deleted on arrival; we then send you a new username so you can upload it again, encrypted. For a second export, such as the customers added while the merchant switches over, we also send you a new username. | Setting | Value | | - | - | | Host | `sftp.dodopayments.com` | | Port | `22` | | Username | Sent by your Solutions Engineer, one per migration | | Authentication | SSH public key (`ssh-ed25519`, `ecdsa-sha2-nistp*`, or `ssh-rsa` of 2048 bits or more) | | Host key (ED25519) | `SHA256:bNVJEIvQDpdVCqGBTNnwg7VQ92zHJAetTgU3yjH4Kzw` | | Host key (RSA) | `SHA256:c6ZtiU/pYkUouo636wygbqy/e0LpCw53l4I3Jwy8lVc` | | PGP key fingerprint | `07E7 A69F 2C48 5BF3 4026 40F6 6381 DFCF F34A 59CC` | | PCI DSS | Level 1 service provider, [AOC](https://pub-2a89184e4c954b599464449d23f506bb.r2.dev/dodo-payments-pci-dss-aoc.pdf) | Your processor can check the host key before connecting: ```bash theme={null} ssh-keyscan -t ed25519,rsa sftp.dodopayments.com | ssh-keygen -lf - ``` ## Timeline | Phase | Typical duration | | - | - | | Setup and planning | 1-2 days | | Card export from your processor | \~2 weeks | | Products and subscriptions file | 3-5 days, in parallel with the card export | | Checks and dry runs | 2-3 days | | Approval and import | 1-2 business days | | Go-live and first billing cycle | Agreed with your Solutions Engineer | > [!TIP] > > A migration usually takes **3-4 weeks** end to end. Preparing your products and subscriptions file while the card export is in progress keeps it short. ## Get Started > [card] [Contact Support](mailto:support@dodopayments.com) > > Start your migration and get connected with a Solutions Engineer. > [card] [Migrate other data](/migrate-to-dodo) > > Move products, customers, and discounts with the migration tool. > [card] [Card Data Export](/miscellaneous/card-data-export) > > Move saved cards from Dodo Payments to another processor. # Test Mode vs Live Mode Source: https://docs.dodopayments.com/miscellaneous/test-mode-vs-live-mode Test mode simulates payments without real charges; live mode processes real transactions. Learn what works in each and how to switch. Test mode lets you build and test your integration without processing real payments. Live mode accepts real transactions from customers. Each mode has its own API keys, products, and webhooks. ## Feature Availability | Feature | Test Mode | Live Mode | Environment Dependent | | :- | :-: | :-: | :-: | | Create products | Yes | Yes | Yes | | Generate payment links | Yes | Yes | Yes | | Simulate payments | Yes | No | Yes | | Process real payments | No | Yes | Yes | | Issue refunds | Yes (simulated) | Yes (real) | Yes | | View transaction history | Yes (simulated) | Yes (real) | Yes | | Download invoices | Yes (simulated) | Yes (real) | Yes | | Link bank account | Yes | Yes | No | | Payouts to bank account | No | Yes | Yes | | Simulate failed transactions | Yes | No | Yes | | View analytics | Yes (simulated) | Yes (real) | Yes | | View detailed reports | Yes (simulated) | Yes (real) | Yes | | Customize invoice templates | Yes | Yes | No | | Generate API keys | Yes | Yes | Yes | | Real-time fraud detection | No | Yes | Yes | | Cart value limit enforced | No | Yes | No | | Access support | Yes | Yes | No | | Create webhooks | Yes | Yes | Yes | | Business profile | Yes | Yes | No | | Account settings | Yes | Yes | No | | Create multiple businesses | Yes | Yes | No | | Payout compliance | Yes | Yes | No | | Send customer emails | Yes (limited, see [Emails in Test Mode](#emails-in-test-mode)) | Yes | Yes | ### Environment Dependent vs Independent **Environment dependent** features keep separate data in each mode. A change in one mode doesn't affect the other. **Environment independent** features share one set of data across both modes. Your account settings, business profile, bank account, and verification documents are the same in test and live mode, so a change in either mode applies to both. ## API Endpoints Use these hostnames to route requests to the correct environment: * **Test Mode:** `https://test.dodopayments.com` * **Live Mode:** `https://live.dodopayments.com` Most SDKs select the environment with a client option instead of a base URL, for example `environment: 'test_mode'` in TypeScript. The C# SDK takes the test mode base URL instead. See [SDKs](/developer-resources/dodo-payments-sdks). ## How Modes Work In test mode, every transaction is simulated and no money moves. Use the test cards, UPI IDs, and other credentials in [Testing Process](/miscellaneous/testing-process) to simulate successful and failed payments. That page also has a video of a complete test payment. Test credentials work only in test mode. Live mode is available as soon as you sign up. Live payments and payouts turn on after your account passes [Account Verification](/miscellaneous/verification-process). Products, API keys, and webhooks belong to the mode you create them in. To reuse a product, open it in test mode and copy it to live mode. The copy keeps the product's details. To build a whole catalog in both modes from one configuration, use the [Terraform provider](/developer-resources/terraform-provider#promoting-changes-from-test-mode-to-live-mode). Test mode API keys start with `dodo_test_` and live mode keys start with `dodo_live_`. A test mode API key doesn't authenticate against `live.dodopayments.com`, and a live key doesn't authenticate against `test.dodopayments.com`. A prefixed key sent to the other environment returns `401` with a message that names the mismatch. To receive test mode webhooks on your local machine while you develop, forward them with the [CLI webhook listener](/developer-resources/sdks/cli#listen-for-webhooks) (`dodo wh listen`). ## Subscriptions in Test Mode Test mode subscriptions renew on their billing schedule, the same way live subscriptions do. Each renewal creates a simulated payment and delivers webhooks to your test mode endpoints. It can also send `[TEST MODE]` customer emails. No money moves. Renewals continue after you finish testing. As a result, new test mode payments can appear weeks after your last test, even when nobody on your team has signed in. If you see a test mode payment that you don't recognize, check its `subscription_id`. A payment that belongs to a subscription you created during earlier testing is a renewal. To stop these renewals, cancel each test subscription that you no longer need. With your test mode API key, call [Update Subscription](/api-reference/subscriptions/patch-subscriptions) and set `status` to `cancelled`. ## Emails in Test Mode Test mode sends real customer emails to the real recipient address, so use addresses you control. Each test mode subject starts with `[TEST MODE]`. A business can send up to 100 test mode emails per week. To stop test mode customer emails, turn off **Test Mode Emails** in **Settings → Communication → Email**. Live mode emails are not affected. See [Test Mode Emails](/features/communication-preferences#test-mode-emails) and [Customer Email Logs](/features/email-logs#test-mode). ## Switching Between Modes To switch modes, use the **Live Mode** switch in the dashboard sidebar. Use the API keys that belong to the mode you're working in. ## Next Steps > [card] [Testing Process](/miscellaneous/testing-process) > > Test cards, UPI, BNPL, wallets, and bank debits. > [card] [Account Verification](/miscellaneous/verification-process) > > Enable live payments and payouts. # Testing Process Source: https://docs.dodopayments.com/miscellaneous/testing-process Test your integration with test cards, UPI IDs, BNPL data, and digital wallets. Simulate payments, refunds, and failures without real charges. Use the test credentials on this page to simulate successful, declined, and failed payments in test mode. No money moves, and no real account is charged. To see a complete test payment, watch this video. [Test Transaction | Dodo Payments](https://www.youtube.com/embed/5CcUSE4L_cg) > [card] Full API Access > > Every API endpoint is available in test mode. > [card] Webhook Testing > > Webhooks fire for test transactions the same way as in production. > [!WARNING] > > Test credentials work only in test mode. In live mode, a payment made with a test credential fails. ## Test Cards Use these card numbers to simulate successful and declined payments across different regions. > [tab] Successful Payments > > | Region | Brand | Card Number | Expiry | CVV | > | :- | :- | :- | :- | :- | > | US | Visa | `4242424242424242` | 06/32 | 123 | > | US | Mastercard | `5555555555554444` | 06/32 | 123 | > | India | Visa | `4576238912771450` | 06/32 | 123 | > | India | Mastercard | `5409162669381034` | 06/32 | 123 | > [tab] Declined Payments > > | Region | Brand | Card Number | Scenario | Error Code | > | :- | :- | :- | :- | :- | > | US | Visa | `4000000000000002` | Generic decline | `GENERIC_DECLINE` | > | US | Visa | `4000000000009995` | Insufficient funds | `INSUFFICIENT_FUNDS` | > | India | Visa | `4706131211212123` | Generic decline | `GENERIC_DECLINE` | > | India | Mastercard | `5105105105105100` | Generic decline | `GENERIC_DECLINE` | > > When a test card declines, the payment's `error_code` and `error_message` reflect the scenario above. Look up any code in the [Transaction Failures](/api-reference/transaction-failures) reference for its meaning and recommended action. See [Handle Payment Failures](/developer-resources/handle-payment-failures) for handling declines in your integration. > [tab] Subscription Renewal Failures > > | Card Number | Expiry | CVV | > | :- | :- | :- | > | `4000000000000341` | 12/34 | 123 | > > Use this card to test subscription renewal, upgrade, and downgrade failures. A subscription that uses this card is declined at its next charge, so you can test retries, customer notifications, and your failure handling. For all test cards, use expiry date **06/32** (or **12/34**) and CVV **123**. ### Testing Renewal Failures **1. Create a test subscription** Create a subscription with your test API keys using a success test card (for example, `4242424242424242`). The initial charge should succeed and the subscription should become active. **2. Update the payment method** Open the [Customer Portal](/features/customer-portal), find the subscription, and click **Update Payment Method**. Enter the failure test card `4000000000000341` (Expiry: `12/34`, CVV: `123`) and save it. **3. Advance the next billing date (optional)** To trigger renewal without waiting for the natural billing cycle, use the Update Subscription API to set `next_billing_date` to a time slightly in the future, such as one minute from now. Replace the example value below. The API rejects a `next_billing_date` that is not in the future, including the current time. The value must be an ISO 8601 / RFC 3339 UTC timestamp (the `Z` suffix is required). ```http theme={null} PATCH /subscriptions/{subscription_id} { "next_billing_date": "2026-05-03T00:00:00Z" } ``` See the [Update Subscription API reference](/api-reference/subscriptions/patch-subscriptions) for details. **4. Verify the failure** On the next billing attempt: * The renewal charge declines on the failure card * The subscription moves to **On-Hold**. If you enabled a [grace period](/features/subscription#grace-period), it moves to **Past Due** first (the `subscription.past_due` webhook carries `past_due_ends_at`), then to **On-Hold** or **Cancelled** when the grace period ends * A `payment.failed` webhook event is delivered * The customer can return to the Customer Portal to update the payment method and retry ## Test UPI UPI testing uses special VPA (Virtual Payment Address) identifiers that simulate different payment outcomes. | Status | UPI ID | | :- | :- | | Success | `success@upi` | | Failure | `failure@upi` | ### Requirements for UPI Testing * Billing country must be set to `IN` * Currency must be `INR` * For non-Indian merchants: Adaptive Currency must be enabled For complete UPI documentation including RBI mandate testing for subscriptions, see the [India Payment Methods](/features/payment-methods/india) page. ## Test Pix Pix testing uses a test CPF (Brazilian tax ID) to simulate the QR code flow. | Field | Test Value | | :- | :- | | CPF | `00000000000` (11 zeros) | ### Requirements for Pix Testing * Billing country must be set to `BR` * Currency must be `BRL` Enter the test CPF when prompted at checkout. A test QR code is generated — scan it with your phone's normal camera (no Pix app needed) and you'll be redirected to a test page where you can simulate the transaction as a success or failure. For complete Pix documentation, see the [Pix](/features/payment-methods/pix) page. ## Test BNPL Buy Now Pay Later providers have specific test data requirements. ### Klarna Test Data Use these details to simulate Klarna payments in test mode: | Field | Approved | Denied | | :- | :- | :- | | Date of Birth | 07-10-1970 | 07-10-1970 | | First Name | Test | Test | | Last Name | Person-us | Person-us | | Email | [customer@email.us](mailto:customer@email.us) | [customer+denied@email.us](mailto:customer+denied@email.us) | | Street | Amsterdam Ave | Amsterdam Ave | | House Number | 509 | 509 | | City | New York | New York | | State | New York | New York | | Postal Code | 10024-3941 | 10024-3941 | | Phone | +13106683312 | +13106354386 | > [!NOTE] > > On USD checkouts, Klarna requires a minimum transaction amount of \$50.01 to appear as a payment option. ### Afterpay Testing **1. Select Afterpay** Choose Afterpay as the payment method in checkout and click Pay. **2. Test successful payment** Use any valid email address and shipping address for successful payments. **3. Test failed authentication** To simulate failure, close the Afterpay modal window on the redirect page. The payment transitions from `requires_customer_action` to `requires_payment_method`. > [!NOTE] > > On USD checkouts, Afterpay requires a minimum transaction amount of \$50.01 to appear as a payment option. For complete BNPL documentation including Billie B2B testing, see the [Buy Now Pay Later](/features/payment-methods/bnpl) page. ## Test Digital Wallets ### Apple Pay **1. Enable test mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. See [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). **2. Add a card to Apple Wallet** Add a real card to your Apple Wallet. In test mode, the card won't be charged. **3. Complete test purchase** Open checkout on an Apple device and complete the Apple Pay flow. > [!WARNING] > > Apple Pay requires HTTPS. It won't appear on `localhost` without proper SSL setup. Domain verification must also be complete. ### Google Pay **1. Join the test card group** [Join the Google Pay test card group](https://groups.google.com/g/googlepay-test-mode-stub-data) to get test cards automatically added to your wallet. **2. Enable test mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. See [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). **3. Complete test purchase** Select one of the test cards in Google Pay to complete the transaction. ### Amazon Pay, Cash App Pay, and RevolutPay Use your test API keys and follow the standard checkout flow. Test transactions are simulated without actual charges. For complete digital wallet documentation including domain verification for Apple Pay, see the [Digital Wallets](/features/payment-methods/digital-wallets) page. ## Test ACH Direct Debit ACH Direct Debit can be tested in test mode by entering test bank details at checkout. **1. Enable test mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. See [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). **2. Set currency and billing address** Set the billing currency to `USD` and the billing address country to `US`. ACH is not offered outside this combination. **3. Use a one-time payment** ACH is not available on subscription checkouts, so test it against a one-time payment. **4. Enter the test bank details** Enter one of the test routing and account number pairs below, then confirm your webhook handler receives the final payment status — ACH payments confirm asynchronously rather than at checkout. ### Test Bank Accounts Use the routing number `110000000` with any of these account numbers: | Account Number | Behavior | | :- | :- | | `000123456789` | The payment succeeds. | | `000222222227` | The payment fails due to insufficient funds. | | `000111111113` | The payment fails because the account is closed. | | `000555555559` | The payment succeeds, then triggers a dispute. | | `000000000009` | The payment stays in processing indefinitely. | For the full list of test accounts, see the [ACH Direct Debit](/features/payment-methods/ach#testing) page. ## Test European Methods European payment methods (iDEAL, Bancontact, EPS, Multibanco) can be tested in test mode. > [!NOTE] > > Multibanco shows a voucher instead of a bank flow. See [Test Multibanco](#test-multibanco). **1. Enable test mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. See [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). **2. Set billing address** Set the billing address country to match the payment method: * `NL` for iDEAL * `BE` for Bancontact * `AT` for EPS * `PT` for Multibanco **3. Set currency** European methods require EUR currency. **4. Complete test flow** Follow the simulated bank authentication flow in the test environment. ### Test Multibanco Use EUR and a `PT` billing address. After you click **Pay**, checkout shows a Multibanco voucher. In test mode, the email you enter decides the result: | Email | Result | | :- | :- | | `succeed_immediately@example.com` | Payment succeeds within a few seconds. | | `expire_immediately@example.com` | Payment fails within a few seconds. | To see the success page, use `succeed_immediately@example.com`, wait a few seconds, and tap **Done**. For the full list of test emails, see the [Europe](/features/payment-methods/europe#multibanco-test-emails) page. ### Test SEPA Direct Debit IBANs SEPA Direct Debit requires EUR and a Eurozone billing address. Use these test IBANs to force a specific outcome: | Test IBAN | Behavior | | :- | :- | | `DE89370400440532013000` | The payment succeeds. | | `DE62370400440532013001` | The payment fails. | | `DE35370400440532013002` | The payment succeeds, then is immediately disputed. | | `DE65370400440002222227` | The payment fails due to insufficient funds. | For the full list of test IBANs, including per-country values, see the [Europe](/features/payment-methods/europe#sepa-test-ibans) page. For complete European payment methods documentation, see the [Europe](/features/payment-methods/europe) page. ## Test Asia-Pacific Wallets GCash, Alipay HK, FPS, and Touch 'n Go are QR code payments that only appear when the billing country and currency match. **1. Enable test mode** Turn off the **Live Mode** switch in the dashboard sidebar, and use API keys created in test mode. See [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). **2. Set billing country and currency** Create a one-time checkout with the matching pair: | Method | Billing Country | Billing Currency | Method Type | | :- | :- | :- | :- | | GCash | `PH` | `PHP` | `gcash` | | Alipay HK | `HK` | `HKD` | `ali_pay_hk` | | FPS | `HK` | `HKD` or `CNY` | `fps` | | Touch 'n Go | `MY` | `MYR` | `touch_n_go` | **3. Select the method and confirm** Select the method and click **Pay**. A QR code opens in a full-screen overlay and the checkout waits for the payment. **4. Verify the checkout behavior** Confirm the method appears only for the matching country and currency and the QR code renders. > [!NOTE] > > Test-mode QR codes are issued by the wallet provider's test environment and may behave differently from a live payment. For complete documentation, see the [Asia-Pacific](/features/payment-methods/asia-pacific) page. ## Testing Best Practices > [accordion] Test all payment scenarios > > Don't test only successful payments. Test declines, cancellations, and edge cases like insufficient funds. > [accordion] Verify webhook handling > > Ensure your webhook endpoints correctly process all event types, especially `payment.succeeded`, `payment.failed`, and subscription events. > > Use the [Dodo Payments CLI](/developer-resources/sdks/cli#webhooks) to test webhooks locally: > > * `dodo wh listen` forwards live test webhooks to your local server > * `dodo wh trigger` sends mock payloads for all supported webhook event types > [accordion] Test on real devices > > For Apple Pay and Google Pay, test on actual iOS and Android devices. Simulators don't fully replicate wallet behavior. > [accordion] Test regional methods with correct addresses > > Regional payment methods (UPI, iDEAL, etc.) require matching billing addresses. A US billing address won't show iDEAL. > [accordion] Verify minimum amounts > > Klarna and Afterpay require a \$50.01 minimum on USD checkouts. Test that they correctly appear or hide based on cart total. ## Related Pages > [card] [Cards](/features/payment-methods/cards) > > Card testing, 3D Secure, and saved payment methods. > [card] [Digital Wallets](/features/payment-methods/digital-wallets) > > Apple Pay, Google Pay, Amazon Pay testing. > [card] [BNPL](/features/payment-methods/bnpl) > > Klarna, Afterpay, and Billie testing. > [card] [India](/features/payment-methods/india) > > UPI and RBI mandate testing. > [card] [Pix](/features/payment-methods/pix) > > Pix testing with test CPF. > [card] [Europe](/features/payment-methods/europe) > > iDEAL, Bancontact, EPS, Multibanco testing. > [card] [Asia-Pacific](/features/payment-methods/asia-pacific) > > GCash, Alipay HK, FPS, and Touch 'n Go testing. > [card] [Webhooks](/developer-resources/webhooks) > > Set up webhooks for test events. > [card] [CLI Webhook Testing](/developer-resources/sdks/cli#webhooks) > > Test webhooks locally with the Dodo Payments CLI. # Add Blocklist Note Source: https://docs.dodopayments.com/api-reference/blocklist/add-blocklist-note post /blocklist/customers/{entry_id}/notes Add a note to a blocklist entry. # Block Customer Source: https://docs.dodopayments.com/api-reference/blocklist/block-customer post /blocklist/customers Add a customer to your blocklist by customer ID or email address. # Get Blocked Customer Source: https://docs.dodopayments.com/api-reference/blocklist/get-blocked-customer get /blocklist/customers/{entry_id} Get a blocklist entry together with its notes. # List Blocked Customers Source: https://docs.dodopayments.com/api-reference/blocklist/list-blocked-customers get /blocklist/customers List the customers on your blocklist, with filters and a total count. # Unblock Customer Source: https://docs.dodopayments.com/api-reference/blocklist/unblock-customer delete /blocklist/customers/{entry_id} Remove a customer from your blocklist. # Update Blocklist Note Source: https://docs.dodopayments.com/api-reference/blocklist/update-blocklist-note patch /blocklist/customers/{entry_id}/notes/{note_id} Edit a note on a blocklist entry. # Create Checkout Session Source: https://docs.dodopayments.com/api-reference/checkout-sessions/create post /checkouts Unified endpoint for creating checkout sessions for all types of billing requirements. # Get Checkout Session Source: https://docs.dodopayments.com/api-reference/checkout-sessions/get-checkouts get /checkouts/{id} Retrieve the status of a specific checkout session by its ID, including the resulting payment ID and payment status. # Preview Checkout Session Source: https://docs.dodopayments.com/api-reference/checkout-sessions/preview post /checkouts/preview Preview a checkout session to calculate pricing, taxes, and totals without creating an actual session. # Create Customer Source: https://docs.dodopayments.com/api-reference/customers/create-customer post /customers Create a new customer in your Dodo Payments account. # Create Customer Portal Session Source: https://docs.dodopayments.com/api-reference/customers/create-customer-portal-session post /customers/{customer_id}/customer-portal/session Create a session of the Customer Portal for a specific customer. # Delete Payment Method Source: https://docs.dodopayments.com/api-reference/customers/delete-payment-method delete /customers/{customer_id}/payment-methods/{payment_method_id} Delete a payment method associated with a customer. Remove a saved payment method from a customer's account. Use this to clean up outdated or unwanted payment methods. > [!WARNING] > > You cannot delete a payment method that is in use by an active subscription. The API returns `409 Conflict` with `Payment method is in use by an active subscription`. Move the subscription to another payment method first using [Update Payment Method](/api-reference/subscriptions/update-payment-method), then delete the old one. A successful delete returns `204 No Content`. ## Use Cases * **Customer request**: Remove a payment method the customer no longer wants on file * **Expired cards**: Clean up payment methods with expired card details * **Security**: Remove compromised payment methods immediately # Get Customer Email Content Source: https://docs.dodopayments.com/api-reference/customers/get-customer-email-body get /customers/{customer_id}/emails/{email_log_id}/body Get one sent email exactly as it was sent, plus the reason it failed when it did. # List Payment Methods Source: https://docs.dodopayments.com/api-reference/customers/get-customer-payment-methods get /customers/{customer_id}/payment-methods List all payment methods associated with a specific customer. # List Customer Wallets Source: https://docs.dodopayments.com/api-reference/customers/get-customer-wallets get /customers/{customer_id}/wallets Retrieve monetary wallet balances associated with a specific customer. Wallets hold real funds in a supported currency that can be applied to invoices and subscription payments. # List Customer Wallet Ledger Entries Source: https://docs.dodopayments.com/api-reference/customers/get-customer-wallets-ledger-entries get /customers/{customer_id}/wallets/ledger-entries List wallet ledger entries (fund additions and deductions) for a specific customer. Supports pagination and currency filter. # List Customers Source: https://docs.dodopayments.com/api-reference/customers/get-customers get /customers Get a list of all customers associated with your account. # Get Customer Detail Source: https://docs.dodopayments.com/api-reference/customers/get-customers-1 get /customers/{customer_id} Get detailed information about a specific customer. # List Customer Credit Entitlements Source: https://docs.dodopayments.com/api-reference/customers/list-customer-credit-entitlements get /customers/{customer_id}/credit-entitlements Get all credit entitlements for a customer along with their current balances. # List Customer Emails Source: https://docs.dodopayments.com/api-reference/customers/list-customer-emails get /customers/{customer_id}/emails Get every transactional email sent to a customer in the last 180 days, with its delivery outcome. # List Customer Entitlements Source: https://docs.dodopayments.com/api-reference/customers/list-customer-entitlements get /customers/{customer_id}/entitlements Get all entitlement grants that have been delivered to, or are still in flight for, a customer. # Update Customer Source: https://docs.dodopayments.com/api-reference/customers/patch-customer patch /customers/{customer_id} Update a customer's information. # Create Customer Wallet Ledger Entry Source: https://docs.dodopayments.com/api-reference/customers/post-customer-wallets-ledger-entries post /customers/{customer_id}/wallets/ledger-entries Add or deduct monetary funds in a customer's wallet. Use entry_type 'credit' to add funds or 'debit' to deduct funds. Wallet balances are real money in a supported currency that can be applied to subscription invoices. # Add Discount Customers Source: https://docs.dodopayments.com/api-reference/discounts/add-discount-customers post /discounts/{discount_id}/customers Idempotently attach customers to a discount's allowlist, which backs a customer_eligibility of specific. # Create Discount Source: https://docs.dodopayments.com/api-reference/discounts/create-discount post /discounts Create a discount for your account. # Delete Discount Source: https://docs.dodopayments.com/api-reference/discounts/delete-discount delete /discounts/{discount_id} Delete a discount from your account. # Get Discount by Code Source: https://docs.dodopayments.com/api-reference/discounts/get-discount-by-code get /discounts/code/{code} Validate and retrieve a discount by its code name (e.g., 'SAVE20') instead of using the internal discount ID. # List Discount Customers Source: https://docs.dodopayments.com/api-reference/discounts/list-discount-customers get /discounts/{discount_id}/customers Get a paginated list of the customers attached to a discount's allowlist. # List Discounts Source: https://docs.dodopayments.com/api-reference/discounts/list-discounts get /discounts Retrieve a list of all discounts associated with your account. # Remove Discount Customer Source: https://docs.dodopayments.com/api-reference/discounts/remove-discount-customer delete /discounts/{discount_id}/customers/{customer_id} Detach a single customer from a discount's allowlist so they are no longer eligible for the discount. # Update Discount Source: https://docs.dodopayments.com/api-reference/discounts/update-discount patch /discounts/{discount_id} Update a discount in your account. # Get Discount Source: https://docs.dodopayments.com/api-reference/discounts/validate-discount get /discounts/{discount_id} Retrieve a discount by its unique discount_id. # Create Entitlement Source: https://docs.dodopayments.com/api-reference/entitlements/create-entitlement post /entitlements Create a new entitlement of any integration type — License Key, Digital Files, Feature Flag, Discord, GitHub, Telegram, Figma, Framer, or Notion. # Delete Entitlement Source: https://docs.dodopayments.com/api-reference/entitlements/delete-entitlement delete /entitlements/{id} Soft-delete an entitlement. Existing grants keep their status and platform access, but are hidden from the Customer Portal. > [!WARNING] > > Deleting an entitlement is a **soft-delete that hides existing grants from the Customer Portal**. It does not revoke platform-side access: > > * Grants linked to the entitlement remain in the database and keep their current `status`. > * Discord roles, GitHub collaborator access, Notion access, Telegram membership, license keys, and digital file URLs stay valid. > * No `entitlement_grant.revoked` webhook is emitted, and `revoked_at` / `revocation_reason` are not set. > > Customers stop seeing these grants in their Customer Portal, but their access on the underlying platform continues until the subscription/payment lifecycle revokes it (cancellation, refund) or you revoke each grant manually via [`DELETE /entitlements/{id}/grants/{grant_id}`](/api-reference/entitlements/revoke-grant). > > If you need to fully cut off access, revoke the grants first, then delete the entitlement. # Delete File Source: https://docs.dodopayments.com/api-reference/entitlements/delete-file delete /entitlements/{id}/files/{file_id} Detach a file from a Digital Files entitlement. The file is removed from the entitlement's digital_file_ids list. # Fulfill License Key Grant Source: https://docs.dodopayments.com/api-reference/entitlements/fulfill-license-key post /grants/{grant_id}/license-key Manually fulfill a pending license-key grant by supplying the key value. Inserts the key, delivers it to the customer by email, and transitions the grant to delivered. > [!NOTE] > > Use this endpoint only for grants created under a License Key entitlement with `fulfillment_mode: manual`. The grant must be in `Pending` status with no key attached. See [Manual Fulfillment](/features/license-keys#manual-fulfillment) and the [Manual License Key Fulfillment Integration Guide](/developer-resources/manual-license-key-fulfillment) for the full flow. # Get Entitlement Source: https://docs.dodopayments.com/api-reference/entitlements/get-entitlement get /entitlements/{id} Retrieve a single entitlement with its resolved integration configuration. For Digital Files entitlements, file metadata and presigned download URLs are populated in the response. # List Customer Grants Source: https://docs.dodopayments.com/api-reference/entitlements/list-customer-grants get /customers/{customer_id}/entitlement-grants List all of a customer's entitlement grants across every entitlement, one row per grant, with optional filters by status and integration type. Feature-flag grants include the typed feature payload. # List Entitlements Source: https://docs.dodopayments.com/api-reference/entitlements/list-entitlements get /entitlements List all entitlements for your business with optional filtering by integration type. # List Grants Source: https://docs.dodopayments.com/api-reference/entitlements/list-grants get /entitlements/{id}/grants List all grants for an entitlement, with optional filters by status and customer ID. Each grant carries the per-customer fulfillment state, including license keys and digital file download URLs where applicable. # Revoke Grant Source: https://docs.dodopayments.com/api-reference/entitlements/revoke-grant delete /entitlements/{id}/grants/{grant_id} Manually revoke a grant. The customer's platform access is removed (for OAuth/bot integrations) and license keys are disabled. Manual revokes use revocation_reason "manual" and are not auto-regranted on subscription renewal. # Update Entitlement Source: https://docs.dodopayments.com/api-reference/entitlements/update-entitlement patch /entitlements/{id} Update an entitlement's name, description, integration configuration, or metadata. # Upload File Source: https://docs.dodopayments.com/api-reference/entitlements/upload-file post /entitlements/{id}/files Upload a file to a Digital Files entitlement. Files are streamed to storage; the maximum size is 500 MiB. The returned file ID is appended to the entitlement's digital_file_ids list. # Error Codes Source: https://docs.dodopayments.com/api-reference/error-codes Reference for Dodo Payments API and business-logic error codes, grouped by category, with triggers, messages, and how to resolve them. ## Overview When a request fails, the Dodo Payments API returns an HTTP status code and a JSON body that names the error. Use this page to find what caused an error and how to resolve it. Each error response includes: * An HTTP status code that gives the general category of the error. * A `code` that identifies the exact error, for example `UNSUPPORTED_COUNTRY`. * A `message` that explains the error in plain language. The `message` can be `null`, for example for internal server errors. Branch your error handling on `code`, not on `message`. Several codes return more than one message, depending on the cause. Use these error codes to: * Debug integration issues. * Handle errors correctly in your application. * Show meaningful feedback to your customers. * Keep your payment processing reliable. > [!NOTE] > > These are **API and business-logic** errors. For **card decline reasons** returned on a failed payment (such as `INSUFFICIENT_FUNDS` or `CARD_DECLINED`), see the [Transaction Failures](/api-reference/transaction-failures) reference instead. ## Standard API Error Codes The API uses these HTTP status codes for errors: | HTTP Status | Name | Description | | - | - | - | | **400** | Bad Request | The request was malformed or contained invalid parameters | | **401** | Unauthorized | The API key is missing or invalid | | **403** | Forbidden | The API key doesn't have permission for the request, or the business can't perform the action | | **404** | Not Found | The requested resource doesn't exist | | **409** | Conflict | The request conflicts with the current state of the resource | | **410** | Gone | The resource has already been deleted or archived | | **413** | Payload Too Large | The request body or uploaded file exceeds the maximum allowed size | | **422** | Unprocessable Entity | The request was well-formed but contained semantic errors | | **429** | Too Many Requests | A rate limit or retry limit was exceeded | | **500** | Internal Server Error | An unexpected error occurred on the Dodo Payments servers | | **502** | Bad Gateway | An upstream service is unavailable. Retry later | | **503** | Service Unavailable | A service is temporarily unavailable. Retry later | ## Error Response Format An error response body contains two fields, `code` and `message`: ```json theme={null} { "code": "UNSUPPORTED_COUNTRY", "message": "Country AI currently not supported" } ``` ## Error Codes Reference The error codes below are grouped by the area of the API they relate to. Each entry lists the condition that triggers the error and the message the API returns. Placeholders such as `{id}` stand for values that the API fills in. ### Authentication & Account * `UNAUTHORIZED` * **Trigger:** The request has no API key or an invalid one (HTTP 401), or the API key lacks the role that the action requires (HTTP 403). A key with a `dodo_test_` or `dodo_live_` prefix sent to the environment of the other mode also returns HTTP 401, with a message that names the mode. * **Message:** You are not authorised to perform this action. For a key of the other mode: This API key is a test mode key. This environment accepts only live mode keys. * `IP_ADDRESS_NOT_ALLOWED` * **Trigger:** The API key has an IP allowlist, and the request comes from an IP address that is not on it (HTTP 403). See [Authentication](/api-reference/introduction#authentication). * **Message:** The IP address `{ip}` is not in the IP allowlist of this API key. * `INSUFFICIENT_PERMISSION` * **Trigger:** The API key doesn't have the access the request needs (HTTP 403). For example, a key with **Read** access to Refunds calls an endpoint that creates a refund. See [Authentication](/api-reference/introduction#authentication) to change a key's access. * **Message:** This API key does not have the required permission. Required: `{resource}:{read|write}`. Scopes: `[{scopes}]` * `MERCHANT_NOT_LIVE` * **Trigger:** A live mode request for a business that does not have live payments enabled (HTTP 403). This covers a business that has only used test mode, and a business whose live payments are not enabled yet because [verification](/miscellaneous/verification-process) is incomplete. Test mode requests are unaffected. * **Message:** Live payments not enabled for merchant * `BUSINESS_ARCHIVED` * **Trigger:** Any customer-facing request for an archived business (HTTP 403). This covers checkout, payment links, the storefront, the Customer Portal, and license key activation. * **Message:** This business is archived and no longer accepts requests ### Payments & Checkout * `CHECKOUT_SESSION_CONSUMED` * **Trigger:** The checkout session has already generated a payment (HTTP 403). Create a new checkout session instead. * **Message:** Payment with the given checkout session has already been generated. * `MANUAL_RETRY_ALREADY_PAID` * **Trigger:** [Manual retry](/features/recovery/manual-retry) of a renewal invoice on which a payment has already succeeded. Sending again would charge the customer twice. * **Message:** A payment on this invoice has already succeeded * `MANUAL_RETRY_HARD_DECLINE` * **Trigger:** Manual retry when the latest failure on the invoice is a hard decline, or carries no classified error code. Another charge on the same card can't succeed, so update the payment method instead. * **Message:** The last failure on this invoice is a hard decline, so retrying cannot succeed *(or)* The last failure on this invoice cannot be classified, so it cannot be retried * `MANUAL_RETRY_IN_FLIGHT` * **Trigger:** Manual retry while a payment on the invoice is `processing` or has no recorded status yet. Wait for the outcome of that payment instead of sending again. * **Message:** A payment on this invoice is still in progress * `MANUAL_RETRY_LIMIT_REACHED` * **Trigger:** Manual retry after all 3 sends on the invoice are spent, or before the cooldown has passed (HTTP 429). The second send waits 1 hour after the first, and the third waits 3 hours after the second. The body carries only `code` and `message`. To find when the next send is allowed, read `retry_available_at` from `GET /payments/{payment_id}/retry`. * **Message:** Every manual retry for this invoice is spent *(or)* Retry now is not available for this invoice yet * `NO_ELIGIBLE_PAYMENT_METHODS` * **Trigger:** No payment method remains available for the payment after filtering (HTTP 422) * **Message:** No eligible payment methods found * `PAYMENT_NOT_PERMITTED` * **Trigger:** A checkout or payment attempt by a customer on the merchant's [blocklist](/features/customer-blocklist) (HTTP 403). The code and the message deliberately name no cause. * **Message:** This payment cannot be processed. * `PAYMENT_NOT_RETRYABLE` * **Trigger:** Manual retry of a payment that manual retry doesn't cover. The payment has no invoice, its invoice is not an open subscription renewal, no payment on the invoice has failed yet, the subscription has no recurring billing configured (for example, an on-demand subscription), or the customer is on the blocklist. * **Message:** Varies with the reason, for example: Only subscription renewal payments can be retried * `PAYMENT_NOT_SUCCEEDED` * **Trigger:** An attempt to refund or process a payment that has not succeeded * **Message:** The provided payment has not succeeded * `PREVIOUS_PAYMENT_PENDING` * **Trigger:** An attempt to create a charge while the previous payment is in a non-terminal state. Also returned for a [manual retry](/features/recovery/manual-retry) when the newest payment on the invoice is neither `failed` nor in flight, for example `requires_customer_action` or `cancelled`. * **Message:** Cannot create new charge as previous payment is not successful yet *(or)* The most recent payment on this invoice has not failed * `UNSUCCESSFUL_PAYMENT_ID` * **Trigger:** The payment ID references a payment that has not succeeded * **Message:** The Payment ID has an unsuccessful status. ### Connectors & BYOP These errors relate to merchant-owned payment connectors (Bring Your Own Processor, or BYOP). * `BYOP_CONNECTOR_DISABLED` * **Trigger:** Updating the payment method of a subscription routed through a disabled BYOP connector. Dodo Payments doesn't fall back to its own connectors, so re-enable the connector first. * **Message:** The subscription is routed through the merchant's own (BYOP) connector which is currently disabled * `BYOP_CUSTOM_INVOICE_ADDRESS_MISSING` * **Trigger:** A payment routed through the merchant's connector (BYOP) has no custom invoice address * **Message:** BYOP custom invoice address is required when a payment is routed through the merchant's connector * `CONNECTOR_LABEL_ALREADY_EXISTS` * **Trigger:** Creating a connector with a label that already exists * **Message:** A connector with this label already exists. Please choose a different label. ### Refunds * `EXISTING_REFUND_REQUEST_PROCESSING` * **Trigger:** A previous refund request is still being processed * **Message:** A refund request with status "Pending" is still being processed * `LINE_ITEM_FULLY_REFUNDED` * **Trigger:** An attempt to refund a line item that is already fully refunded * **Message:** Line item `{id}` has been fully refunded cannot be refunded further. * `LINE_ITEM_NOT_FOUND` * **Trigger:** The item ID is not part of the referenced payment * **Message:** Line item `{id}` not found in payment * `LINE_ITEM_PRORATED` * **Trigger:** A refund or update attempted on a prorated line item * **Message:** Line item `{id}` cannot be refunded because its prorated * `LINE_ITEM_REFUND_AMOUNT_TOO_HIGH` * **Trigger:** The refund amount, including tax, is higher than the amount that remains refundable on the line item * **Message:** Line item `{id}` requested refund amount including tax is `{amount}` which is above the refundable amount `{amount}` * `LINE_ITEM_REFUND_AMOUNT_TOO_LOW` * **Trigger:** The refund amount is below the minimum threshold, or it is too small to convert to the other currency of a cross-currency payment * **Messages:** * Line item `{id}` requested refund amount is `{amount}` which is too low * The refund amount is too small to convert to `{currency}` * `NOTHING_TO_REFUND` * **Trigger:** No refundable amount remains, because all positive line items are already fully refunded * **Message:** No refundable amount remaining. All positive line items have been fully refunded. * `PARTIAL_REFUND_NOT_ALLOWED` * **Trigger:** A partial refund, or a refund of the remaining amount after an earlier refund, on a payment that allows only a full refund until its payment verification completes * **Message:** Partial refunds for this payment are available after payment verification completes * `PAYMENT_ALREADY_REFUNDED` * **Trigger:** A duplicate refund * **Message:** This payment has already been refunded * `PAYMENT_HAS_BEEN_REFUNDED` * **Trigger:** The payment has been fully refunded * **Message:** The Payment ID has been fully refunded. * `REFUND_AMOUNT_EXCEEDS_PAID_AMOUNT` * **Trigger:** The total refund amount is higher than the paid amount * **Message:** The calculated refund amount is larger than the paid amount * `REFUND_CURRENCY_NOT_SUPPORTED` * **Trigger:** A refund request sets `currency`, and the API can't refund in that currency (HTTP 422). See [Refunds in the Payment Currency](/features/transactions/refunds#refunds-in-the-payment-currency). * **Messages:** * Refund currency must be `{currency}`: `currency` is not the payment currency. `{currency}` is the payment currency. Set `currency` to this value. * Credits can only be refunded in `{currency}`: the request sets `currency` and includes the `credits` item. `{currency}` is the settlement currency. Send the credits refund without `currency`. * An earlier refund of this payment has no amount in `{currency}`. Send the refund without currency: `{currency}` is the payment currency. Send the refund without `currency`. * `REFUND_WINDOW_EXPIRED` * **Trigger:** The refund is requested outside the allowed refund window * **Message:** Refunds cannot be initiated `{days}` days after payment creation. Contact [support@dodopayments.com](mailto:support@dodopayments.com). * `ZERO_AMOUNT_PAYMENT_REFUND_NOT_ALLOWED` * **Trigger:** An attempt to refund a zero-amount payment * **Message:** Cannot refund a payment with zero currency amount ### Subscriptions & Add-ons * `ADDONS_IN_USAGE_BASED_BILLING_NOT_SUPPORTED` * **Trigger:** An attempt to add add-ons to a usage-based billing subscription * **Message:** Addons in Subscriptions are not supported for Usage Based Billing * `ADDON_IS_DELETED` * **Trigger:** An attempt to archive an add-on that is already archived (HTTP 410) * **Message:** The addon is already archived * `ADDON_IS_NOT_ARCHIVED` * **Trigger:** An attempt to unarchive an add-on that is not archived (HTTP 409) * **Message:** The addon is not archived * `ADDONS_NOT_ALLOWED_FOR_ON_DEMAND` * **Trigger:** An attempt to add add-ons to an on-demand subscription * **Message:** Addons are not allowed for on demand subscriptions * `CANCEL_SCHEDULED_PLAN_CHANGE_FOR_CUSTOMER_PORTAL_DISABLED` * **Trigger:** The Customer Portal attempts to cancel a scheduled plan change while the business has disabled that action * **Message:** Cancelling scheduled plan change is disabled for customer portal. * `CHARGE_NOT_ALLOWED_FOR_SCHEDULED_CANCELLATION` * **Trigger:** An attempt to charge a subscription that is scheduled for cancellation * **Message:** Subscription scheduled for cancellation * `CUSTOMER_HAS_EXISTING_SUBSCRIPTION` * **Trigger:** Creating a subscription for a customer who already has one, when the business doesn't allow multiple subscriptions per customer * **Message:** Customer `{id}` has an existing subscription. To allow multiple subscriptions per customer, change business settings * `DO_NOT_BILL_NOT_ALLOWED_IN_CUSTOMER_PORTAL` * **Trigger:** The `do_not_bill` proration mode is used in a Customer Portal plan change * **Message:** do\_not\_bill proration mode is not allowed in the customer portal * `DUPLICATE_ADDON_IDS_IN_REQUEST` * **Trigger:** The same `addon_id` appears more than once in the request * **Message:** Duplicate addon IDs are not allowed * `INACTIVE_SUBSCRIPTION_PLAN_CHANGE_NOT_SUPPORTED` * **Trigger:** A plan change on an inactive subscription. On an `on_hold` subscription, also returned for a usage-based current or target plan, for a hold during a pause, and for a Customer Portal request. See [Change Plan on an On-Hold Subscription](/developer-resources/subscription-upgrade-downgrade#change-plan-on-an-on-hold-subscription). * **Message:** Changing plans is not supported for inactive subscriptions *(or)* Plan change on hold is supported only for fixed-price subscriptions *(or)* Plan change is not supported while a paused subscription is on hold *(or)* Plan change on an on-hold subscription is available only to the merchant * `INVALID_PRORATION_MODE_WITH_NEXT_BILLING_DATE` * **Trigger:** A proration mode other than `full_immediately` used with `effective_at: next_billing_date` * **Message:** Only full\_immediately proration mode is allowed with effective\_at: next\_billing\_date * `MISSING_ADDON_IDS` * **Trigger:** The `addon_id` list is empty, or contains unknown or archived add-on IDs * **Message:** One or more product IDs do not exist: `{id}` * `ON_DEMAND_PLAN_CHANGE_NOT_SUPPORTED` * **Trigger:** A plan change on an on-demand subscription * **Message:** Changing plans is not supported for on demand subscriptions * `ON_DEMAND_USAGE_BASED_BILLING_NOT_SUPPORTED` * **Trigger:** An attempt to use an on-demand subscription with usage-based billing * **Message:** On Demand Subscriptions are not supported for Usage Based Billing * `ON_HOLD_PLAN_CHANGE_OPTIONS_NOT_SUPPORTED` * **Trigger:** A plan change on an `on_hold` subscription without `proration_billing_mode: full_immediately`, `effective_at: immediately`, and `on_payment_failure: apply_change`, or with `collect_via_payment_link: true` (HTTP 422) * **Message:** A plan change on an on-hold subscription requires proration\_billing\_mode=full\_immediately, effective\_at=immediately and on\_payment\_failure=apply\_change. * `ON_HOLD_PLAN_CHANGE_RATE_LIMITED` * **Trigger:** A second plan change on the same `on_hold` subscription within 24 hours. The preview is not limited (HTTP 409) * **Message:** This on-hold subscription already had a plan change in the last 24 hours. * `ONE_TIME_PRODUCTS_NOT_ALLOWED_FOR_ON_DEMAND` * **Trigger:** A one-time product added to an on-demand subscription * **Message:** One-time products are not allowed for on demand subscriptions * `PENDING_PLAN_CHANGE_EXISTS` * **Trigger:** A new plan change requested while a previous one is still awaiting payment. To replace a pending payment-link change, set `cancel_older_payment_link: true`. * **Message:** A pending plan change already exists for this subscription. Please wait for the current payment to complete. * `PLAN_CHANGE_FOR_CUSTOMER_PORTAL_DISABLED` * **Trigger:** A plan change through the Customer Portal while the business has disabled it * **Message:** Subscription plan change for customer portal is disabled. * `PLAN_CHANGE_LINK_CANCEL_FAILED` * **Trigger:** A plan change with `cancel_older_payment_link: true` could not cancel the previous payment link. Nothing changed, so you can retry the request. * **Message:** Could not cancel the previous payment link. Try again. * `PLAN_CHANGE_NOT_ALLOWED_FOR_SCHEDULED_CANCELLATION` * **Trigger:** A plan change on a subscription that is scheduled for cancellation * **Message:** Subscription scheduled for cancellation * `PLAN_CHANGE_PAYMENT_ALREADY_COMPLETED` * **Trigger:** A plan change with `cancel_older_payment_link: true` while the customer has already paid the previous plan change. That change applies, so do not retry. * **Message:** The customer already paid the previous plan change. It applies shortly. * `PLAN_CHANGE_PAYMENT_IN_PROGRESS` * **Trigger:** A plan change with `cancel_older_payment_link: true` while the customer is paying the previous plan change, for example during 3D Secure. Retry after the payment completes or fails. * **Message:** The customer is paying the previous plan change now. Try again later. * `SCHEDULE_PLAN_CHANGE_FOR_CUSTOMER_PORTAL_DISABLED` * **Trigger:** Scheduling a plan change through the Customer Portal while the business has disabled it * **Message:** Scheduling plan changes is disabled for this business. * `SCHEDULED_PLAN_CHANGE_EXISTS` * **Trigger:** Creating a scheduled plan change when one already exists * **Message:** A scheduled plan change already exists for this subscription. Please cancel the existing scheduled change before creating a new one. * `SCHEDULED_PLAN_CHANGE_NOT_FOUND` * **Trigger:** Referencing or cancelling a scheduled plan change that does not exist * **Message:** No scheduled plan change found for this subscription. * `SUBSCRIPTION_EXPIRED` * **Trigger:** Billing a subscription after its `expires_at` date * **Message:** Subscription expired cannot create new charges * `SUBSCRIPTION_HAS_NO_PAYMENT_METHOD` * **Trigger:** Manual retry of a subscription that has no saved payment method to charge off-session * **Message:** This subscription has no saved payment method to charge * `SUBSCRIPTION_INACTIVE` * **Trigger:** The subscription status is not `active` * **Message:** Subscription is not active *(or)* This subscription is not live, so a cancellation cannot be scheduled * `SUBSCRIPTION_NOT_ON_DEMAND` * **Trigger:** An on-demand action on a subscription that bills on a fixed interval * **Message:** Subscription is already not on demand * `SUBSCRIPTION_PAYMENT_RETRY_LIMIT_EXCEEDED` * **Trigger:** The subscription payment retries exceeded the maximum number of attempts * **Message:** Maximum retry limit of 10 attempts exceeded for this subscription ### Customers & Blocklist * `CUSTOMER_ALREADY_BLOCKED` * **Trigger:** Blocking a customer who is already on the [blocklist](/features/customer-blocklist) and has no live subscriptions left to cancel (HTTP 409) * **Message:** This customer is already on the blocklist * `PORTAL_ACTION_NOT_PERMITTED` * **Trigger:** A blocked customer calls a Customer Portal write route: cancel, pause, resume, change plan, or update payment method (HTTP 403). Read routes stay open. The code and the message deliberately name no cause. * **Message:** This action is not available. ### Products, Cart & Brands * `BRAND_ALREADY_ARCHIVED` * **Trigger:** Archiving a brand that is already archived * **Message:** Brand is already archived * `BRAND_ARCHIVED` * **Trigger:** Updating an archived brand, submitting it for verification, or tagging a new product, product collection, or subscription to it * **Message:** Brand is archived *(or)* Brand is archived and cannot be updated *(or)* Brand is archived and cannot be submitted for verification * `BRAND_ARCHIVE_TARGET_REQUIRED` * **Trigger:** Archiving a brand that still holds products, live subscriptions, or product collections without a `move_products_to` target * **Message:** Brand has `{count}` product(s). Set move\_products\_to to a target brand to re-tag them. The message names live subscriptions or product collections instead when those block the archive. * `BRAND_MISMATCH` * **Trigger:** The cart items belong to different brands * **Message:** All items in the product cart should belong to the same brand * `BRAND_NOT_ENABLED` * **Trigger:** The brand is disabled or not active * **Message:** Brand provided is not enabled * `BRAND_SUBMISSION_NOT_ENABLED` * **Trigger:** The brand verification resubmission feature is not enabled * **Message:** `Brand verificatin resubmission is not enabled` (spelled exactly as the API returns it) * `CANNOT_ARCHIVE_PRIMARY_BRAND` * **Trigger:** Archiving the primary brand, whose brand ID is the business ID * **Message:** The primary brand cannot be archived * `CART_AMOUNT_EXCEEDS_LIMIT` * **Trigger:** In live mode, an amount before tax is above the [cart value limit](/features/cart-value-limit) of the business (HTTP 422). This applies to a product, add-on, or localized price, a Pay What You Want minimum price, a checkout cart, or an on-demand charge. A renewal payment above the limit fails with this code without reaching the processor. * **Message:** The price is more than the cart value limit of this business. *(or)* This product is currently unavailable for purchase. Please contact the seller. *(or)* This amount is above the maximum allowed. Please enter a lower amount. *(or)* The charge amount is more than the cart value limit of this business. Split it into smaller charges. * `FILE_IN_USE` * **Trigger:** Deleting a digital product file that active entitlement grants still reference * **Message:** Digital file is referenced by active grants * `INVALID_BRAND_ARCHIVE_TARGET` * **Trigger:** `move_products_to` names the brand being archived, an archived brand, or a brand of another business * **Message:** move\_products\_to must be a brand of this business that is not archived *(or)* move\_products\_to cannot be the brand you archive * `INVALID_SUGGESTED_PRICE` * **Trigger:** A Pay What You Want suggested price is lower than the minimum price * **Message:** Suggested Price cannot be lower than minimum price. In case of pay what you want, price is considered as minimum accepted amount * `LOCALIZED_PRICE_ALREADY_EXISTS` * **Trigger:** A localized price already exists for this product and country or currency * **Message:** A localized price for this product and country/currency already exists * `LOCALIZED_PRICE_DUPLICATES_BASE` * **Trigger:** The localized price duplicates the base currency or country of the product * **Message:** Localized price duplicates the product's base currency/country * `LOCALIZED_PRICE_SHAPE_MISMATCH` * **Trigger:** The localized price shape does not match the `pricing_mode` of the product * **Message:** Localized price shape does not match the product's pricing\_mode * `MISSING_PRODUCT_INFORMATION` * **Trigger:** The product exists, but mandatory information is missing * **Message:** Product `{id}` exists but other mandatory information is missing or invalid * `PAY_AS_YOU_WANT_AMOUNT_REQUIRED` * **Trigger:** The amount is missing for a Pay What You Want product * **Message:** Amount is mandatory for pay as you want product * `PRODUCT_CART_EMTPY` * **Trigger:** An empty product cart is submitted * **Message:** product\_cart is empty (the error code is intentionally spelled `EMTPY` to match the exact value the API returns) * `PRODUCT_COLLECTION_IS_DELETED` * **Trigger:** Operating on a product collection that has been deleted * **Message:** *No message* * `PRODUCT_COLLECTION_MUST_HAVE_PRODUCTS` * **Trigger:** Removing the last product, or the last group with products, from a collection * **Message:** Cannot delete the last product in a collection. Archive the collection instead. *(or)* Cannot delete the last group with products. Archive the collection instead. * `PRODUCT_IS_DELETED` * **Trigger:** The product has been deleted * **Message:** *No message* * `PRODUCT_PRICING_MODE_REQUIRED` * **Trigger:** Adding localized prices before the `pricing_mode` of the product is set * **Message:** Product pricing\_mode must be set before adding localized prices * `SLUG_ALREADY_TAKEN` * **Trigger:** The requested product slug or short URL is already in use * **Message:** Slug is already taken * `UNABLE_TO_EDIT_PRIMARY_BRAND` * **Trigger:** An attempt to update the primary brand through the regular brand API * **Message:** Primary brand cannot be updated via this API endpoint. ### Discounts * `DISCOUNT_ALREADY_USED_ON_SUBSCRIPTION` * **Trigger:** Applying a discount again that has already been used on this subscription * **Message:** This discount has already been used on this subscription * `DISCOUNT_CODE_ALREADY_EXISTS` * **Trigger:** Creating a discount code that already exists * **Message:** Discount Code already exists * `DISCOUNT_CODE_EXPIRED` * **Trigger:** The discount code is past its `expires_at` date * **Message:** Discount code expired * `DISCOUNT_CODE_USAGE_LIMIT_EXCEEDED` * **Trigger:** The discount code is used after its `usage_limit` is reached * **Message:** Usage limit cannot be less than times\_used *(or)* Discount code hit usage limit * **Note:** Terminal. The code is exhausted, so don't retry. * `DISCOUNT_CONCURRENT_REDEMPTION` * **Trigger:** Another redemption of the same code held the usage-limit lock too long (HTTP 503) * **Message:** Discount is being redeemed concurrently; please retry * **Note:** Transient. The code may still have capacity, so the request is safe to retry. Don't show this to the customer as an exhausted code. * `DISCOUNT_CURRENCY_OPTION_INVALID` * **Trigger:** Invalid `currency_options` on create or update * **Message:** A flat discount requires at least one currency option with a resolvable default *(or)* Duplicate currency options are not allowed *(or)* Only one currency option may be marked as default * `DISCOUNT_CUSTOMER_NOT_ELIGIBLE` * **Trigger:** The customer does not meet the `customer_eligibility` of the code (`first_time`, `existing`, or not on the allow list of a `specific` code) * **Message:** Customer is not eligible for this discount code * `DISCOUNT_MINIMUM_SUBTOTAL_NOT_MET` * **Trigger:** The cart subtotal is below the `minimum_subtotal` configured for the checkout currency * **Message:** Cart subtotal is below the discount's minimum required subtotal * `DISCOUNT_NOT_YET_ACTIVE` * **Trigger:** The code is used before its `starts_at` date * **Message:** Discount code is not yet active (starts\_at is in the future) * `DISCOUNT_PER_CUSTOMER_USAGE_LIMIT_EXCEEDED` * **Trigger:** The customer has already redeemed the code `per_customer_usage_limit` times * **Message:** Per-customer usage limit exceeded for this discount code * `DISCOUNT_NOT_APPLICABLE_TO_NEW_PRODUCT` * **Trigger:** A plan change to a product that the existing discount does not apply to * **Message:** Discount not applicable to the new plan's product * `DISCOUNT_NOT_AVAILABLE_FOR_ON_DEMAND` * **Trigger:** The code is applied to an on-demand subscription * **Message:** Discount coupon not available for on demand subscriptions * `DISCOUNT_NOT_AVAILABLE_FOR_PRODUCT` * **Trigger:** The code is applied to products it doesn't cover * **Message:** Discount coupon not available for this product * `INVALID_DISCOUNT_CODE` * **Trigger:** The code does not exist, or it doesn't apply to any product in the cart * **Message:** Invalid Discount Code *(or)* Discount Code cannot be applied to any product in the cart * `INVALID_PERCENTAGE` * **Trigger:** The percentage is higher than 100% (10,000 basis points) * **Message:** Percentage amount cannot be more than 10000 *(or)* Discount code amount cannot be more than 100% * `UNSUPPORTED_DISCOUNT_TYPE` * **Trigger:** A discount type that is not supported. `percentage` and `flat` are both supported; per-unit amount discounts are not. * **Message:** Only percentage and flat discount codes are supported *(or)* Only percentage discount codes are supported for now ### License Keys * `ACTIVATION_LIMIT_LESS_THAN_CURRENT_AMOUNT` * **Trigger:** The new activation limit of a license key is lower than its current number of instances * **Message:** New activation limit cannot be less than current instances count * `INACTIVE_LICENSE_KEY` * **Trigger:** The license key status is not `active` * **Message:** License key is not active * `LICENSE_KEY_LIMIT_REACHED` * **Trigger:** The number of activations has reached the activation limit * **Message:** License key activation limit reached * `LICENSE_KEY_NOT_FOUND` * **Trigger:** The instance ID or license key ID is invalid * **Message:** License key instance not found or does not belong to this license key * `NO_EXPIRY_ON_SUBSCRIPTION_LICENSE_KEYS` * **Trigger:** An attempt to set an expiry date on a subscription-based license key * **Message:** Cannot set expiry date for subscription-based license key ### Usage-Based Billing & Meters * `DUPLICATE_METER_IDS_IN_REQUEST` * **Trigger:** The same meter ID appears more than once in the request * **Message:** Duplicate Meter Ids are not allowed * `INVALID_QUANTITY` * **Trigger:** A quantity other than 1 for a product with usage-based pricing * **Message:** Only 1 quantity allowed in usage based price products * `METER_IS_DELETED` * **Trigger:** An attempt to use a deleted meter * **Message:** The Meter is already been deleted * `MISSING_METER_IDS` * **Trigger:** The meter ID list is empty or contains invalid IDs * **Message:** One or more meter IDs do not exist: `{id}` ### Credit-Based Billing * `CREDIT_ENTITLEMENT_IS_DELETED` * **Trigger:** Operating on a credit entitlement that has been deleted * **Message:** The credit entitlement has already been deleted * `CREDIT_ENTITLEMENT_NAME_ALREADY_EXISTS` * **Trigger:** Creating a credit entitlement with a name that already exists * **Message:** A credit entitlement with this name already exists * `OVERAGE_LIMIT_EXCEEDED` * **Trigger:** A usage or credit deduction would exceed the configured overage limit * **Message:** Overage limit exceeded ### Wallet * `INSUFFICIENT_WALLET_FUNDS` * **Trigger:** The wallet balance is lower than the debit amount * **Message:** Insufficient funds in wallet * `NEGATIVE_BALANCE_ADJUSTMENT` * **Trigger:** An attempt to make the wallet balance negative * **Message:** Wallet balance is not allowed to be made negative ### Currency, Tax & Region * `EXCHANGE_RATE_NOT_FOUND` * **Trigger:** No exchange rate exists for the currency pair * **Message:** Exchange rate not found to convert from `{currency}` to `{currency}` * `INVALID_TAX_ID` * **Trigger:** The VAT, GST, or TIN failed validation * **Message:** Tax Id is invalid * `REQUEST_AMOUNT_BELOW_MINIMUM` * **Trigger:** The amount is lower than the minimum set for the product * **Message:** Amount cannot be less than minimum amount specified for the product * `TOTAL_PAYMENT_AMOUNT_BELOW_MINIMUM_AMOUNT` * **Trigger:** The combined cart total, including tax, is lower than the minimum amount required to process a payment. The minimum depends on the billing currency and on whether the payment is one-time or a subscription. For currencies other than USD, EUR, and GBP, the total is also checked against the USD minimum. See [Minimum Amounts](/features/adaptive-currency#minimum-amounts) * **Message:** Minimum amount of `{display_str}` is required to process payment, for example `Minimum amount of 1.00 USD is required to process payment` * `UNSUPPORTED_BILLING_CURRENCY` * **Trigger:** The requested billing currency is not supported for this subscription * **Message:** Non USD billing currency is not supported for subscriptions * `UNSUPPORTED_COUNTRY` * **Trigger:** The country is not supported * **Message:** Country `{country_name}` currently not supported * `UNSUPPORTED_CURRENCY` * **Trigger:** The product or add-on currency is not a currency that Dodo Payments can charge in. Base prices can be set in any chargeable currency, so this error usually means that the currency code is invalid or not supported. * **Message:** Currency is not currently supported *(or)* Only USD and INR products supported currently *(or)* Only USD and INR supported for addon price *(or)* Can only request USD or INR for billing\_currency *(or)* Currency Not Supported *(or)* Unexpected currency for Indian card subscriptions * `UNSUPPORTED_TAX_CATEGORY` * **Trigger:** The tax category is not one of the supported values * **Message:** Category `{category}` currently not supported ### Validation & Requests * `DUPLICATE_LINE_ITEMS_IN_REQUEST` * **Trigger:** The same `item_id` appears more than once in `items[]` * **Message:** Duplicate item\_ids specified in items array * `INVALID_QUERY_PARAMS` * **Trigger:** Query parameters that are mutually exclusive or malformed * **Message:** Query params should only contain either time\_frame or (start, end) *(or)* The start of the range must not be after the end * `INVALID_REQUEST_BODY` * **Trigger:** Malformed JSON or a schema violation * **Message:** Your request body is invalid. Please check your request headers and object. * `INVALID_REQUEST_PARAMETERS` * **Trigger:** Parameter values that are valid in format but not in meaning, for example a date in the past * **Message:** Cannot change next\_billing\_date to past time *(or)* A checkout with more than one subscription product cannot hold one-time products *(or)* All product IDs must be unique *(or)* On demand subscriptions cannot hold more than one product *(or)* A checkout can hold at most 20 subscription products *(or)* Duplicate subscription products in one checkout are not allowed * `MAXIMUM_KEYS_REACHED` * **Trigger:** Metadata or custom fields exceed 50 key-value pairs * **Message:** Exceeds 50 key-value pairs ### General & System * `INTEGER_CONVERSION_FAILURE` * **Trigger:** A server-side conversion between an integer and a string or decimal fails, for example when a cart total is too large to process * **Message:** Integer Conversion Failure *(or)* Cart total is too large to process. Reduce the quantity, or select a different billing currency. * `INTERNAL_SERVER_ERROR` * **Trigger:** An unexpected server error. Log the request details on your side. * **Message:** *No public message (generic 500, `message` is usually `null`)* * `NOT_FOUND` * **Trigger:** Generic 404 for any missing resource * **Message:** Item not found *(or a more specific message that names what is missing)* * `TOO_MANY_REQUESTS` * **Trigger:** A rate limit was exceeded (HTTP 429) * **Message:** *No message* * `UNSUPPORTED_ACTION` * **Trigger:** An action that the resource type doesn't support * **Message:** Changing plans for usage based subscriptions is not supported ## Best Practices Follow these practices when you handle API errors: 1. Handle every error response in your application, and branch on `code` rather than on `message`. 2. Log the HTTP status, `code`, and `message` of every failed request. 3. Show end users a message written for them instead of the raw API `message`. 4. Retry only transient errors, such as `429` and `5xx` responses or `DISCOUNT_CONCURRENT_REDEMPTION`, after a delay. 5. Contact support for errors that you can't resolve. ## Support For more help with error codes or integration issues, contact the support team at [support@dodopayments.com](mailto:support@dodopayments.com). # API Reference Source: https://docs.dodopayments.com/api-reference/introduction REST API for payments, subscriptions, customers, and billing. Authenticate with API keys and handle webhooks for real-time events. > [card] [SDKs & Libraries](/developer-resources/dodo-payments-sdks) > > Official backend SDKs for TypeScript, Python, Go, PHP, Java, Kotlin, C#, Ruby, and Rust. These libraries handle authentication, serialization, and error handling so you can focus on your integration. > [card] [Mobile Checkout SDKs](/developer-resources/mobile-integration) > > Open Dodo's hosted checkout from Android, iOS, React Native, and Flutter apps and get a typed result back in one call. These SDKs hold no API key. ## Environment URLs * **Test Mode**: `https://test.dodopayments.com` * **Live Mode**: `https://live.dodopayments.com` > [!NOTE] > > Learn more about [Test Mode vs Live Mode](/miscellaneous/test-mode-vs-live-mode). ## Authentication API requests require an API key, except a few public endpoints such as [Activate License](/api-reference/licenses/activate-license), [Validate License](/api-reference/licenses/validate-license), and [Deactivate License](/api-reference/licenses/deactivate-license). Generate one in your dashboard and include it in the `Authorization` header of every request. **1. Generate an API Key** Go to **Developer → API Keys** in your dashboard and select **Create New Key**. Create the key in the mode you want to call: a test mode key works only with `https://test.dodopayments.com`, and a live mode key works only with `https://live.dodopayments.com`. Enter a **Key Name**, then set **None**, **Read**, or **Write** access for each resource, such as Payments, Refunds, Subscriptions, Products, Customers, Webhooks, or Moderation. **Write** includes **Read**, and Payouts and Balances are read-only. Use **Select all** to set every resource at once. You can give a key only the access that you have yourself. If your role lacks access to a resource, the dashboard hides it or limits it to **Read**. A request the key has no access for returns `403` with the `INSUFFICIENT_PERMISSION` [error code](/api-reference/error-codes). To change a key's access later, use **Edit Permissions** on the key. To limit where the key can be used, enter IPv4 or IPv6 addresses or CIDR ranges in **IP Allowlist**, one on each line, up to 20 entries. Leave it empty to allow any IP address. A request from an address that is not on the list returns `403` with the `IP_ADDRESS_NOT_ALLOWED` error code. The **IP Access** column of the API keys table shows each key's allowlist. > [!TIP] > > Grant each key only the access its integration needs. For example, give an analytics tool **Read** access, and a refunds bot **Write** access to Refunds and **Read** access to Payments. > [!NOTE] > > Keys created before per-resource access keep their original reach: a key with write access can read and write every API resource, and a read-only key can read every API resource. **2. Store Your Key Securely** Copy the key immediately. You won't see it again. Store it in an environment variable such as `DODO_PAYMENTS_API_KEY`. The prefix shows which mode a key belongs to: test mode keys start with `dodo_test_`, and live mode keys start with `dodo_live_`. The **Key** column of the API keys table shows the prefix of each key. A prefixed key sent to the other mode's environment returns `401` with a message that names its mode. Keys created before prefixes were added have no prefix and keep working. **3. Authenticate Requests** Include your API key in the `Authorization` header of every request: ```bash theme={null} Authorization: Bearer dodo_test_... ``` > [!WARNING] > > Never expose your API key in client-side code, public repositories, or version control. > [!TIP] > > CI/CD pipelines and cloud workloads can authenticate without a stored API key. Exchange a platform-issued token at `POST /workload-identity/token` and send the returned access token in the same `Authorization: Bearer` header. See [Workload Identity](/developer-resources/workload-identity/overview). ## Response Format Successful requests return `200` or `201` with a JSON body, or `204` with no body. Errors return a `4xx` or `5xx` status with a JSON body that contains a `code` and a `message`. ```json Success theme={null} { "payment_id": "pay_gr4RizvMOXFJ6xca3y2tU", "status": "succeeded", "total_amount": 2999, "currency": "USD", "created_at": "2024-01-15T10:30:00Z" } ``` ```json Error theme={null} { "code": "INVALID_REQUEST_BODY", "message": "Your request body is invalid. Please check your request headers and object." } ``` ## Rate Limits The API enforces two limits at once: a per-second burst limit and a per-minute sustained limit. Limits apply to your business as a whole, across all of its API keys, and depend on your business's rate limit tier. ### Default Tier | Window | Limit | | - | - | | Per Second (Burst) | 40 requests | | Per Minute (Sustained) | 240 requests | ### Higher Tiers Businesses with increased API needs can upgrade to higher rate limits: | Tier | Burst (per second) | Sustained (per minute) | | - | - | - | | Default | 40 | 240 | | Tier 1 | 100 | 1,000 | | Tier 2 | 500 | 5,000 | > [!TIP] > > To upgrade your rate limit tier, email [support@dodopayments.com](mailto:support@dodopayments.com). ### Unauthenticated Requests Requests without a valid API key are rate limited by IP address: | Window | Limit | | - | - | | Per Second (Burst) | 20 requests | | Per Minute (Sustained) | 100 requests | ### Invoice Downloads The invoice PDF endpoints, such as [Get Invoice](/api-reference/payments/get-invoice), `GET /invoices/refunds/{refund_id}`, and `GET /invoices/payouts/{payout_id}`, have their own limits: | Scope | Limit | | - | - | | Per record (one payment, refund, or payout) | 5 requests per minute | | Per client IP address | 20 requests per minute | When either limit is exceeded, the endpoint returns `429 Too Many Requests`. To fetch many invoices, space out your requests. ### Rate Limit Headers Responses include headers that show your current usage: * `X-RateLimit-Limit` — Maximum requests allowed in the current window. * `X-RateLimit-Remaining` — Requests remaining before you hit the limit. * `X-RateLimit-Reset` — Seconds until the current window resets. When you exceed the limit, the API returns `429 Too Many Requests`. Implement exponential backoff in your retry logic. ## Error Handling To find what an error means and how to resolve it, see the error codes and transaction failures pages. > [card] [Error Codes](/api-reference/error-codes) > > Complete list of error codes and their meanings. > [card] [Transaction Failures](/api-reference/transaction-failures) > > Common transaction issues and how to handle them. ## Webhooks Receive real-time notifications when payments, subscriptions, and other events occur. Set up webhooks in your dashboard and handle the events your integration needs. > [card] [Webhook Guide](/developer-resources/webhooks) > > Set up webhooks, handle events, and verify signatures. ## Integration Guides Start with one of these guides to build your first integration: > [card] [One-time Payments](/developer-resources/integration-guide) > > Create checkout sessions, payment links, and handle payments. > [card] [Subscriptions](/developer-resources/subscription-integration-guide) > > Set up recurring billing, manage plans, and handle lifecycle events. > [card] [Usage-Based Billing](/developer-resources/usage-based-billing-guide) > > Meter usage and charge customers based on consumption. > [card] [Checkout Sessions](/developer-resources/checkout-session) > > Create secure, hosted checkout experiences. # Add a Note to an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/add-note post /billing/invoices/{invoice_id}/notes Add an internal note to an invoice. The note shows in the invoice events. # Change the Dunning of an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/change-dunning post /billing/invoices/{invoice_id}/dunning Pause, resume or move the payment reminders of an open or past-due invoice. # Create the Hosted Link of an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/create-hosted-link post /billing/invoices/{invoice_id}/hosted-link Get the hosted page where the customer views and pays an invoice. # Create a Draft Invoice Source: https://docs.dodopayments.com/api-reference/invoices/create-invoice post /billing/invoices Create a draft invoice for a customer. A repeat with the same Idempotency-Key returns the first draft. # Delete a Draft Invoice Source: https://docs.dodopayments.com/api-reference/invoices/delete-invoice delete /billing/invoices/{invoice_id} Delete a draft invoice. Only a draft can be deleted. # Duplicate an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/duplicate-invoice post /billing/invoices/{invoice_id}/duplicate Copy the customer, product lines, terms and recipients of an invoice into a new draft. # Finalize an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/finalize-invoice post /billing/invoices/{invoice_id}/finalize Issue a draft invoice, and optionally email it to the customer in the same call. # Get an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/get-invoice get /billing/invoices/{invoice_id} Get an invoice with its lines, payments, status and the actions its status accepts. # List the Events of an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/list-invoice-events get /billing/invoices/{invoice_id}/events Get the change history of an invoice, oldest first. # List Invoices Source: https://docs.dodopayments.com/api-reference/invoices/list-invoices get /billing/invoices List invoice-led invoices, newest first, filtered by status, customer, subscription, dates, amount or collection method. # Mark an Invoice Uncollectable Source: https://docs.dodopayments.com/api-reference/invoices/mark-uncollectable post /billing/invoices/{invoice_id}/mark-uncollectable Mark an invoice that you do not expect to be paid as uncollectable. # Preview a Draft Invoice Source: https://docs.dodopayments.com/api-reference/invoices/preview-invoice get /billing/invoices/{invoice_id}/preview Preview a draft invoice as JSON, a PDF with a draft mark, or the invoice email. # Preview an Invoice Request Source: https://docs.dodopayments.com/api-reference/invoices/preview-invoice-request post /billing/invoices/preview Price an invoice request as a draft and get it back as JSON, a PDF, or the invoice email, without saving it. # Retry the Charge of an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/retry-invoice post /billing/invoices/{invoice_id}/retry Charge the saved payment method of the invoice subscription again now. # Send an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/send-invoice post /billing/invoices/{invoice_id}/send Email an issued invoice to the customer email and the CC emails. # Update an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/update-invoice patch /billing/invoices/{invoice_id} Change the fields of an invoice that its status allows. Only the sent fields change. # Void an Invoice Source: https://docs.dodopayments.com/api-reference/invoices/void-invoice post /billing/invoices/{invoice_id}/void Close an open or past-due invoice. Applied credits go back to the customer wallet. # Activate License Source: https://docs.dodopayments.com/api-reference/licenses/activate-license post /licenses/activate This endpoint allows you to activate a license for the user. > [!NOTE] > > **No API Key Required**: This is a public endpoint that does not require authentication. You can call it directly from client applications, desktop software, or CLIs to activate license keys without exposing your API credentials. # Create License Key Source: https://docs.dodopayments.com/api-reference/licenses/create-license-key post /license_keys Import an existing license key from another system. The key string, customer, and product are all required. > [!NOTE] > > This endpoint imports a key you already have — `key`, `customer_id`, and `product_id` are all required. It does not generate a key value for you. Importing a `key` that already exists returns `409 Conflict`. > [!NOTE] > > License keys created or updated through the API do not trigger email notifications to customers. If you need to notify customers about their license key, you must handle that separately in your application. # Deactivate License Source: https://docs.dodopayments.com/api-reference/licenses/deactivate-license post /licenses/deactivate This endpoint allows you to deactivate a license for the user. > [!NOTE] > > **No API Key Required**: This is a public endpoint that does not require authentication. You can call it directly from client applications, desktop software, or CLIs to deactivate license keys without exposing your API credentials. # Get License Key Source: https://docs.dodopayments.com/api-reference/licenses/get-license-key get /license_keys/{id} Deprecated: retrieve a license key by its ID. Use List Customer Grants with integration_type=license_key to read license key details instead. > [!WARNING] > > **Deprecated API**: License keys are now managed through the [Entitlements](/features/entitlements/introduction) system. Use [List Customer Grants](/api-reference/entitlements/list-customer-grants) (filter with `integration_type=license_key`) to retrieve a key's grant and its `license_key` details. This endpoint will be removed in a future release. # Get License Key Instance Source: https://docs.dodopayments.com/api-reference/licenses/get-license-key-instance get /license_key_instances/{id} Retrieve details of a specific license key instance by its ID. # List License Key Instances Source: https://docs.dodopayments.com/api-reference/licenses/get-license-key-instances get /license_key_instances Retrieve a list of license key instances. Optionally filter by `license_key_id` to scope results to a specific license key, or by `grant_id` to scope to an entitlement grant. # List License Keys Source: https://docs.dodopayments.com/api-reference/licenses/list-license-keys get /license_keys Deprecated: list the license keys on your account. Use List Customer Grants with integration_type=license_key to list issued license keys instead. > [!WARNING] > > **Deprecated API**: License keys are now managed through the [Entitlements](/features/entitlements/introduction) system. Use [List Customer Grants](/api-reference/entitlements/list-customer-grants) to list issued license keys (filter with `integration_type=license_key`); each grant carries its `license_key` details. This endpoint will be removed in a future release. # Update License Key Source: https://docs.dodopayments.com/api-reference/licenses/update-license-key patch /license_keys/{id} Deprecated: update a license key by its ID. Configure limits on the License Key entitlement and use Revoke Grant to disable a key instead. > [!WARNING] > > **Deprecated API**: License keys are now managed through the [Entitlements](/features/entitlements/introduction) system. Configure activation limits and durations on the [License Key entitlement](/api-reference/entitlements/update-entitlement), and use [Revoke Grant](/api-reference/entitlements/revoke-grant) to disable a customer's key. This endpoint will be removed in a future release. > [!NOTE] > > Updating a license key through the API does not trigger email notifications to the customer. # Update License Key Instance Source: https://docs.dodopayments.com/api-reference/licenses/update-license-key-instance patch /license_key_instances/{id} This endpoint allows you to update a specific license key instance by its ID. # Validate License Source: https://docs.dodopayments.com/api-reference/licenses/validate-license post /licenses/validate This endpoint allows you to validate a license for the user. > [!NOTE] > > **No API Key Required**: This is a public endpoint that does not require authentication. You can call it directly from client applications, desktop software, or CLIs to validate license keys without exposing your API credentials. # Metadata Guide Source: https://docs.dodopayments.com/api-reference/metadata Use metadata to store your own key-value data, such as order IDs and CRM references, on Dodo Payments payments, subscriptions, customers, and more. ## Introduction Metadata lets you store your own key-value data on Dodo Payments objects, such as an order ID from your system or a CRM reference. You can attach metadata to most objects, including payments, subscriptions, customers, and products. See [Supported Objects](#supported-objects) for the full list. ## Overview Metadata follows these rules: * Metadata keys can be up to 40 characters long (up to 100 characters for usage events ingested through `POST /events/ingest`). * Metadata values can be a string, integer, number, or boolean. String values can be up to 500 characters long. * Objects, arrays, and `null` are not accepted as metadata values. * You can add up to 50 metadata key-value pairs per object. A request with more returns the `MAXIMUM_KEYS_REACHED` [error code](/api-reference/error-codes). * The API can't search or filter by metadata, but it returns metadata in API responses and webhooks. ## Use Cases Use metadata to: * Store external IDs or references. * Add internal notes. * Link Dodo Payments objects to records in your system. * Categorize transactions. * Add custom attributes for reporting. ## Adding Metadata Add metadata when you create or update an object through the API. For products, you can also add metadata in the dashboard. ### Via API Pass a `metadata` object in the request body. The examples below use the TypeScript SDK and assume an initialized `client`: ```javascript expandable theme={null} // Assumes an initialized client, for example: // const client = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY }); // Adding metadata when creating a checkout session const checkoutSession = await client.checkoutSessions.create({ product_cart: [{ product_id: 'pdt_123', quantity: 1 }], return_url: 'https://example.com/return', metadata: { order_id: 'ORD-123', campaign_source: 'email', customer_segment: 'premium' } }); // Adding metadata when creating a product const product = await client.products.create({ name: 'Premium Software License', tax_category: 'digital_products', price: { type: 'one_time_price', currency: 'USD', price: 9900, discount_bps: 0, purchasing_power_parity: false }, metadata: { category: 'software', license_type: 'premium', support_tier: 'priority' } }); // Adding metadata when creating a customer const customer = await client.customers.create({ email: 'customer@example.com', name: 'John Doe', metadata: { crm_id: 'CRM-12345', customer_segment: 'enterprise', referral_source: 'website' } }); // Adding metadata when changing a subscription plan await client.subscriptions.changePlan('sub_123', { product_id: 'pdt_premium', proration_billing_mode: 'prorated_immediately', quantity: 1, metadata: { upgrade_reason: 'feature_request', previous_plan: 'basic', sales_rep: 'john@example.com' } }); // Adding metadata when creating a discount const discount = await client.discounts.create({ type: 'percentage', amount: 1500, // 15% code: 'SUMMER2025', metadata: { campaign: 'summer_promo', source: 'email_blast', team: 'marketing' } }); ``` ### Via Dashboard UI (Products Only) To add metadata to a product without writing code, open the product in **Products** and add key-value pairs in the metadata section. You can do this when you create or edit the product. ![Product metadata section in the Dodo Payments dashboard](https://mintcdn.com/dodopayments/5D2vY2CKcFOZLLyz/images/product-catalog/product-metadata-ui.png?fit=max\&auto=format\&n=5D2vY2CKcFOZLLyz\&q=85\&s=9e4fee91d8922325d8c1c72b27ccb0a2) > [!TIP] > > Team members who don't work with the API can use the dashboard to manage product metadata, such as product categories. ## Retrieving Metadata API responses include metadata when you retrieve an object: ```javascript theme={null} // Retrieving payment metadata const payment = await client.payments.retrieve('pay_123'); console.log(payment.metadata.order_id); // 'ORD-123' // Retrieving customer metadata const customer = await client.customers.retrieve('cus_123'); console.log(customer.metadata.crm_id); // 'CRM-12345' // Retrieving refund metadata const refund = await client.refunds.retrieve('ref_123'); console.log(refund.metadata.refund_reason); // 'customer_request' ``` > [!NOTE] > > Retrieving a checkout session (`GET /checkouts/{id}`) doesn't return `metadata`. The session status response contains only `id`, `created_at`, `payment_id`, `payment_status`, `customer_email`, and `customer_name`. To read the metadata you attached when you created the session, retrieve the resulting payment with the returned `payment_id`. ## Searching and Filtering The API can't search by metadata. To find an object by a metadata value: 1. Store your important identifiers in metadata. 2. List or retrieve objects through the API. 3. Filter the results in your application code. ```javascript theme={null} // Example: Find a payment using your order ID. // list() is auto-paginating, so iterating searches across pages instead of // only the first one. let matchingPayment; for await (const payment of client.payments.list({ page_size: 100 })) { if (payment.metadata?.order_id === '6735') { matchingPayment = payment; break; } } ``` ## Best Practices Follow these guidelines to keep metadata useful. ### Do: * Use consistent naming conventions for metadata keys. * Document your metadata schema internally. * Keep values short and meaningful. * Use metadata for static data only. * Consider prefixes that name the source system, for example `crm_id` or `inventory_sku`. ### Don't: * Store sensitive data in metadata. * Use metadata for values that change often. * Rely on metadata for critical business logic. * Duplicate information that the object already contains. * Use special characters in metadata keys. ## Supported Objects These objects support metadata: | Object Type | Support | | - | - | | Payments | ✓ | | Subscriptions | ✓ | | Subscription Change Plan | ✓ | | Subscription Charges | ✓ | | Products | ✓ | | Refunds | ✓ | | Checkout Sessions | ✓ | | Customers | ✓ | | Discounts | ✓ | | Entitlements | ✓ | | Credit Ledger Entries | ✓ | | Usage Events | ✓ | | Webhooks | ✓ | ## Webhooks and Metadata Webhook payloads include the metadata of the object, so your webhook handler can match an event to your own records: ```javascript theme={null} // Example webhook handler. Assumes an Express `app` that parses JSON bodies. // Verify the webhook signature before you trust the payload: // see /developer-resources/webhooks app.post('/webhook', (req, res) => { const event = req.body; if (event.type === 'payment.succeeded') { const orderId = event.data.metadata.order_id; // Process order using your internal order ID } if (event.type === 'subscription.active') { const orderId = event.data.metadata.order_id; const campaignSource = event.data.metadata.campaign_source; // Handle subscription activation with custom metadata } res.sendStatus(200); }); ``` # Get Invoice Source: https://docs.dodopayments.com/api-reference/payments/get-invoice get /invoices/payments/{payment_id} Get an invoice by Payment ID. # List Payments Source: https://docs.dodopayments.com/api-reference/payments/get-payments get /payments Get a list of all payments associated with your account. # Get Payment Detail Source: https://docs.dodopayments.com/api-reference/payments/get-payments-1 get /payments/{payment_id} Get detailed information about a specific payment. # Create One-Time Payment Source: https://docs.dodopayments.com/api-reference/payments/post-payments post /payments Deprecated: create a one-time payment for a customer. Use Create Checkout Session (POST /checkouts) for new one-time payment integrations. > [!WARNING] > > **Deprecated API**: This endpoint is deprecated and will be removed in a future release. We recommend using [Checkout Sessions](/api-reference/checkout-sessions/create) instead, which provides a more powerful and customizable API to create payment links for one-time payments and subscriptions. # Retrieve Line Items Source: https://docs.dodopayments.com/api-reference/payments/retrieve-line-items get /payments/{payment_id}/line-items Retrieve line items for a specific payment. # Get Manual Retry State Source: https://docs.dodopayments.com/api-reference/payments/retrieve-retry-state get /payments/{payment_id}/retry Check whether a failed subscription renewal payment can be retried now, and when the next manual retry becomes available. # Retry Payment Source: https://docs.dodopayments.com/api-reference/payments/retry-payment post /payments/{payment_id}/retry Retry a failed subscription renewal payment by charging the saved payment method again for its open invoice. # List Products Source: https://docs.dodopayments.com/api-reference/products/get-products get /products Get a list of all products associated with your account. # Get Product Detail Source: https://docs.dodopayments.com/api-reference/products/get-products-1 get /products/{id} Get detailed information about a specific product. # Update Product Source: https://docs.dodopayments.com/api-reference/products/patch-products patch /products/{id} Update a product's details. # Create Product Source: https://docs.dodopayments.com/api-reference/products/post-products post /products Create a new product. # Update Product Image Source: https://docs.dodopayments.com/api-reference/products/put-products-images put /products/{id}/images Get a presigned S3 URL to upload an image for a product. Upload the image to the returned URL within 60 seconds. # Cancel Scheduled Plan Change Source: https://docs.dodopayments.com/api-reference/subscriptions/cancel-change-plan delete /subscriptions/{subscription_id}/change-plan/scheduled Cancel a scheduled plan change for a subscription. # Change Plan Source: https://docs.dodopayments.com/api-reference/subscriptions/change-plan post /subscriptions/{subscription_id}/change-plan Modify an existing subscription's plan, enabling both upgrades and downgrades to different pricing tiers.

Note: By default this uses the customer's existing payment information. Set collect_via_payment_link to charge via a hosted checkout page instead. ## Scheduled Plan Changes Use the `effective_at` parameter to control when the plan change takes effect: | Value | Behavior | | - | - | | `immediately` | Apply the plan change right away. This is the default. | | `next_billing_date` | Schedule the change for the next billing date. The customer retains access to their current plan until the billing period ends. | > [!NOTE] > > Scheduled plan changes are ideal for downgrades — customers keep their current plan benefits until the end of the billing period, then automatically switch to the new plan. To cancel a scheduled plan change before it takes effect, use the [Cancel Scheduled Plan Change](/api-reference/subscriptions/cancel-change-plan) endpoint. To replace a scheduled plan change with a new one in a single request, set `cancel_scheduled_change_plan` to `true`. The scheduled change is cancelled only when the new change applies. ## Payment Failure Handling Use the `on_payment_failure` parameter to control what happens when the plan change payment fails: | Value | Behavior | | - | - | | `prevent_change` | Keep subscription on current plan until payment succeeds. Plan change remains pending. | | `apply_change` | Apply plan change immediately regardless of payment outcome. | > [!NOTE] > > If `on_payment_failure` is not specified, the behavior defaults to your business-level setting configured in the dashboard. With `effective_at: next_billing_date`, the plan change payment replaces the renewal payment. If that payment fails with `prevent_change`, the plan change is cancelled and the subscription renews on its current plan, with the usual payment retries. ## Invoice-Led Subscriptions Two fields apply only to invoice-led subscriptions (see [Invoice-Based Billing](/features/invoice-based-billing)): | Field | Behavior | | - | - | | `credit` | Where the credit of a downgrade billed now goes: `customer_balance` (default) or `refund`. | | `invoice` | How the plan change billed now is invoiced: `collection_method`, `payment_terms`, and `finalize` (set `false` to keep the invoice as a draft for review). | The response includes `invoice_id` for an invoice-led subscription, and `refund_id` for a downgrade with `credit: refund`. ## Collecting via Payment Link Set `collect_via_payment_link` to `true` to send the customer to a hosted checkout page instead of charging their saved payment method. The response then includes `payment_id`, `payment_link`, `client_secret`, and `expires_on` — redirect the customer to `payment_link` to complete the payment. This requires: | Requirement | Why | | - | - | | Business has the `allow_plan_change_via_payment_link` capability enabled | Off by default; toggled in **Settings → Subscriptions → Collect Plan Change Payments by Payment Link**. | | `effective_at: immediately` | A scheduled change doesn't charge anything until it applies, so there's nothing to collect via checkout yet. | | `on_payment_failure: prevent_change` | The subscription must stay on its current plan until the checkout payment actually succeeds. Send the field explicitly in the request. | A request that doesn't meet these returns `422`. While the link is unpaid, the subscription stays on its current plan and a further `change-plan` request returns `409`, unless you set `cancel_older_payment_link`. ### Redirecting After Payment Set `return_url` to send the customer back to your site after they pay the link. The redirect adds `subscription_id`, `payment_id`, and `status` as query parameters. * `status` is the status of the plan-change payment, not the status of the subscription. * When the payment fails, the subscription stays active on its current plan. To try again, call `change-plan` again to get a new link. * The new plan can apply shortly after the redirect, when the payment webhook arrives. `return_url` needs `collect_via_payment_link: true`. Without it, the request returns `422`. ### Replacing a Pending Payment Link If the customer leaves the checkout without paying, set `cancel_older_payment_link` to `true` on the next `change-plan` request. Dodo Payments cancels the unpaid link, and the new plan change replaces the pending one. The cancelled link no longer accepts a payment. The request is validated before the link is cancelled, so an invalid request keeps the customer's link. The link is cancelled only if the customer has not started to pay: | Previous payment | Response | | - | - | | Not opened, opened but not paid, or declined | `200` with the new link | | Customer is paying now, for example during 3D Secure | `409` `PLAN_CHANGE_PAYMENT_IN_PROGRESS`. Retry after the payment completes or fails. | | Already paid | `409` `PLAN_CHANGE_PAYMENT_ALREADY_COMPLETED`. The previous plan change applies. | | The link could not be cancelled | `503` `PLAN_CHANGE_LINK_CANCEL_FAILED`. Nothing changed, so you can retry. | Each `change-plan` request issues its own invoice. The replaced plan change and its invoice are cancelled. > [!NOTE] > > See the [Subscription Upgrade & Downgrade Guide](/developer-resources/subscription-upgrade-downgrade#collecting-payment-via-a-checkout-link) for the full flow, including declined payments, replacing a pending link, and what happens if the link expires. ## Discount Codes You can apply one or more **stacked discount codes** when changing plans by passing the `discount_codes` array (max 20 entries, applied in array order). The singular `discount_code` field is deprecated but still works for existing integrations; it cannot be combined with `discount_codes` in the same request. | `discount_codes` value | Behavior | | - | - | | Not provided (`null` / omitted) | Existing discounts with `preserve_on_plan_change=true` are preserved if applicable to the new product. | | `[]` (empty array) | **All** existing discounts are removed from the subscription. | | `["CODE_A", "CODE_B", ...]` | Replaces any existing discounts with this stacked set, validated and applied in array order. | > [!TIP] > > Use discount codes during plan changes to offer promotional pricing on upgrades, or pass codes when migrating customers to a new plan tier. > [!TIP] > > Use `prevent_change` for critical upgrades where you want to ensure payment before granting access to premium features. # Create Charge (On-Demand) Source: https://docs.dodopayments.com/api-reference/subscriptions/create-charge post /subscriptions/{subscription_id}/charge Create a charge for a subscription. This is useful for on-demand billing. # Get Subscription Detail Source: https://docs.dodopayments.com/api-reference/subscriptions/get-subscriptions get /subscriptions/{subscription_id} Get detailed information about a specific subscription. # List Subscriptions Source: https://docs.dodopayments.com/api-reference/subscriptions/get-subscriptions-1 get /subscriptions Get a list of all subscriptions associated with your account. # Get the Upcoming Invoice of a Subscription Source: https://docs.dodopayments.com/api-reference/subscriptions/get-upcoming-invoice get /subscriptions/{subscription_id}/upcoming-invoice Price the next cycle invoice of an invoice-led subscription before it is issued. # Get Subscription Usage History Source: https://docs.dodopayments.com/api-reference/subscriptions/get-usage-history get /subscriptions/{subscription_id}/usage-history Retrieve the complete usage history for a subscription with usage-based billing. # Update Subscription Source: https://docs.dodopayments.com/api-reference/subscriptions/patch-subscriptions patch /subscriptions/{subscription_id} Update a subscription's details. # Create Subscription Source: https://docs.dodopayments.com/api-reference/subscriptions/post-subscriptions post /subscriptions Deprecated: create a subscription for a customer. Use Create Checkout Session (POST /checkouts) for new subscription integrations. > [!WARNING] > > **Deprecated API**: This endpoint is deprecated and will be removed in a future release. We recommend using [Checkout Sessions](/api-reference/checkout-sessions/create) instead, which provides a more powerful and customizable API to create payment links for one-time payments and subscriptions. # Preview Plan Change Source: https://docs.dodopayments.com/api-reference/subscriptions/preview-change-plan post /subscriptions/{subscription_id}/change-plan/preview Preview the effects of a subscription plan change before committing to it. Returns the immediate charge amount and the new subscription details without making any actual changes. > [!NOTE] > > Use this endpoint to show customers exactly what they'll be charged when upgrading or downgrading their subscription, improving transparency and reducing support requests. ## Use Cases * **Checkout confirmation**: Display the prorated charge before customers confirm a plan change * **Pricing calculators**: Build upgrade/downgrade calculators in your application * **Customer self-service**: Let customers explore plan options with accurate pricing * **Discount validation**: Preview how stacked discount codes affect the plan change pricing > [!NOTE] > > You can include `discount_codes` (an array of up to 20 codes, applied in order) in the preview request to see how the stacked discounts affect the immediate charge and new plan pricing before committing to the change. The singular `discount_code` field is deprecated but still supported for backward compatibility; we recommend `discount_codes` going forward. ## Response Fields The preview response includes: | Field | Description | | - | - | | `immediate_charge` | The charge that would be created immediately, including line items and summary | | `new_plan` | The full subscription object showing how it would look after the plan change | > [!TIP] > > The `immediate_charge.summary` contains the total amount that would be charged. Use this to display pricing to your customers before they confirm the plan change. # Retrieve Credit Usage Source: https://docs.dodopayments.com/api-reference/subscriptions/retrieve-credit-usage get /subscriptions/{subscription_id}/credit-usage Retrieve the credit usage for a subscription. # Update Payment Method Source: https://docs.dodopayments.com/api-reference/subscriptions/update-payment-method post /subscriptions/{subscription_id}/update-payment-method Update the payment method for an existing subscription. You can either add a new payment method or use an existing one from the customer's saved payment methods. Update the payment method for a subscription. This endpoint supports both active subscriptions and subscriptions in `on_hold` state. > [!NOTE] > > For subscriptions in `on_hold` state, updating the payment method automatically creates a charge for remaining dues, generates an invoice, and reactivates the subscription to `active` state upon successful payment. > [!NOTE] > > For an invoice-led subscription, billing charges the open invoices after the change, so the response has no payment. ### Use Cases * **Active subscriptions**: Update payment method when a card expires or customer wants to use a different payment method * **On hold subscriptions**: Reactivate subscriptions that went on hold due to failed payments by updating the payment method * **Payment method management**: Switch between saved payment methods or add new ones > [!NOTE] > > To list existing payment methods for a customer, use the [List Payment Methods API](/api-reference/customers/get-customer-payment-methods). This helps you retrieve available payment method IDs when using `type: "existing"` to update a subscription's payment method. ### Behavior for Active Subscriptions When updating the payment method for an active subscription: * The payment method is updated immediately * No charge is created * The subscription remains active * Future renewals will use the new payment method ### Behavior for On Hold Subscriptions When updating the payment method for a subscription in `on_hold` state: 1. A charge is automatically created for remaining dues 2. An invoice is generated for the charge 3. The payment is processed using the new payment method 4. Upon successful payment, the subscription is reactivated to `active` state 5. You'll receive webhook events: `payment.succeeded` followed by `subscription.active` > [!WARNING] > > If the payment fails after updating the payment method for an `on_hold` subscription, the subscription will remain in `on_hold` state. Monitor webhook events to track payment status. ### Webhook Events When updating a payment method for an `on_hold` subscription, you'll receive the following webhook events: 1. **`payment.succeeded`** - The charge for remaining dues was successful 2. **`subscription.active`** - The subscription has been reactivated # Transaction Failures Source: https://docs.dodopayments.com/api-reference/transaction-failures Understand every Dodo Payments transaction failure code, whether it is a soft or hard decline, and the recommended action to recover the payment. ## Overview When a payment attempt fails, Dodo Payments returns a standardized failure code that tells you why. The codes are the same across payment methods and payment processors, so one set of handling rules covers every failed payment. The `payment.failed` webhook and the payment object expose these fields for a failed payment: * `error_code`: a standardized failure code from the table below. * `error_message`: an explanation written for **you**, the merchant. When `error_code` is one of the standardized codes below, this is a headline plus the recommended action, not the raw text from the payment processor. * `retry_attempt`: `0` for the original charge, and `1` or higher for each subscription renewal retry, scheduled or [manual](/features/recovery/manual-retry). Payments that are not subscription renewals keep the value `0`. Use these codes to give customers clear feedback, decide whether a retry can succeed, and recover more revenue. ### Merchant Copy vs. Customer Copy Each standardized failure code maps to two messages, one for you and one for your customer: | Audience | Where it appears | What it says | | - | - | - | | **You** | `error_message` on the payment, the payment details page in the dashboard, and the payment-failed email that merchants receive | The real reason plus a recommended action, for example *"The card hasn't been activated by the cardholder. Ask the customer to activate it with their bank, then retry."* | | **Your customer** | The checkout failure screen, the [Customer Portal](/features/customer-portal), and [dunning](/features/recovery/subscription-dunning) emails | A short, plain-language explanation they can act on, for example *"Your card hasn't been activated yet. Please activate it with your bank and try again."* | > [!NOTE] > > The Customer Portal returns the customer wording in `error_message`, while the merchant API returns the merchant wording for the same payment. The `error_code` is the same in both. > [card] [Handle Payment Failures](/developer-resources/handle-payment-failures) > > A step-by-step developer guide for reading these codes from webhooks and the API, showing them to customers, and deciding when to retry. ## Soft vs. Hard Declines Each failure code is either a soft decline or a hard decline. The type tells you whether a later attempt with the same payment details can succeed, or whether the customer must act first. | Decline type | What it means | What to do | Examples | | - | - | - | - | | **Soft decline** | Temporary. The same payment details can succeed on a later attempt. | Retry after a delay. | `INSUFFICIENT_FUNDS`, `GENERIC_DECLINE`, `DO_NOT_HONOR`, `TRANSACTION_NOT_ALLOWED`, `CARD_VELOCITY_EXCEEDED`, `PROCESSING_ERROR`, `NETWORK_ERROR`, `NETWORK_TIMEOUT`, `TRY_AGAIN_LATER` | | **Hard decline** | A retry with the same payment details and no action from the customer does not change the outcome. | Do **not** retry the same details. Ask the customer to correct their details, complete authentication, contact their bank, or use a different payment method. | `STOLEN_CARD`, `LOST_CARD`, `PICKUP_CARD`, `FRAUDULENT`, `TRANSACTION_NOT_APPROVED`, `INVALID_ACCOUNT`, `INCORRECT_CVC` | For subscription renewals, Dodo Payments applies this classification automatically. [Subscription Payment Retries](/features/recovery/payment-retries) re-attempt soft declines. A hard decline ends the retry chain immediately; recover it with [Subscription Dunning](/features/recovery/subscription-dunning). The same classification gates [Manual Retry](/features/recovery/manual-retry): if the latest failure on the invoice is a hard decline, [`POST /payments/{payment_id}/retry`](/api-reference/payments/retry-payment) fails with `MANUAL_RETRY_HARD_DECLINE`. > [!WARNING] > > **Never reveal the real reason for `STOLEN_CARD`, `LOST_CARD`, `PICKUP_CARD`, or `FRAUDULENT` to the customer.** Revealing these reasons can alert a fraudulent actor. Show the customer a generic decline message (for example, *"Your card was declined. Please contact your bank or use another card."*), and log the specific code only internally. > > Dodo Payments applies this rule on the surfaces it controls. For these four codes, checkout, the Customer Portal, and dunning emails show a generic decline message, while your merchant copy keeps the real reason. Apply the same rule anywhere you show `error_message` from the merchant API to a customer. ## Transaction Failure Reasons The following table lists every failure code with its decline type, whether the customer can resolve it, a description, and the recommended action. | Failure Code | Type | User Error | Description | Recommended Action | | - | - | - | - | - | | `AUTHENTICATION_FAILURE` | Hard | Yes | The customer couldn't complete 3DS authentication with their bank | Ask the customer to retry and complete 3DS authentication, or use another card | | `AUTHENTICATION_REQUIRED` | Hard | Yes | The bank requires additional 3DS authentication to complete the transaction | Prompt the customer to complete 3DS authentication. For subscription renewals, ask the customer to return and authenticate | | `AUTHENTICATION_TIMEOUT` | Soft | Yes | Authentication timed out before the customer completed it | Ask the customer to retry and complete authentication promptly | | `CARD_DECLINED` | Soft | No | The issuing bank declined the card without a specific reason (generic decline) | Ask the customer to retry, contact their bank, or use another card | | `CARD_NOT_ACTIVATED` | Soft | Yes | The cardholder has not activated the card | Ask the customer to activate the card with their bank, then retry | | `CARD_VELOCITY_EXCEEDED` | Soft | Yes | Too many transactions were attempted in a short period | Ask the customer to wait and retry later, or contact their bank about limits | | `CUSTOMER_CANCELLED` | Hard | Yes | The customer cancelled the transaction | Let the customer restart checkout when they are ready | | `DO_NOT_HONOR` | Soft | No | The issuing bank refused the transaction (ISO 8583 code 05, do not honor) without giving a reason | Retry after a delay. With payment retries on, Dodo Payments retries renewals automatically. If the retries fail, ask the customer to contact their bank or use another payment method | | `EXPIRED_CARD` | Hard | Yes | The card has expired | Ask the customer to use a card with a valid expiry date | | `FRAUDULENT` | Hard | Yes | The transaction was flagged as potentially fraudulent and declined | Don't retry this card. Show the customer a generic decline message, without the reason, and ask them to use another payment method | | `GENERIC_DECLINE` | Soft | No | The transaction was declined for an unspecified reason | Ask the customer to contact their bank or try another card | | `INCORRECT_CVC` | Hard | Yes | The CVC entered was incorrect | Ask the customer to re-enter the correct CVC | | `INCORRECT_NUMBER` | Hard | Yes | The card number was entered incorrectly | Ask the customer to re-enter the correct card number | | `INSUFFICIENT_FUNDS` | Soft | Yes | The account doesn't have enough funds to complete the transaction | Ask the customer to use another payment method or retry once funds are available | | `INVALID_ACCOUNT` | Hard | Yes | The account details provided are invalid | Ask the customer to contact their bank or use another card | | `INVALID_AMOUNT` | Hard | Yes | The bank rejected the transaction amount | Verify the amount and any purchase limits with the customer | | `INVALID_CARD_NUMBER` | Hard | Yes | The card number format is invalid | Ask the customer to re-enter a valid card number | | `INVALID_CARD_OWNER` | Hard | Yes | The cardholder name is invalid | Ask the customer to correct the cardholder name | | `INVALID_CVC` | Hard | Yes | The CVC format is invalid | Ask the customer to re-enter a valid CVC | | `INVALID_EXPIRY_YEAR` | Hard | Yes | The card expiry year is invalid | Ask the customer to enter a valid expiry date | | `INVALID_PIN` | Hard | Yes | The PIN entered is incorrect | Ask the customer to re-enter the correct PIN | | `INVALID_REQUEST` | Hard | Yes | The transaction request contains invalid data | Check the payment request fields and resubmit with valid data | | `INVALID_UPI_ID` | Hard | Yes | The UPI ID provided is invalid | Ask the customer to enter a valid UPI ID | | `LIMIT_EXCEEDED` | Soft | Yes | The transaction exceeds the card or account limit | Ask the customer to contact their bank about limits, or use another method | | `LIVE_MODE_TEST_CARD` | Hard | Yes | A test card was used in live mode | Use a real card. A test card always fails in live mode | | `LOST_CARD` | Hard | Yes | The card has been reported as lost | Don't retry. Show the customer a generic decline message, without the reason, and ask them to use another card | | `MANDATE_INVALID` | Hard | Yes | The payment mandate is invalid | Ask the customer to set up the payment mandate again | | `MANDATE_REQUIRED` | Hard | Yes | A mandate is required for this transaction | Set up a mandate and ask the customer to authorize it before charging | | `MANDATE_REQUIRED_SYSTEM` | Hard | No | This transaction type requires a mandate that wasn't set up | Complete the mandate setup flow before charging | | `NETWORK_ERROR` | Soft | No | A network error occurred during the transaction | Transient. Retry the payment after a short delay | | `NETWORK_TIMEOUT` | Soft | No | The network request timed out | Transient. Retry the payment after a short delay | | `ORDER_ALREADY_EXISTS` | Hard | No | An order already exists for this transaction (duplicate order creation) | Check the status of the existing order before retrying. Contact support if it persists | | `ORDER_CREATION_FAILED` | Soft | No | The order for the transaction could not be created | Transient or system error. Retry the payment, and contact support if it persists | | `PAYMENT_METHOD_PROVIDER_DECLINED` | Hard | Yes | The payment method provider declined the transaction | Ask the customer to contact their provider or use another payment method | | `PAYMENT_METHOD_UNSUPPORTED` | Hard | Yes | The payment method is not supported for this transaction | Ask the customer to use a supported payment method | | `PICKUP_CARD` | Hard | Yes | The card has been reported as lost or stolen and flagged for pickup | Don't retry. Show the customer a generic decline message, without the reason, and ask them to use another card | | `PROCESSING_ERROR` | Soft | No | An error occurred while processing the transaction | Transient. Retry the payment. If it persists, ask the customer to contact their bank | | `PROVIDER_UNSUPPORTED` | Hard | No | The payment provider does not support this transaction type | Ask the customer to use another payment method | | `REENTER_TRANSACTION` | Soft | Yes | The transaction needs to be entered again | Ask the customer to retry the payment | | `REVOCATION_OF_AUTHORIZATION` | Hard | Yes | The cardholder revoked authorization for this payment | Ask the customer to use another payment method | | `STOLEN_CARD` | Hard | Yes | The card has been reported as stolen, or the issuer restricted it because it may be lost or stolen | Don't retry. Show the customer a generic decline message, without the reason, and ask them to use another card | | `SUBSCRIPTION_NOT_ACTIVE` | Hard | No | The subscription is not active, so the recurring charge could not be processed | Reactivate the subscription (for example, by updating the payment method) before you attempt the charge again | | `TRANSACTION_NOT_ALLOWED` | Soft | Yes | The bank doesn't allow this transaction type on this card | Retry after a delay. With payment retries on, Dodo Payments retries renewals automatically. If the retries fail, ask the customer to contact their bank to allow this transaction type, or use another card | | `TRANSACTION_NOT_APPROVED` | Hard | Yes | The cardholder didn't approve a recurring payment above the mandate amount or INR 15,000, as Indian e-mandate rules require | Don't retry. Ask the customer to approve the payment with their bank, or to use another card | | `TRY_AGAIN_LATER` | Soft | No | The bank asked for the transaction to be retried later | Transient. Retry the payment later | | `UNKNOWN_ERROR` | Soft | No | An unknown error occurred | Retry the payment. If it persists, contact support | > [!NOTE] > > **User Error** shows whether the customer can resolve the decline. `Yes` means the customer can fix the issue, for example by entering correct card details. `No` means a system-level issue or a bank restriction caused the decline, and the customer can't resolve it directly. > [!NOTE] > > An issuing bank can also decline a card because its own risk engine flags the cardholder as high-risk, independent of the merchant or the transaction details. These declines usually appear as generic codes such as `DO_NOT_HONOR`, `GENERIC_DECLINE`, `CARD_DECLINED`, or `FRAUDULENT`. The bank doesn't share the specific reason, and neither Dodo Payments nor the merchant can override the decision. Ask the customer to contact their bank to resolve the flag, or to use a different card or payment method. ## Handling Failures Programmatically Read `error_code` from the `payment.failed` webhook or the payment object, map it to the recommended action in the table, and decide whether to retry. For subscription renewals, Dodo Payments retries soft declines for you. See [Subscription Payment Retries](/features/recovery/payment-retries). For API and business-logic errors that are not card declines, such as `PAYMENT_NOT_SUCCEEDED` or `REFUND_WINDOW_EXPIRED`, see the [Error Codes](/api-reference/error-codes) reference. ## Related > [card] [Handle Payment Failures](/developer-resources/handle-payment-failures) > > End-to-end guide to detecting, surfacing, and retrying failed payments. > [card] [Error Codes](/api-reference/error-codes) > > API and business-logic error codes for non-decline failures. > [card] [Subscription Payment Retries](/features/recovery/payment-retries) > > Automatic retries that recover soft declines on subscription renewals. > [card] [Subscription Dunning](/features/recovery/subscription-dunning) > > Email sequences that recover hard declines by prompting a payment method update. ## Support For more help with transaction failures or integration issues, contact the support team at [support@dodopayments.com](mailto:support@dodopayments.com). # Build a Prepaid Email Service with Credit-Based Billing Source: https://docs.dodopayments.com/developer-resources/build-a-prepaid-email-service-with-credit-based-billing Build MailKit, a prepaid transactional email service with Dodo Payments and Resend: a monthly credit plan, top-up packs, a debit per send, and low-balance alerts. > [!TIP] > > To have your coding agent write the integration, install the [Dodo Agent Plugin](/developer-resources/build-with-ai-coding-agents). It adds the Dodo Payments skills and MCP servers to Claude Code, Codex CLI, Cursor, VS Code / GitHub Copilot, Kiro, and OpenCode. You'll build **MailKit**, a transactional email service where customers prepay for email credits. A monthly plan grants 5,000 emails per billing cycle. A customer who runs low buys a top-up pack instead of waiting for the next cycle. Each send debits one credit. > [!NOTE] > > This tutorial uses [Resend](https://resend.com) as the email provider. Its free tier (3,000 emails per month) covers building and testing the whole flow. The billing pattern works with any provider: replace `resend.emails.send` with a call to SendGrid, Postmark, Amazon SES, or your own SMTP relay. When you finish, you'll know how to: * Create a custom credit entitlement for emails in the dashboard. * Attach credits to a subscription plan and a one-time top-up product. * Send email through Resend and debit one credit per send with a ledger entry. * Read a customer's live credit balance from your frontend. * Verify Dodo Payments webhooks and handle `credit.balance_low` to warn customers before their balance reaches zero. ## What We're Building MailKit sells two products: | Product | Price | Emails | | - | - | - | | MailKit Plan | \$19/month | 5,000 emails per billing cycle | | Top-Up Pack | \$9 one-time | +5,000 emails | The unit is **one email = one credit**. Customers don't need to reason about tokens, batches, or weighted units. They see "4,231 emails left this month." Before you start, you need: * A Dodo Payments account. Build everything in test mode. * A free [Resend](https://resend.com) account and API key. * Node.js 22 or later, and working knowledge of TypeScript. ## Step 1: Create Your Email Credit Entitlement The credit entitlement defines the unit MailKit sells: one email send. ![Credits tab under Products, listing the business's credit entitlements](https://mintcdn.com/dodopayments/Uc5BUwzydK5AJ2P-/images/CBB/Desktop%20-%20Cookbook%20-%20Credits.png?fit=max\&auto=format\&n=Uc5BUwzydK5AJ2P-\&q=85\&s=7cb0896037c7e8578bf85f2009c26837) The Credits tab under Products lists all your credit entitlements. **1. Open the Credits Section** 1. Log in to the Dodo Payments dashboard. 2. Click **Products** in the sidebar. 3. Select the **Credits** tab. 4. Click **Create Credit**. **2. Configure the Credit Unit** Enter these values: **Credit Name**: `Email Credits` **Credit Type**: **Custom Unit** **Unit Name**: `email` **Define Precision**: `0`. An email is a whole unit, so the balance never needs decimals. **Credit Expiry**: `30 days`. Unused credits expire 30 days after they're issued. > [!WARNING] > > Precision can't be changed after you create the credit. For discrete units such as emails, messages, or sessions, use `0`. **3. Leave the Other Defaults** This tutorial leaves rollover and overage off to keep the credit flow minimal. You can turn them on later, either on the credit or on each product's credit attachment. **4. Save and Copy the Credit ID** Click **Create Credit**. Open the credit and copy its ID, which starts with `cde_`. The backend uses it for balance reads and ledger entries. > [!TIP] > > The `Email Credits` entitlement is ready. Next, create the products that grant it to customers. ## Step 2: Create the Plan and Top-Up Pack Create two products that attach the same `Email Credits` entitlement: a **Subscription** plan that grants 5,000 emails each billing cycle, and a **One Time** top-up that adds 5,000 more on demand. > [!TIP] > > This tutorial debits credits with ledger entries instead of usage meters. A ledger debit is applied when the API call returns, needs no meter setup, and fits cases where one user action costs exactly one credit. To deduct credits automatically from ingested usage events, which suits weighted units such as tokens or megabytes processed, see [Usage Billing with Credits](/features/credit-based-billing) in the Credit-Based Billing guide. ### MailKit Plan (\$19/month, 5,000 Emails) **1. Create the Subscription** 1. Go to **Products** and click **Add Product**. 2. Enter the product details: **Product Name**: `MailKit Plan` **Description**: `5,000 transactional emails per month.` 3. Under **Pricing Type**, select **Subscription**. 4. Set the recurring price: **Price**: `19.00` **Repeat payment every**: `1` month **Currency**: `USD` **2. Attach the Email Credit Entitlement** In the **Entitlements** section, click **Attach** next to **Credits** and configure: **Select credits**: `Email Credits` **Credits issued per billing cycle**: `5000` **Low Balance Threshold (%)**: `20`. Dodo Payments sends `credit.balance_low` when the balance falls below 20% of the credits issued per cycle, which is 1,000 emails. **Import Default Credit Settings**: on, so the product uses the 30-day expiry from Step 1. Add the credit to the product, then save the product. Copy the product ID, which starts with `pdt_`. > [!TIP] > > Plan: \$19/month, with 5,000 emails issued each billing cycle. ### Top-Up Pack (\$9 One-Time, 5,000 Emails) **1. Create a One-Time Product** 1. Go to **Products** and click **Add Product**. 2. Enter the product details: **Product Name**: `Email Top-Up Pack` **Description**: `Add 5,000 emails to your MailKit balance.` 3. Under **Pricing Type**, select **One Time**. 4. Set the price: **Price**: `9.00` **Currency**: `USD` **2. Attach the Credit Grant** In the **Entitlements** section, click **Attach** next to **Credits** and configure: * **Select credits**: `Email Credits` * **No of credits issued**: `5000` > [!NOTE] > > A one-time product grants credits with their own expiry: 30 days from purchase, from the default you set in Step 1. Top-up credits add to the subscription credits. They don't replace them. Save the product and copy its ID. > [!TIP] > > Top-Up Pack: \$9 for 5,000 emails, added to the balance after the payment succeeds. ## Step 3: Set Up the Backend Build the Express server that creates checkouts, sends email, reads balances, and receives webhooks. **1. Initialize the Project** ```bash theme={null} mkdir mailkit && cd mailkit npm init -y npm install dodopayments resend express dotenv npm install -D tsx @types/node @types/express ``` Add a dev script to `package.json`: ```json theme={null} { "scripts": { "dev": "tsx watch server.ts" } } ``` > [!TIP] > > [`tsx`](https://tsx.is) runs TypeScript directly, without a build step or a `tsconfig.json`. For production, add a `tsconfig.json` and a `build` script. **2. Configure Environment Variables** Create `.env` with a test mode API key from **Developer → API Keys** and the IDs from Steps 1 and 2: ```bash .env theme={null} # Dodo Payments DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your_dodo_webhook_signing_secret CREDIT_ENTITLEMENT_ID=cde_xxxxxxxxxxxx PLAN_PRODUCT_ID=pdt_xxxxxxxxxxxx TOPUP_PRODUCT_ID=pdt_xxxxxxxxxxxx # Resend RESEND_API_KEY=re_xxxxxxxxxxxx # App BASE_URL=http://localhost:3000 PORT=3000 ``` You fill in `DODO_PAYMENTS_WEBHOOK_KEY` in Step 4, after you create the webhook endpoint. Create the Resend API key at [resend.com/api-keys](https://resend.com/api-keys). > [!WARNING] > > Add `.env` to `.gitignore` before your first commit. Never commit API keys. **3. Build the Server** Create `server.ts` in the project root. The server exposes five routes: subscribe checkout, top-up checkout, balance read, send, and the webhook receiver. ```typescript server.ts expandable theme={null} import 'dotenv/config'; import express, { Request, Response } from 'express'; import DodoPayments from 'dodopayments'; import { Resend } from 'resend'; const app = express(); const dodo = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY!, webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY!, environment: 'test_mode', }); const resend = new Resend(process.env.RESEND_API_KEY!); const CREDIT_ENTITLEMENT_ID = process.env.CREDIT_ENTITLEMENT_ID!; const BASE_URL = process.env.BASE_URL!; // --------------------------------------------------------------- // Webhook endpoint MUST receive the raw body for signature // verification. Register it BEFORE express.json(). // --------------------------------------------------------------- app.post( '/webhooks/dodo', express.raw({ type: 'application/json' }), async (req: Request, res: Response) => { const headers = { 'webhook-id': req.headers['webhook-id'] as string, 'webhook-signature': req.headers['webhook-signature'] as string, 'webhook-timestamp': req.headers['webhook-timestamp'] as string, }; let event: any; try { event = await dodo.webhooks.unwrap(req.body.toString('utf8'), { headers }); } catch (err) { console.error('Webhook signature verification failed:', err); return res.status(401).json({ error: 'invalid signature' }); } switch (event.type) { case 'credit.balance_low': { const { customer_id, credit_entitlement_name, available_balance, threshold_percent } = event.data; console.log( `[low-balance] ${customer_id} has ${available_balance} ${credit_entitlement_name} ` + `left (under ${threshold_percent}%)` ); await notifyCustomerLowBalance(customer_id, Number(available_balance)); break; } case 'credit.added': console.log('[credit.added]', event.data); break; case 'credit.rolled_over': console.log('[rolled_over]', event.data); break; } res.json({ received: true }); } ); // JSON parsing for everything else. app.use(express.json()); // --------------------------------------------------------------- // POST /checkout/subscribe → start the MailKit subscription. // --------------------------------------------------------------- app.post('/checkout/subscribe', async (req, res) => { const { email, name } = req.body as { email: string; name: string }; const session = await dodo.checkoutSessions.create({ product_cart: [{ product_id: process.env.PLAN_PRODUCT_ID!, quantity: 1 }], customer: { email, name }, return_url: `${BASE_URL}/?subscribed=1`, }); res.json({ checkout_url: session.checkout_url }); }); // --------------------------------------------------------------- // POST /checkout/topup → buy a 5,000-email top-up for an existing // customer. In a real app, customer_id is resolved from the // authenticated session, never trusted from request input. // --------------------------------------------------------------- app.post('/checkout/topup', async (req, res) => { const { customer_id } = req.body as { customer_id: string }; const session = await dodo.checkoutSessions.create({ product_cart: [{ product_id: process.env.TOPUP_PRODUCT_ID!, quantity: 1 }], customer: { customer_id }, return_url: `${BASE_URL}/?topped_up=1`, }); res.json({ checkout_url: session.checkout_url }); }); // --------------------------------------------------------------- // GET /credits/:customerId → live balance for the dashboard widget. // --------------------------------------------------------------- app.get('/credits/:customerId', async (req, res) => { const balance = await dodo.creditEntitlements.balances.retrieve(req.params.customerId, { credit_entitlement_id: CREDIT_ENTITLEMENT_ID, }); res.json({ balance: balance.balance }); }); // --------------------------------------------------------------- // POST /send → send an email via Resend, then write a ledger entry // to debit 1 credit from the customer's balance. The deduction is // instant; the next /credits call reflects it. // --------------------------------------------------------------- app.post('/send', async (req, res) => { const { customer_id, to, subject, html } = req.body as { customer_id: string; to: string; subject: string; html: string; }; // 1. Pre-flight balance check: refuse to send if the balance is at zero. const balance = await dodo.creditEntitlements.balances.retrieve(customer_id, { credit_entitlement_id: CREDIT_ENTITLEMENT_ID, }); if (Number(balance.balance) <= 0) { return res.status(402).json({ error: 'No email credits remaining. Buy a top-up pack or upgrade your plan.', }); } // 2. Send via Resend. const { data, error } = await resend.emails.send({ from: 'MailKit ', // swap for your verified domain to: [to], subject, html, }); if (error) { return res.status(500).json({ error: error.message }); } // 3. Debit 1 credit. Resend's message ID is the idempotency key: if this // ledger call is repeated for the same send, Dodo Payments rejects the // duplicate with 409 Conflict instead of debiting the customer twice. await dodo.creditEntitlements.balances.createLedgerEntry(customer_id, { credit_entitlement_id: CREDIT_ENTITLEMENT_ID, amount: '1', entry_type: 'debit', reason: `email send ${data!.id}`, idempotency_key: data!.id, }); res.json({ id: data!.id }); }); async function notifyCustomerLowBalance(customerId: string, available: number) { // In production: send an email to the account owner, push a banner, // open an in-app modal, etc. For the demo we just log. console.log(`[NOTIFY] ${customerId}: ${available} emails left. Consider topping up.`); } app.use(express.static('public')); const port = Number(process.env.PORT) || 3000; app.listen(port, () => { console.log(`MailKit running on http://localhost:${port}`); }); ``` > [!WARNING] > > The webhook route must receive the raw request body. `express.json()` replaces the body with a parsed object, and signature verification needs the exact bytes Dodo Payments signed. Keep the `/webhooks/dodo` route, with `express.raw()`, above the `app.use(express.json())` line. > [!TIP] > > The backend is ready: subscribe, top-up, balance, send, and the webhook handler. **4. Add a Demo UI** Create `public/index.html`. It calls each route from a simple form, so you can test the flow in a browser: ```html public/index.html expandable theme={null} MailKit Demo

MailKit

Prepaid transactional email, billed per send.

1. Subscribe to MailKit ($19/mo, 5,000 emails)

2. Check your balance

3. Send a transactional email

4. Run low? Buy a top-up pack

``` ## Step 4: Wire Up the Webhook Endpoint The `credit.balance_low` event lets you warn customers before they run out. Without it, a customer first notices the problem when an email fails to send. **1. Expose Your Local Server** Webhooks need a public URL. While you develop, use [ngrok](https://ngrok.com) or another tunnel: ```bash theme={null} ngrok http 3000 ``` Copy the HTTPS forwarding URL, for example `https://1234abcd.ngrok-free.app`. **2. Register the Endpoint in Dodo Payments** 1. Go to **Developer → Webhooks** and click **Add endpoint**. 2. Enter the URL `https://1234abcd.ngrok-free.app/webhooks/dodo`, using your own tunnel host. 3. Select the events `credit.added`, `credit.balance_low`, and `credit.rolled_over`. 4. Click **Create endpoint**. 5. Copy the signing secret from the endpoint's **Overview** tab into `.env` as `DODO_PAYMENTS_WEBHOOK_KEY`. 6. Restart the server. ## Step 5: Test the Full Flow **1. Start the Server** ```bash theme={null} npm run dev ``` The server logs `MailKit running on http://localhost:3000`. Open that URL in your browser. **2. Subscribe a Test Customer** 1. In section 1, enter a test email address and name, then click **Get checkout link**. 2. Open the link and complete checkout with a [test card](/miscellaneous/testing-process). 3. In the dashboard, go to **Customers** and copy the new customer's ID, which starts with `cus_`. > [!TIP] > > The customer has **5,000 emails** in their balance. To confirm, open the customer in **Customers** and select the **Credits** tab. **3. Send an Email** 1. Paste the customer ID into section 3. 2. Leave **To** set to `delivered@resend.dev`, a Resend test address that accepts every message. 3. Click **Send**. The page shows the Resend message ID. Refresh the balance in section 2: it reads 4,999. A ledger debit is part of the balance as soon as the API call returns. **4. Trigger the Low-Balance Webhook** The threshold is 20%, or 1,000 of the 5,000 emails issued per cycle. To reach it without sending 4,000 emails, debit the balance manually in the dashboard: 1. Open the customer in **Customers**, select the **Credits** tab, and choose **Email Credits**. 2. Click **Apply Credit/Debit**, select **Debit**, and enter `4000`. The balance is now exactly 1,000, which isn't below the threshold yet. 3. Send one more email from the demo. The balance drops to 999. When the webhook arrives, the server logs: ```text theme={null} [low-balance] cus_xxx has 999 Email Credits left (under 20%) [NOTIFY] cus_xxx: 999 emails left. Consider topping up. ``` > [!TIP] > > The server received and verified the webhook. In production, this is where you email the customer or show an in-app banner. **5. Buy a Top-Up Pack** 1. Paste the customer ID into section 4. 2. Click **Buy 5,000 emails** and complete the test checkout. 3. Refresh the balance. It increases by 5,000. > [!TIP] > > Dodo Payments sends a `credit.added` event with `transaction_type: "credit_added"`. The grant behind it has `source_type: one_time`, which you can read back with the [List Customer Grants](/api-reference/credit-entitlements/list-customer-grants) API. Top-up credits add to the subscription credits. Ledger debits draw from existing grants in FIFO order, oldest grant first. **6. Test the Hard Stop** Debit the balance to zero in the dashboard, then try to send one more email. The server responds with `402`: ```json theme={null} { "error": "No email credits remaining. Buy a top-up pack or upgrade your plan." } ``` That `402` is your application's enforcement. Treat the Dodo Payments balance API as the source of truth, and don't cache the balance on the client. ## Troubleshooting > [accordion] Webhook signature verification fails (401) > > The signature covers the raw HTTP body. `express.json()` replaces the body with a parsed object, so verification fails. Register `/webhooks/dodo` with `express.raw({ type: 'application/json' })` above the `app.use(express.json())` line. Then check that `DODO_PAYMENTS_WEBHOOK_KEY` matches the signing secret on the endpoint's **Overview** tab. > [accordion] Balance is 0, customer not found, or credits don't deduct > > Check these three things, in order: > > 1. The customer **completed checkout**. Credits are issued when the payment succeeds, not when the checkout session is created. > 2. `CREDIT_ENTITLEMENT_ID` in `.env` matches the credit attached to the product. The balance and ledger calls use this ID, so a mismatch reads or debits a different credit. > 3. The `customer_id` you pass is the Dodo Payments customer ID (it starts with `cus_`), not an ID from your own database. > [accordion] Resend rejects the recipient > > The test sender `onboarding@resend.dev` delivers only to the email address on your Resend account, or to `delivered@resend.dev`. To send to anyone else, [verify a domain](https://resend.com/docs/dashboard/domains/introduction) and use a `from` address on that domain. ## What You Built > [card] One Reusable Credit Unit > > `Email Credits`, defined once and attached to both the subscription plan and the top-up pack. > [card] Subscription with Prepaid Allowance > > \$19/month grants 5,000 emails per billing cycle. Customers know what they pay for, and you know your maximum cost. > [card] Top-Up Pack > > A one-time product that grants 5,000 emails on top of subscription credits, with no plan change. > [card] Direct Ledger Debits > > One `createLedgerEntry` call after each send, with no meter and no aggregation delay. The Resend message ID as the idempotency key blocks a second debit for the same send. > [card] [Credit-Based Billing Reference](/features/credit-based-billing) > > Rollover, overage modes, ledger management, and the full credit API. For help, ask in the [Discord Community](https://discord.gg/bYqAp4ayYh) or email [support@dodopayments.com](mailto:support@dodopayments.com). # Build an AI API Platform with Credit-Based Billing Source: https://docs.dodopayments.com/developer-resources/build-an-ai-api-platform-with-credit-based-billing Build NeuralAPI, a tiered AI API with token credits. Subscription plans and top-up packs grant credits, and a meter deducts them as customers call your API. > [!TIP] > > To have your coding agent write the integration, install the [Dodo Agent Plugin](/developer-resources/build-with-ai-coding-agents). It adds the Dodo Payments skills and MCP servers to Claude Code, Codex CLI, Cursor, VS Code / GitHub Copilot, Kiro, and OpenCode. You'll build **NeuralAPI**, a tiered AI API where each subscription plan includes a monthly allowance of token credits. Customers who run low buy a top-up pack, and your backend reports the tokens each OpenAI request uses so Dodo Payments deducts them from the customer's balance. > [!NOTE] > > This tutorial uses Node.js, Express, and the OpenAI SDK. The Dodo Payments concepts (credits, meters, and webhooks) work the same with any framework or AI provider. When you finish, you'll know how to: * Create a custom credit entitlement for tokens, and a meter that deducts from it. * Attach credits to subscription plans, with and without overage, and to a one-time top-up product. * Call OpenAI from an endpoint that bills tokens through Dodo Payments. * Read a customer's live credit balance with the SDK. * Verify webhook signatures and route Dodo Payments credit events. ## What We're Building NeuralAPI sells three products: | Product | Price | Tokens | Overage | | - | - | - | - | | Starter Plan | \$29/month | 10,000,000 tokens/cycle | Blocked at zero | | Pro Plan | \$99/month | 40,000,000 tokens/cycle | \$0.005 per 1K tokens | | Token Top-Up Pack | \$19 one-time | +5,000,000 tokens | — | Before you start, you need: * A Dodo Payments account. Build everything in test mode. * An OpenAI API key. * Node.js 22 or later, and working knowledge of TypeScript and Node.js. ## Step 1: Create Your Token Credit Entitlement Create the credit entitlement that both plans and the top-up pack share. It defines the token unit NeuralAPI sells. ![Credits listing page showing created credit entitlements](https://mintcdn.com/dodopayments/eU6ZCQ885P3550bK/images/CBB/Desktop%20-%20Cookbook%20-%20NeuralAPI%20-%20Credit.png?fit=max\&auto=format\&n=eU6ZCQ885P3550bK\&q=85\&s=6c34ed3755c78534dcd6012680e98e40) The Credits tab under Products shows all your credit entitlements. **1. Navigate to Credits** 1. Log in to the Dodo Payments dashboard. 2. Click **Products** in the sidebar. 3. Select the **Credits** tab. 4. Click **Create Credit**. **2. Configure the Credit Unit** Enter these values: **Credit Name**: `API Tokens` **Credit Type**: **Custom Unit** **Unit Name**: `token` **Define Precision**: `0`. Token counts are whole numbers. **Credit Expiry**: `30 days`. Credits expire 30 days after they're issued, which matches the monthly billing cycle. > [!WARNING] > > Precision can't be changed after you create the credit. For token counts, use `0`. **3. Skip Overage at the Credit Level** Leave overage **disabled** on the credit. You configure it per plan when you attach the credit to each product, so the Starter plan can block usage at zero while the Pro plan allows overage. > [!TIP] > > Overage settings on the credit are defaults. Each product attachment can override them, which Step 3 does for the Pro plan. **4. Save and Copy the Credit ID** Click **Create Credit**. Open the saved credit and copy its ID, which starts with `cde_`. > [!TIP] > > The `API Tokens` credit entitlement is ready. Next, create a meter so that usage events deduct credits. ## Step 2: Create a Meter for Token Usage A meter aggregates incoming usage events. When you link it to a credit, the aggregated usage is deducted from the customer's credit balance. Create the meter before the plan products, because you attach it while you create them in Step 3. **1. Open the Meters Section** 1. In the dashboard sidebar, go to **Products → Meters**. 2. Click **Create Meter**. **2. Configure the Meter** Enter these values: **Meter Name**: `Token Usage Meter` **Event Name**: `api.tokens_used`. This must match the `event_name` your app sends. **Aggregation Type**: `Sum`, to add up the token count from each event. **Over Property**: `tokens`, the metadata key whose value is summed. **Measurement Unit**: `tokens` > [!WARNING] > > Event names are case-sensitive: `api.tokens_used` and `Api.Tokens.Used` are different events. After you create a meter, you can change only its name, description, and measurement unit. To change the event name, aggregation, or filter, archive the meter and create a new one, so check every value before you confirm. Create the meter. You select it by name when you attach it to products. > [!TIP] > > The meter is created. Next, link it to the credit on each plan product. ## Step 3: Create the Plan Products Create both plans with the **Usage Based Billing** pricing type, not plain **Subscription**. Meters attach to Usage Based Billing products, and the meter is what deducts credits as customers call your API. A Usage Based Billing product still charges a recurring base fee (\$29 or \$99), and usage on top of it is billed in credits. ![Usage Based Billing pricing configuration](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20UBB.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=41b2862c12d126e7843098307e27e137) Usage Based Billing pricing type with meter configuration. ### Starter Plan (\$29/month — 10M Tokens, No Overage) **1. Create the Starter Product** 1. Go to **Products** and click **Add Product**. 2. Under **Pricing Type**, select **Usage Based Billing**. 3. Enter these values: **Product Name**: `NeuralAPI Starter` **Description**: `10 million API tokens per month. Perfect for individual developers and small projects.` **Price**: `29.00`. This is the recurring base fee, charged every month even before any usage. **Repeat payment every**: `1` month **Currency**: `USD` **2. Attach the Meter** In the **Select meter** section, click **+** and add `Token Usage Meter`. Then configure the meter: 1. Turn on **Bill usage in credits**. 2. **Select credit**: `API Tokens` 3. **Meter units per credit**: `1`. Each token in an event deducts one credit. 4. **Free Threshold**: `0`. The free threshold applies only when a meter bills in money. When it bills in credits, every unit is deducted from the balance. ![Meter with Bill usage in Credits enabled and API Tokens selected](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20UBB-5.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=b4ef2fe5079cbf3bb39eb3814f101cbd) Toggle 'Bill usage in Credits' on the meter and pick the credit entitlement. This link is what makes incoming `api.tokens_used` events deduct from the customer's balance. **3. Configure Credit Issuance for Starter** After you attach a credit-billed meter, the product shows a credit configuration section. Enter: **Credits issued per billing cycle**: `10000000` **Import Default Credit Settings**: on, so the product uses the 30-day expiry from the credit entitlement. **Allow Overage**: off. The default from Step 1 keeps overage disabled, so Starter customers stop at zero. ![Credit configuration form with per-cycle amount and overage settings](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20UBB-6.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=22e99c54f11305a24d63c77e09a4650c) Configure credit issuance per cycle on the UBB product. Save the product and copy its ID, which starts with `pdt_`. > [!TIP] > > Starter Plan: \$29/month base fee, 10M tokens per cycle, blocked at zero, and deducted through the meter. ### Pro Plan (\$99/month — 40M Tokens, Overage Enabled) **1. Create the Pro Product** Follow the Starter flow with these values: **Product Name**: `NeuralAPI Pro` **Description**: `40 million API tokens per month with overage. Built for production applications.` **Price**: `99.00` **Repeat payment every**: `1` month **Currency**: `USD` **2. Attach the Meter** Configure the meter as you did for Starter: add `Token Usage Meter`, turn on **Bill usage in credits**, select `API Tokens`, and set **Meter units per credit** to `1` and **Free Threshold** to `0`. **3. Configure Credit Issuance with Overage** Configure credit issuance, this time with overage enabled: **Credits issued per billing cycle**: `40000000` **Import Default Credit Settings**: off, so you can set overage for this product. **Allow Overage**: on **Price Per Unit**: `0.000005` USD per token. That is \$0.005 per 1K tokens, or \$5 per 1M tokens, which is above the plan's effective per-token rate and discourages overage. **Overage Behavior**: `Bill overage at billing`. Overage is charged on the next invoice, and then the balance resets. Save the product and copy its ID. > [!TIP] > > Pro Plan: \$99/month base fee, 40M tokens per cycle, overage at \$0.005 per 1K tokens, and deducted through the meter. ## Step 4: Create the Token Top-Up Pack The top-up pack is a one-time purchase that adds 5,000,000 tokens to an existing customer's balance. ![Product pricing section with Single Payment selected](https://mintcdn.com/dodopayments/ibNfoFRyCIGyt3pO/images/CBB/Desktop%20-%20Attach%20Credit%20-%20OTP.jpg?fit=max\&auto=format\&n=ibNfoFRyCIGyt3pO\&q=85\&s=1743cb3e515952f9d4b1b2782cebac8b) One-time pricing selected for a credit product. **1. Create a One-Time Product** 1. Go to **Products** and click **Add Product**. 2. Under **Pricing Type**, select **One Time**. 3. Enter these values: **Product Name**: `Token Top-Up Pack` **Description**: `Add 5 million tokens to your NeuralAPI balance.` **Price**: `19.00` **Currency**: `USD` **2. Attach the Token Credit** 1. In the **Entitlements** section, click **Attach** next to **Credits**. 2. Select `API Tokens`. 3. Set **No of credits issued** to `5000000`. 4. Turn off **Import Default Credit Settings** to override the default 30-day expiry. 5. Set **Credit Expiry** to **Custom** and enter `365` days. 6. Save the product. Copy the product ID. > [!TIP] > > Why a longer expiry on top-ups? Subscription credits expire after 30 days because that's the billing cycle. A top-up is a prepaid purchase: the customer paid \$19 upfront and expects the tokens to last longer than a month. A 365-day expiry matches how prepaid API credits work at OpenAI and Anthropic, where purchased credits expire one year after purchase, and still caps your liability so customers can't stockpile credits indefinitely. > [!TIP] > > The Top-Up Pack is configured. Buying it grants 5,000,000 tokens that stay valid for 365 days. ## Step 5: Build the Backend Build the Express server. It creates subscription and top-up checkouts, calls OpenAI and bills the tokens, reads balances, and receives credit webhook events. **1. Set Up Your Project** ```bash theme={null} mkdir neural-api-billing cd neural-api-billing npm init -y npm install dodopayments openai express dotenv npm install -D @types/node @types/express typescript tsx ``` Create a `tsconfig.json`: ```json tsconfig.json theme={null} { "compilerOptions": { "target": "ES2022", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true } } ``` Update `package.json` scripts: ```json package.json theme={null} { "scripts": { "dev": "tsx watch src/server.ts", "build": "tsc", "start": "node dist/server.js" } } ``` **2. Set Up Environment Variables** Create `.env` with a test mode API key from **Developer → API Keys** and the IDs from the previous steps: ```bash .env theme={null} DODO_PAYMENTS_API_KEY=dodo_test_... DODO_PAYMENTS_WEBHOOK_KEY=your_webhook_signing_secret_here DODO_PAYMENTS_ENVIRONMENT=test_mode OPENAI_API_KEY=your_openai_api_key_here CREDIT_ENTITLEMENT_ID=cde_xxxxxxxxxxxx STARTER_PLAN_PRODUCT_ID=pdt_xxxxxxxxxxxx PRO_PLAN_PRODUCT_ID=pdt_xxxxxxxxxxxx TOPUP_PRODUCT_ID=pdt_xxxxxxxxxxxx BASE_URL=http://localhost:3000 ``` > [!WARNING] > > Never commit `.env` to version control. Add it to `.gitignore` before your first commit. You fill in `DODO_PAYMENTS_WEBHOOK_KEY` in Step 7, after you register the webhook endpoint. **3. Implement the Server** Create `src/server.ts`. The completion endpoint calls OpenAI's `gpt-6-luna` model, which suits high-volume requests. The `package.json` tab shows the full dependency list: ```typescript src/server.ts expandable theme={null} import 'dotenv/config'; import DodoPayments from 'dodopayments'; import OpenAI from 'openai'; import express, { Request, Response } from 'express'; const app = express(); // IMPORTANT: webhook route needs the raw body for signature verification. // We register the raw parser ONLY on /webhooks/dodo, then JSON for everything else. app.use('/webhooks/dodo', express.raw({ type: 'application/json' })); app.use(express.json()); app.use(express.static('public')); const dodo = new DodoPayments({ bearerToken: process.env.DODO_PAYMENTS_API_KEY!, webhookKey: process.env.DODO_PAYMENTS_WEBHOOK_KEY, environment: (process.env.DODO_PAYMENTS_ENVIRONMENT as 'test_mode' | 'live_mode') ?? 'test_mode', }); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY! }); const CREDIT_ENTITLEMENT_ID = process.env.CREDIT_ENTITLEMENT_ID!; const BASE_URL = process.env.BASE_URL!; const PLAN_PRODUCTS: Record = { starter: process.env.STARTER_PLAN_PRODUCT_ID!, pro: process.env.PRO_PLAN_PRODUCT_ID!, }; // ──────────────────────────────────────────────────────────────────────────── // Subscription checkout // Body: { plan: 'starter' | 'pro', email: string, name: string } // ──────────────────────────────────────────────────────────────────────────── app.post('/checkout/subscribe', async (req: Request, res: Response) => { const { plan, email, name } = req.body; if (!PLAN_PRODUCTS[plan]) { return res.status(400).json({ error: `Unknown plan: ${plan}` }); } try { const session = await dodo.checkoutSessions.create({ product_cart: [{ product_id: PLAN_PRODUCTS[plan], quantity: 1 }], customer: { email, name }, return_url: `${BASE_URL}/?subscribed=1`, }); res.json({ checkout_url: session.checkout_url, session_id: session.session_id }); } catch (err) { console.error('Subscription checkout error:', err); res.status(500).json({ error: 'Failed to create subscription checkout' }); } }); // ──────────────────────────────────────────────────────────────────────────── // Top-up checkout — buyer must already be a customer // Body: { customer_id: string } // ──────────────────────────────────────────────────────────────────────────── app.post('/checkout/topup', async (req: Request, res: Response) => { const { customer_id } = req.body; if (!customer_id) return res.status(400).json({ error: 'customer_id required' }); try { const session = await dodo.checkoutSessions.create({ product_cart: [{ product_id: process.env.TOPUP_PRODUCT_ID!, quantity: 1 }], customer: { customer_id }, return_url: `${BASE_URL}/?topup=1`, }); res.json({ checkout_url: session.checkout_url }); } catch (err) { console.error('Top-up checkout error:', err); res.status(500).json({ error: 'Failed to create top-up checkout' }); } }); // ──────────────────────────────────────────────────────────────────────────── // Live token balance for a customer // ──────────────────────────────────────────────────────────────────────────── app.get('/credits/:customerId', async (req: Request, res: Response) => { try { const result = await dodo.creditEntitlements.balances.retrieve(req.params.customerId, { credit_entitlement_id: CREDIT_ENTITLEMENT_ID, }); res.json({ balance: result.balance, overage: result.overage, last_transaction_at: result.last_transaction_at, }); } catch (err) { console.error('Balance fetch error:', err); res.status(500).json({ error: 'Failed to fetch credit balance' }); } }); // ──────────────────────────────────────────────────────────────────────────── // AI completion — calls OpenAI, then ingests a usage event with the real // token count. The meter aggregates these and deducts credits automatically. // Body: { customer_id: string, prompt: string } // ──────────────────────────────────────────────────────────────────────────── app.post('/api/generate', async (req: Request, res: Response) => { const { customer_id, prompt } = req.body; if (!customer_id || !prompt) { return res.status(400).json({ error: 'customer_id and prompt required' }); } // Best-effort balance gate for Starter (no overage). Note: balance updates // are eventually consistent (~1 min lag from event ingestion), so a Starter // customer can technically squeeze through a few extra requests right after // running out. Use a stricter rate-limiter on top if you need hard cutoffs. try { const balance = await dodo.creditEntitlements.balances.retrieve(customer_id, { credit_entitlement_id: CREDIT_ENTITLEMENT_ID, }); if (Number(balance.balance) <= 0 && Number(balance.overage) <= 0) { return res.status(402).json({ error: 'Out of tokens. Top up or upgrade to continue.', }); } } catch { // Fall through — if the balance lookup fails, don't block; rely on metering. } let completion; try { completion = await openai.chat.completions.create({ model: 'gpt-6-luna', messages: [{ role: 'user', content: prompt }], }); } catch (err) { console.error('OpenAI error:', err); return res.status(502).json({ error: 'Upstream AI provider failed' }); } const tokensUsed = completion.usage?.total_tokens ?? 0; // Fire-and-forget — don't block the response on metering. ingestTokenUsage(customer_id, tokensUsed, completion.model).catch((err) => console.error('Usage ingest failed:', err), ); res.json({ text: completion.choices[0]?.message?.content ?? '', tokens_used: tokensUsed, model: completion.model, }); }); async function ingestTokenUsage(customerId: string, tokens: number, model: string) { await dodo.usageEvents.ingest({ events: [ { // event_id is the idempotency key. Use a stable, unique value per request. event_id: `req_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`, customer_id: customerId, event_name: 'api.tokens_used', timestamp: new Date().toISOString(), metadata: { tokens, model }, }, ], }); } // ──────────────────────────────────────────────────────────────────────────── // Webhook handler — verifies signature using the SDK, then routes events. // ──────────────────────────────────────────────────────────────────────────── app.post('/webhooks/dodo', async (req: Request, res: Response) => { const rawBody = (req.body as Buffer).toString('utf8'); const headers = { 'webhook-id': req.header('webhook-id') ?? '', 'webhook-signature': req.header('webhook-signature') ?? '', 'webhook-timestamp': req.header('webhook-timestamp') ?? '', }; let event: { type: string; data: any }; try { event = dodo.webhooks.unwrap(rawBody, { headers }) as any; } catch (err) { console.error('Webhook verification failed:', err); return res.status(401).json({ error: 'Invalid signature' }); } switch (event.type) { case 'credit.added': console.log(`[credit.added] customer=${event.data.customer_id} amount=${event.data.amount}`); break; case 'credit.deducted': console.log(`[credit.deducted] customer=${event.data.customer_id} amount=${event.data.amount}`); break; case 'credit.overage_charged': console.log(`[credit.overage_charged] customer=${event.data.customer_id}`); break; default: // Ignore other event types break; } res.json({ received: true }); }); app.listen(3000, () => { console.log('NeuralAPI billing server running on http://localhost:3000'); }); ``` ```json package.json theme={null} { "name": "neural-api-billing", "version": "1.0.0", "scripts": { "dev": "tsx watch src/server.ts", "build": "tsc", "start": "node dist/server.js" }, "dependencies": { "dodopayments": "latest", "openai": "^4.0.0", "express": "^4.18.0", "dotenv": "^16.0.0" }, "devDependencies": { "@types/node": "^20.0.0", "@types/express": "^4.17.0", "typescript": "^5.0.0", "tsx": "^4.0.0" } } ``` > [!TIP] > > The backend is done: subscription checkout, top-up checkout, an OpenAI completion with metered token billing, a balance read, and a verified webhook handler. > [!TIP] > > [`@dodopayments/ingestion-blueprints`](/features/usage-based-billing/ingestion-blueprints) provides trackers that make the `usageEvents.ingest` call for you, including the [LLM Blueprint](/developer-resources/ingestion-blueprints/llm), [API gateway](/developer-resources/ingestion-blueprints/api-gateway), [object storage](/developer-resources/ingestion-blueprints/object-storage), [streams](/developer-resources/ingestion-blueprints/stream), and [time-range](/developer-resources/ingestion-blueprints/time-range) usage. **4. How Deductions Happen** The server never calls a "deduct N credits" endpoint. The meter does the deduction: 1. Your handler calls OpenAI and reads `usage.total_tokens`, for example 1532. 2. You ingest one usage event with `event_name: api.tokens_used` and `metadata: { tokens: 1532 }`. 3. The `Token Usage Meter` aggregates events per customer. A background worker processes new events every minute. 4. Because the meter bills the `API Tokens` credit through **Bill usage in credits**, Dodo Payments deducts 1532 credits, starting with the customer's grant that expires first (FIFO). 5. If overage is enabled and the balance runs out, the deficit is tracked and billed on the next invoice. Your code only ingests events. ## Step 6: Add a Demo Frontend Create `public/index.html` to test every flow in your browser. The page saves the customer ID in `localStorage`, so subscribe, generate, and top-up share one identity, as they would in a logged-in app: ```html public/index.html expandable theme={null} NeuralAPI Demo

NeuralAPI Demo

After completing checkout, copy the customer ID from your Dodo Payments dashboard (Customers → most recent) and paste here.

1. Subscribe to a Plan

2. Generate AI Response (deducts tokens)

3. Live Token Balance

4. Buy a Top-Up Pack

``` ## Step 7: Wire Up the Webhook Webhooks let your server react to balance changes, for example to email a customer whose balance is running low. **1. Expose Your Local Server** Webhooks need a public URL. For local development, use [ngrok](https://ngrok.com) or another tunnel: ```bash theme={null} ngrok http 3000 ``` Copy the HTTPS forwarding URL, which ends in `ngrok-free.app`. **2. Register the Webhook in Dodo Payments** 1. In the dashboard, go to **Developer → Webhooks** and click **Add endpoint**. 2. Enter the URL `https://your-tunnel.ngrok-free.app/webhooks/dodo`, using your own tunnel host. 3. Select at least these events: * `credit.added` * `credit.deducted` * `credit.overage_charged` 4. Click **Create endpoint**, then copy the signing secret from the endpoint's **Overview** tab. 5. Paste it into `.env` as `DODO_PAYMENTS_WEBHOOK_KEY`, then restart `npm run dev`. > [!TIP] > > The SDK's `dodo.webhooks.unwrap()` checks the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers with your signing secret, then parses the payload. Don't write your own HMAC check: Dodo Payments follows [Standard Webhooks](https://www.standardwebhooks.com/), which signs `id.timestamp.body`, not the body alone. ## Step 8: Test the Full Flow **1. Subscribe a Test Customer** 1. Run `npm run dev`. 2. Open `http://localhost:3000`. 3. Pick **Pro**, enter a test email address and name, and click **Get Checkout Link**. Complete checkout with [test card details](/miscellaneous/testing-process). 4. In the dashboard, go to **Customers**, open the newest customer, and copy its ID, which starts with `cus_`. 5. Paste the ID into the **Logged-in customer ID** field on the demo and click **Save**. > [!TIP] > > The customer has 40,000,000 tokens. Click **Refresh Balance** to confirm. **2. Generate an AI Response** Type a prompt and click **Generate**. The server calls OpenAI, reads the actual `total_tokens`, ingests a usage event, and returns the response. > [!NOTE] > > A background worker processes usage events every minute, so the balance doesn't drop right away. Wait a minute or two, then click **Refresh Balance** again. An unchanged balance on the first refresh doesn't mean metering failed. **3. Test the Top-Up Flow** Click **Buy 5M Tokens — \$19** and complete checkout. After the payment succeeds, refresh the balance: it increases by 5,000,000 tokens, and the server log shows a `credit.added` event. ## Troubleshooting > [accordion] Credits not deducting after usage events > > **Possible causes:** > > * The meter's event name doesn't match the `event_name` you send. `api.tokens_used` is case-sensitive. > * The meter isn't linked to the `API Tokens` credit on the product. Open the product's meter configuration and confirm **Bill usage in credits** is on. > * The `metadata.tokens` key doesn't match the meter's **Over Property**. > * The customer's grant has expired. Check the customer's credit history. > > **What to check:** > > 1. In **Products → Meters**, open the meter and confirm the product attachment shows the linked credit name. > 2. Open the meter's **Events** tab. Ingested events appear there even before any deduction. > 3. Open the customer in **Customers** and select the **Credits** tab. Ledger entries appear within a minute or two. > [accordion] Balance always shows 0 or 'customer not found' > > **Possible causes:** > > * The customer hasn't completed checkout. Credits are issued only after a successful payment. > * You're querying with the wrong `customer_id`. Use the ID that starts with `cus_` from the dashboard, not an ID from your own database. > * `CREDIT_ENTITLEMENT_ID` in `.env` doesn't match the credit attached to the product. > > **What to check:** > Open the customer in **Customers** and select the **Credits** tab. If no credits appear, the credit wasn't attached to the product or the payment didn't complete. > [accordion] Overage not working for Pro plan customers > > **Possible causes:** > > * Overage isn't enabled on the **Pro product's credit attachment**. The setting on the credit is only a default. > * The customer is on Starter, not Pro. > * **Overage Limit** is set to 0. > > **What to check:** > Edit the Pro product, open the credit in **Entitlements**, and confirm **Allow Overage** is on and **Price Per Unit** is `0.000005` (\$5 per million tokens). Check the leading zeros: the field takes a price per token, not per 1K tokens. > [accordion] `Webhook verification failed` in logs > > **Possible causes:** > > * Body parsing order: `express.json()` ran on `/webhooks/dodo` before `express.raw()`. The SDK needs the **raw bytes** of the request, not parsed JSON. > * `DODO_PAYMENTS_WEBHOOK_KEY` holds the wrong signing secret. > * A reverse proxy rewrites the request headers. > > **What to check:** > Confirm that the `app.use('/webhooks/dodo', express.raw(...))` line comes before `app.use(express.json())` in `server.ts`. ## Need Help? * [Discord Community](https://discord.gg/bYqAp4ayYh) * [support@dodopayments.com](mailto:support@dodopayments.com) ## Congratulations! You've Built Credit-Based Billing for NeuralAPI NeuralAPI now bills in credits from checkout to deduction: > [card] Token Credit Entitlement > > A reusable `API Tokens` credit with a 30-day expiry, shared by both plans and the top-up pack. > [card] Tiered Plans, One Credit > > Starter (10M tokens, hard limit) and Pro (40M tokens plus overage), configured per product without duplicating the credit. > [card] One-Time Top-Up Pack > > Customers add 5M tokens for \$19 without changing their subscription. > [card] Deduction Through a Meter > > Actual OpenAI token counts are ingested as events, and the meter deducts credits FIFO with no manual tracking. > [card] Live Balance API > > The current balance, read through the SDK, to gate access, show usage, or warn customers in your app. > [card] Verified Webhook Pipeline > > Credit ledger events (`credit.added`, `credit.deducted`, `credit.overage_charged`) routed through a handler that verifies signatures with the SDK's Standard Webhooks helper. > [!NOTE] > > **Going to production?** Tighten these: > > * **Add authentication to `/credits/:customerId` and `/api/generate`.** As written, anyone can call them with any customer ID. Authenticate users and look up their customer ID on the server. > * **Use stable `event_id` values.** The example uses `Date.now()` plus a random string. In production, use your request ID so that retries are idempotent: Dodo Payments ignores an event whose `event_id` it has already ingested. > * **Store the customer-to-user mapping.** Save `customer_id` in your database after the first checkout, so users don't paste it manually. > * **Decide what happens when a subscription ends.** Plan credits stay in the customer's ledger until they expire 30 days after issuance, and top-up credits stay valid for 365 days. The tutorial's `/api/generate` checks only the balance, not the subscription status, so a cancelled customer can still use their remaining tokens. That's the customer-friendly default. For stricter access, either (a) listen for the `subscription.cancelled` webhook and gate `/api/generate` on subscription status, or (b) on cancellation, debit the unused plan credits with the ledger API. Ledger debits draw from existing grants in FIFO order, oldest grant first. > * **Monitor the Usage Billing dashboard** to catch metering anomalies early. > [card] [Credit-Based Billing Reference](/features/credit-based-billing) > > Rollover, overage modes, ledger management, and every credit API endpoint. > [card] [Credit Webhook Events](/developer-resources/webhooks/intents/credit) > > Payload schemas for every credit event your server can receive. # Archive Addon Source: https://docs.dodopayments.com/api-reference/addons/archive-addon delete /addons/{id} Archive an addon. Products no longer offer it, and active subscriptions keep it. # Create Addon Source: https://docs.dodopayments.com/api-reference/addons/create-addon post /addons Create a new addon product that can be attached to your main subscription products # Get Addon Source: https://docs.dodopayments.com/api-reference/addons/get-addon get /addons/{id} Retrieve detailed information about a specific addon using its unique identifier # List Addons Source: https://docs.dodopayments.com/api-reference/addons/list-addons get /addons Retrieve a comprehensive list of all available addons # Unarchive Addon Source: https://docs.dodopayments.com/api-reference/addons/unarchive-addon post /addons/{id}/unarchive Unarchive an addon. Unarchiving does not attach the addon to products again. # Update Addon Source: https://docs.dodopayments.com/api-reference/addons/update-addon patch /addons/{id} Modify the details of an existing addon using its unique identifier # Update Addon Image Source: https://docs.dodopayments.com/api-reference/addons/update-addon-images put /addons/{id}/images Get a presigned S3 URL to upload an image for an existing addon. Upload the image to the returned URL within 60 seconds. # List Balance Ledger Entries Source: https://docs.dodopayments.com/api-reference/balance-ledger/list-ledger-entries get /balances/ledger Retrieve a paginated list of balance ledger entries for your account. Use query parameters to filter by date range, event type, currency, or reference object. # Archive Brand Source: https://docs.dodopayments.com/api-reference/brands/archive-brand post /brands/{id}/archive Archive a brand and move its products, live subscriptions, and product collections to another brand of the same business. # Create Brand Source: https://docs.dodopayments.com/api-reference/brands/create-brand post /brands Create a new brand. # Get Brand Source: https://docs.dodopayments.com/api-reference/brands/get-brand get /brands/{id} Retrieve a specific brand by ID. # List Brands Source: https://docs.dodopayments.com/api-reference/brands/list-brands get /brands List all brands. # Update Brand Source: https://docs.dodopayments.com/api-reference/brands/update-brand patch /brands/{id} Update an existing brand's details. # Update Brand Image Source: https://docs.dodopayments.com/api-reference/brands/update-brand-images put /brands/{id}/images Get a presigned S3 URL to upload an image for a brand. Upload the image to the returned URL within 60 seconds. # Create Credit Entitlement Source: https://docs.dodopayments.com/api-reference/credit-entitlements/create-credit-entitlement post /credit-entitlements Creates a new credit entitlement for the authenticated business # Create Ledger Entry Source: https://docs.dodopayments.com/api-reference/credit-entitlements/create-ledger-entry post /credit-entitlements/{credit_entitlement_id}/balances/{customer_id}/ledger-entries Creates a ledger entry to credit or debit a customer's balance # Delete Credit Entitlement Source: https://docs.dodopayments.com/api-reference/credit-entitlements/delete-credit-entitlement delete /credit-entitlements/{id} Soft-deletes a credit entitlement by its ID # Get Credit Entitlement Source: https://docs.dodopayments.com/api-reference/credit-entitlements/get-credit-entitlement get /credit-entitlements/{id} Retrieves a specific credit entitlement by its ID # Get Customer Balance Source: https://docs.dodopayments.com/api-reference/credit-entitlements/get-customer-balance get /credit-entitlements/{credit_entitlement_id}/balances/{customer_id} Gets a specific customer's balance for a credit entitlement # List Balances Source: https://docs.dodopayments.com/api-reference/credit-entitlements/list-balances get /credit-entitlements/{credit_entitlement_id}/balances Lists all customer balances for a specific credit entitlement # List Credit Entitlements Source: https://docs.dodopayments.com/api-reference/credit-entitlements/list-credit-entitlements get /credit-entitlements Lists all credit entitlements for the authenticated business with pagination support # List Customer Grants Source: https://docs.dodopayments.com/api-reference/credit-entitlements/list-customer-grants get /credit-entitlements/{credit_entitlement_id}/balances/{customer_id}/grants Lists credit grants for a customer under a specific credit entitlement # List Customer Ledger Source: https://docs.dodopayments.com/api-reference/credit-entitlements/list-customer-ledger get /credit-entitlements/{credit_entitlement_id}/balances/{customer_id}/ledger Lists ledger entries for a customer under a specific credit entitlement # Undelete Credit Entitlement Source: https://docs.dodopayments.com/api-reference/credit-entitlements/undelete-credit-entitlement post /credit-entitlements/{id}/undelete Restores a previously deleted credit entitlement # Update Credit Entitlement Source: https://docs.dodopayments.com/api-reference/credit-entitlements/update-credit-entitlement patch /credit-entitlements/{id} Updates an existing credit entitlement with partial data # List Disputes Source: https://docs.dodopayments.com/api-reference/disputes/get-disputes get /disputes Get a list of all disputes associated with your account. # Get Dispute Detail Source: https://docs.dodopayments.com/api-reference/disputes/get-disputes-1 get /disputes/{dispute_id} Get detailed information about a specific dispute. # Archive Meter Source: https://docs.dodopayments.com/api-reference/meters/archive-meter delete /meters/{id} Archive a meter by its ID. # Create Meter Source: https://docs.dodopayments.com/api-reference/meters/create-meter post /meters Create a new meter. # List Meters Source: https://docs.dodopayments.com/api-reference/meters/get-meters get /meters Get a list of all meters. # Get Meter Source: https://docs.dodopayments.com/api-reference/meters/retrieve-meter get /meters/{id} Retrieve a meter by its ID. # Unarchive Meter Source: https://docs.dodopayments.com/api-reference/meters/unarchive-meter post /meters/{id}/unarchive Unarchive a meter by its ID. # Update Meter Source: https://docs.dodopayments.com/api-reference/meters/update-meter patch /meters/{id} Update the name, description, or measurement unit of a meter. # Supported Countries Source: https://docs.dodopayments.com/api-reference/misc/supported-countries get /checkout/supported_countries Retrieve a list of countries that are supported by Dodo Payments for your customers. > [!TIP] > > You will receive a list of [ISO Alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country codes representing the countries we **currently support for payments**. You can view the full list of supported countries [here](/miscellaneous/list-of-countries-we-accept-payments-from). This list is updated regularly as we expand our coverage. > [!TIP] > > Note: The available options include ISO Alpha-2 codes for **all countries**, not just the ones we currently support. Please refer to the supported countries list to confirm availability. # Get Moderation Usage Source: https://docs.dodopayments.com/api-reference/moderation/get-usage get /moderation/usage Get your billable moderation screens per day for the last 30 days, your unbilled screens, and how many screens remain until the next charge. # Screen a Prompt Source: https://docs.dodopayments.com/api-reference/moderation/screen post /moderation/screen Screen text, an image, or both before you generate, and get an allow, flag, or deny verdict with a score for every moderation category. # Download Payout Breakup CSV Source: https://docs.dodopayments.com/api-reference/payouts/download-breakup-csv get /payouts/{payout_id}/breakup/details/csv Downloads the complete payout breakup as a CSV file with columns for ledger ID, event type, amounts, and more. # Get Payout Invoice Source: https://docs.dodopayments.com/api-reference/payouts/get-payout-invoice get /invoices/payouts/{payout_id} Get the invoice for a payout as a PDF. # List Payouts Source: https://docs.dodopayments.com/api-reference/payouts/get-payouts get /payouts Get a list of all payouts associated with your account. # List Payout Breakup Details Source: https://docs.dodopayments.com/api-reference/payouts/list-breakup-details get /payouts/{payout_id}/breakup/details Returns paginated individual balance ledger entries for a payout, with each entry converted into the payout's currency at the rate the payout settled at. # Retrieve Payout Breakup Source: https://docs.dodopayments.com/api-reference/payouts/retrieve-breakup get /payouts/{payout_id}/breakup Returns the breakdown of a payout by event type (payments, refunds, disputes, fees, etc.) in the payout's currency. # Add Products to Group Source: https://docs.dodopayments.com/api-reference/product-collections/add-group-items post /product-collections/{id}/groups/{group_id}/items Add one or more products to a group within a product collection. # Archive Product Collection Source: https://docs.dodopayments.com/api-reference/product-collections/archive-product-collection delete /product-collections/{id} Archive a product collection associated with your account. # Create Product Collection Group Source: https://docs.dodopayments.com/api-reference/product-collections/create-group post /product-collections/{id}/groups Add a new group to a product collection. # Create Product Collection Source: https://docs.dodopayments.com/api-reference/product-collections/create-product-collection post /product-collections Create a new product collection. # Delete Product Collection Group Source: https://docs.dodopayments.com/api-reference/product-collections/delete-group delete /product-collections/{id}/groups/{group_id} Delete a group from a product collection. # Delete Group Item Source: https://docs.dodopayments.com/api-reference/product-collections/delete-group-item delete /product-collections/{id}/groups/{group_id}/items/{item_id} Remove a product item from a product collection group. # Get Product Collection Source: https://docs.dodopayments.com/api-reference/product-collections/get-product-collection get /product-collections/{id} Get detailed information about a specific product collection. # List Product Collections Source: https://docs.dodopayments.com/api-reference/product-collections/list-product-collections get /product-collections Get a list of all product collections associated with your account. # Unarchive Product Collection Source: https://docs.dodopayments.com/api-reference/product-collections/unarchive-product-collection post /product-collections/{id}/unarchive Unarchive a product collection associated with your account. # Update Product Collection Group Source: https://docs.dodopayments.com/api-reference/product-collections/update-group patch /product-collections/{id}/groups/{group_id} Update a group within a product collection. # Update Group Item Source: https://docs.dodopayments.com/api-reference/product-collections/update-group-item patch /product-collections/{id}/groups/{group_id}/items/{item_id} Update a product item within a product collection group. # Update Product Collection Source: https://docs.dodopayments.com/api-reference/product-collections/update-product-collection patch /product-collections/{id} Update a product collection's details. # Update Product Collection Image Source: https://docs.dodopayments.com/api-reference/product-collections/update-product-collection-images put /product-collections/{id}/images Get a presigned S3 URL to upload an image for a product collection. Upload the image to the returned URL within 60 seconds. # Archive Product Source: https://docs.dodopayments.com/api-reference/products/archive-product delete /products/{id} Archive a product associated with your account. # Archive Localized Price Source: https://docs.dodopayments.com/api-reference/products/delete-products-localized-prices delete /products/{product_id}/localized-prices/{id} Archive a localized price rule. Idempotent soft-delete. # List Localized Prices Source: https://docs.dodopayments.com/api-reference/products/get-products-localized-prices get /products/{product_id}/localized-prices List the active localized price rules for a product. # Get Localized Price Source: https://docs.dodopayments.com/api-reference/products/get-products-localized-prices-id get /products/{product_id}/localized-prices/{id} Retrieve a single localized price rule for a product. # List Short Links Source: https://docs.dodopayments.com/api-reference/products/get-products-short-links get /products/short_links Lists all short links created by the business. Short links provide shortened checkout URLs with custom slugs for your products. # Update Localized Price Source: https://docs.dodopayments.com/api-reference/products/patch-products-localized-prices patch /products/{product_id}/localized-prices/{id} Update the amount of a localized price rule. # Create Short Link Source: https://docs.dodopayments.com/api-reference/products/post-products-id-short-links post /products/{id}/short_links Creates a short checkout URL with a custom slug for a product. Uses a Static Checkout URL under the hood. # Create Localized Price Source: https://docs.dodopayments.com/api-reference/products/post-products-localized-prices post /products/{product_id}/localized-prices Create a localized price rule for a product, by currency or by country. # Unarchive Product Source: https://docs.dodopayments.com/api-reference/products/unarchive-product post /products/{id}/unarchive Unarchive a product associated with your account. # Upload Product File Source: https://docs.dodopayments.com/api-reference/products/update-files put /products/{id}/files Get a presigned S3 URL to upload a single file for a product. Upload the file to the returned URL within 60 seconds. # Get Refund Receipt Source: https://docs.dodopayments.com/api-reference/refunds/get-refund-receipt get /invoices/refunds/{refund_id} Get a refund receipt for a refund. # List Refunds Source: https://docs.dodopayments.com/api-reference/refunds/get-refunds get /refunds Get a list of all refunds associated with your account. # Get Refund Detail Source: https://docs.dodopayments.com/api-reference/refunds/get-refunds-1 get /refunds/{refund_id} Get detailed information about a specific refund. # Create Refund Source: https://docs.dodopayments.com/api-reference/refunds/post-refunds post /refunds Create a refund for a payment. # Get Event Source: https://docs.dodopayments.com/api-reference/usage-events/get-event get /events/{event_id} Get an event by its ID. # Ingest Events Source: https://docs.dodopayments.com/api-reference/usage-events/ingest-events post /events/ingest Ingest events for usage-based billing. # List Events Source: https://docs.dodopayments.com/api-reference/usage-events/list-events get /events Get a list of all events. # Create Webhook Source: https://docs.dodopayments.com/api-reference/webhooks/create-webhook post /webhooks Create a new webhook for a business. # Delete Webhook Source: https://docs.dodopayments.com/api-reference/webhooks/delete-webhook delete /webhooks/{webhook_id} Delete a specific webhook. # Get Webhook Detail Source: https://docs.dodopayments.com/api-reference/webhooks/get-details get /webhooks/{webhook_id} Get detailed information about a specific webhook. # Get Webhook Headers Source: https://docs.dodopayments.com/api-reference/webhooks/get-webhook-headers get /webhooks/{webhook_id}/headers Get the headers for a specific webhook. # Get Webhook Signing Key Source: https://docs.dodopayments.com/api-reference/webhooks/get-webhook-signing-key get /webhooks/{webhook_id}/secret Get the signing key for a specific webhook. # List Webhooks Source: https://docs.dodopayments.com/api-reference/webhooks/list-webhooks get /webhooks List all webhooks for a business. # Update Webhook Source: https://docs.dodopayments.com/api-reference/webhooks/update-webhook patch /webhooks/{webhook_id} Update a specific webhook. # Update Webhook Headers Source: https://docs.dodopayments.com/api-reference/webhooks/update-webhook-headers patch /webhooks/{webhook_id}/headers Update the headers for a specific webhook. # AutoSend Source: https://docs.dodopayments.com/integrations/autosend Send transactional emails through AutoSend's email API when Dodo Payments events occur, such as successful payments, new subscriptions, and failed payments. ## Introduction The AutoSend integration sends an email through AutoSend's email API each time a Dodo Payments event occurs, from successful payments to failed payment attempts and refund confirmations. A transformation on the webhook endpoint turns each event into an AutoSend send request. To set it up, you need an AutoSend API key and a sender domain verified in AutoSend. You can find your API key in the AutoSend dashboard under **Settings → API Keys**. ## Getting Started Follow these steps to connect AutoSend to Dodo Payments: **1. Open Webhook Section** In the Dodo Payments dashboard, go to **Developer → Webhooks** and click **Add endpoint**. ![Add endpoint dialog with AutoSend selected in the Integration dropdown](https://mintcdn.com/dodopayments/DL_ADtkdH7ph5YST/images/integrations/autosend.png?fit=max\&auto=format\&n=DL_ADtkdH7ph5YST\&q=85\&s=c6d40b6c5f867f9164c0177858c8d6b4) **2. Select AutoSend Integration** In **Integration**, select **Autosend**. **3. Enter API Key** In **API key**, paste your AutoSend API key. Dodo Payments sends it in the `Authorization` header of every delivery. > [card] [Learn how to create and manage API keys](https://docs.autosend.com/api-keys) > > See the AutoSend documentation for how to create and manage API keys. **4. Select Events** In **Subscribed events**, select the events your transformation handles, such as `payment.succeeded`, `subscription.active`, and `payment.failed`. An endpoint with no events selected receives every event type. **5. Configure Transformation** Under **Transformation code**, write the JavaScript handler that builds the email for each event. Start from the [code examples](#code-examples). **6. Test & Create** Under **Test this code**, click **Simulate** to run the handler against a sample payload and check the result. Then click **Create endpoint**. **7. Activation Complete** The endpoint sends an email through AutoSend each time a subscribed event occurs. ## Code Examples Each handler checks the event type in `webhook.eventType` and reads the event data from `webhook.payload.data`. It sets `webhook.url` to AutoSend's send endpoint and replaces `webhook.payload` with the email request. Dodo Payments amounts, such as `total_amount`, are in the smallest currency unit, for example cents for USD. ### Payment Confirmation Email Send a confirmation email when a payment succeeds (`payment.succeeded`): ```javascript payment_confirmation.js icon="js" expandable theme={null} function handler(webhook) { if (webhook.eventType === "payment.succeeded") { const p = webhook.payload.data; webhook.url = "https://api.autosend.com/v1/mails/send"; webhook.payload = { to: { email: p.customer.email, name: p.customer.name, }, from: { email: "payments@mail.yourdomain.com", name: "Your Company", }, subject: "Payment Successful - Thank you for your purchase!", templateId: "A-61522f2xxxxxxxxx", dynamicData: { customerName: p.customer.name, amount: p.total_amount, currency: p.currency, paymentId: p.payment_id, paymentDate: new Date(p.created_at).toLocaleDateString(), }, replyTo: { email: "support@yourdomain.com", name: "Support Team", }, }; } return webhook; } ``` ### Subscription Welcome Email Send a welcome email when a subscription becomes active (`subscription.active`). The example passes `product_id` as `planName`. If your template shows the plan name, map the ID to a display name first. ```javascript subscription_welcome.js icon="js" expandable theme={null} function handler(webhook) { if (webhook.eventType === "subscription.active") { const s = webhook.payload.data; webhook.url = "https://api.autosend.com/v1/mails/send"; webhook.payload = { to: { email: s.customer.email, name: s.customer.name, }, from: { email: "subscriptions@mail.yourdomain.com", name: "Your Company", }, subject: "Welcome to your subscription!", templateId: "A-61522f2xxxxxxxxx", dynamicData: { customerName: s.customer.name, planName: s.product_id, billingInterval: s.payment_frequency_interval, nextBillingDate: new Date(s.next_billing_date).toLocaleDateString(), subscriptionId: s.subscription_id, }, replyTo: { email: "support@yourdomain.com", name: "Support Team", }, }; } return webhook; } ``` ### Payment Failure Notification Send a notification email when a payment fails (`payment.failed`). The payment's `error_message` field holds the reason for the failure. ```javascript payment_failure.js icon="js" expandable theme={null} function handler(webhook) { if (webhook.eventType === "payment.failed") { const p = webhook.payload.data; webhook.url = "https://api.autosend.com/v1/mails/send"; webhook.payload = { to: { email: p.customer.email, name: p.customer.name, }, from: { email: "billing@mail.yourdomain.com", name: "Your Company Billing", }, subject: "Payment Failed - Action Required", templateId: "A-61522f2xxxxxxxxx", dynamicData: { customerName: p.customer.name, amount: p.total_amount, currency: p.currency, failureReason: p.error_message, paymentId: p.payment_id, retryUrl: `https://yourdomain.com/billing/retry/${p.payment_id}`, }, replyTo: { email: "billing@yourdomain.com", name: "Billing Support", }, }; } return webhook; } ``` ## Best Practices * **Verify your sender domain**: AutoSend sends only from a verified domain, so verify the domain of your `from` address in AutoSend before you create the endpoint. A verified domain also improves deliverability and helps keep your emails out of spam folders. * **Use dynamic data for personalization**: Pass customer-specific values, such as names, payment amounts, and subscription details, in the `dynamicData` field, and reference them as variables in your AutoSend template. * **Write clear subject lines**: Write subject lines that state the email's purpose. Avoid words that trigger spam filters, and keep subjects under 50 characters. * **Test before production**: Run each handler with **Test this code**, then send a test email before you go live. Check that the content renders correctly and that every `dynamicData` value is mapped. ## API Reference For every parameter and error code of the send endpoint, see the [AutoSend API documentation](https://docs.autosend.com/api-reference/mails/send). ## Troubleshooting > [accordion] Emails Not Being Sent > > * Verify that the API key is correct and active. > * Check that the sender domain is verified in AutoSend. > * Check that the recipient email addresses are valid. > * Review your AutoSend sending limits and quotas. > * Verify that the transformation sets the send endpoint URL: `https://api.autosend.com/v1/mails/send`. > * Check that the payload includes every required parameter. > * Open the endpoint's delivery attempts in the **Logs** tab of **Developer → Webhooks** to see AutoSend's response code. > [accordion] Transformation Errors > > * Check that the payload matches the AutoSend API format. > * Check that all required fields are present: `to`, `from`, and either `templateId` or `html`/`text`. Without `templateId`, `subject` is also required. > * Check that email addresses are formatted correctly. > * If you use a template, verify that `templateId` is valid. > * Check that the `dynamicData` keys match your template variables. > [accordion] Template Issues > > * Verify that your template ID is correct and the template is active in AutoSend. > * Check that the `dynamicData` keys match the variables in your template. > * Check that every required template variable has a value. > * Test the template on its own in the AutoSend dashboard. # Close CRM Source: https://docs.dodopayments.com/integrations/close-crm Create Close CRM contacts and opportunities when customers pay or subscribe through Dodo Payments, so your sales team can track leads and revenue in Close. ## Introduction The Close CRM integration creates records in Close from Dodo Payments events. A successful payment can create a contact, and a new subscription can create an opportunity, so your sales team sees revenue activity next to its leads. > [!NOTE] > > This integration requires a Close API key with permission to create contacts and opportunities. To create one in Close, go to **Settings → Developer → API Keys** and click **New API Key**. ## Getting Started **1. Open the Webhook Section** In the Dodo Payments dashboard, go to **Developer → Webhooks** and click **Add endpoint**. ![Add endpoint dialog with CloseCRM selected in the Integration dropdown](https://mintcdn.com/dodopayments/DL_ADtkdH7ph5YST/images/integrations/close-crm.png?fit=max\&auto=format\&n=DL_ADtkdH7ph5YST\&q=85\&s=28aaf0e7e1f79507ea1b5d46c1c409cd) **2. Select Close CRM** In **Integration**, select **CloseCRM**. **3. Enter API Key** In **API key**, paste your Close API key. Dodo Payments sends it in the `Authorization` header of every delivery. **4. Select Events** In **Subscribed events**, select the events your transformation handles. The examples on this page use `payment.succeeded` and `subscription.active`. **5. Configure Transformation** Under **Transformation code**, edit the handler to map payment data to Close objects. Start from the [examples](#transformation-code-examples). **6. Test & Create** Under **Test this code**, click **Simulate** to run the handler against a sample payload. Then click **Create endpoint**. **7. Done** Each subscribed event now creates a record in Close. ## Transformation Code Examples Each handler sets `webhook.url` to a Close API endpoint and replaces `webhook.payload` with the request body. Close sets custom fields through `custom.cf_` keys, so replace the `cf_` keys in the examples with the IDs of your own custom fields. Dodo Payments amounts are in the smallest currency unit, for example cents for USD. ### Create Contact from Payment When a payment succeeds, create a contact. Close takes `emails` and `phones` as lists of objects. If the request has no `lead_id`, Close creates a new lead named after the contact. ```javascript create_contact.js icon="js" expandable theme={null} function handler(webhook) { if (webhook.eventType === "payment.succeeded") { const p = webhook.payload.data; webhook.url = "https://api.close.com/api/v1/contact/"; webhook.payload = { name: p.customer.name, emails: [{ email: p.customer.email, type: "office" }], phones: p.customer.phone_number ? [{ phone: p.customer.phone_number, type: "office" }] : [], // Replace each cf_ key with the ID of a contact custom field in Close "custom.cf_payment_amount": (p.total_amount / 100).toFixed(2), "custom.cf_payment_method": p.payment_method || '', "custom.cf_dodo_customer_id": p.customer.customer_id }; } return webhook; } ``` ### Create Opportunity from Subscription When a subscription becomes active, create an opportunity. Close takes `value` as an integer in cents and `value_period` as `one_time`, `monthly`, or `annual`, so the example maps the subscription's `payment_frequency_interval` to a period. `lead_id` must be a Close lead ID, not a Dodo Payments customer ID. The example reads it from the subscription's `metadata`, so store the lead ID there when you create the subscription. Without a `lead_id`, Close creates a new, untitled lead. ```javascript create_opportunity.js icon="js" expandable theme={null} function handler(webhook) { if (webhook.eventType === "subscription.active") { const s = webhook.payload.data; // Close accepts one_time, monthly, or annual const periods = { Month: "monthly", Year: "annual" }; webhook.url = "https://api.close.com/api/v1/opportunity/"; webhook.payload = { lead_id: s.metadata.close_lead_id, // A Close lead ID stored in the subscription's metadata value: s.recurring_pre_tax_amount, // Integer in the smallest currency unit value_period: periods[s.payment_frequency_interval] || "one_time", note: `Subscription - ${s.product_id}`, // Replace each cf_ key with the ID of an opportunity custom field in Close "custom.cf_subscription_id": s.subscription_id, "custom.cf_billing_frequency": s.payment_frequency_interval, "custom.cf_next_billing": s.next_billing_date }; } return webhook; } ``` ## Tips * Check field names and types in the [Close API documentation](https://developer.close.com/) before you map fields. * Store payment-specific data, such as the amount and payment method, in custom fields. Create the fields in Close first, then use their IDs. * Map the subscription's `recurring_pre_tax_amount` to the opportunity `value`, and its billing interval to `value_period`. * Use IDs to link records: store the Dodo Payments `customer_id` on the Close contact, and the Close lead ID in the Dodo Payments `metadata`. * The contact example runs on every `payment.succeeded`, including renewals and repeat purchases, so a returning customer creates another contact. ## Troubleshooting > [accordion] Records Not Created in Close CRM > > * Verify that the API key has write permissions. > * Check that the required fields are included. > * Check that each email address is valid. > * Review the Close API rate limits. > * If deliveries fail with a `401`, Close may expect Basic authentication. Adjust the `Authorization` header on the endpoint's **Advanced** tab. > * Open the endpoint's delivery attempts in the **Logs** tab of **Developer → Webhooks** to see the response from Close. > [accordion] Transformation Errors > > * Check that the payload matches the Close API format. > * Check that all required fields are present. > * Check that field names match the Close schema exactly, and that custom fields use `custom.cf_` IDs. # Discord Source: https://docs.dodopayments.com/integrations/discord Post real-time Dodo Payments notifications, such as payments, subscriptions, and disputes, to your Discord channels through a Discord webhook. ## Introduction The Discord integration posts payment, subscription, dispute, and other Dodo Payments events to a Discord channel you choose. Your team sees each event where it already collaborates, without polling an API or checking a dashboard. > [!NOTE] > > You need access to **Developer → Webhooks** in the Dodo Payments dashboard, and the **Manage Webhooks** permission in the Discord server. ## Getting Started **1. Create a Discord Webhook** In Discord, open the channel that should receive notifications and click **Edit Channel**. Go to **Integrations → Webhooks → New Webhook**, name the webhook, confirm the channel, and click **Copy Webhook URL**. **2. Open the Webhook Section** In the Dodo Payments dashboard, go to **Developer → Webhooks** and click **Add endpoint**. ![Add endpoint dialog with Discord selected in the Integration dropdown](https://mintcdn.com/dodopayments/DL_ADtkdH7ph5YST/images/integrations/discord.png?fit=max\&auto=format\&n=DL_ADtkdH7ph5YST\&q=85\&s=7ad7cc924fdfa59f88663666eee58983) **3. Select Discord** In **Integration**, select **Discord**. The **How to connect Discord** panel repeats the steps for creating the Discord webhook. **4. Paste the Webhook URL** Paste the Discord webhook URL, which starts with `https://discord.com/api/webhooks/`, into **Endpoint URL**. Discord doesn't need an API key. **5. Select Events** In **Subscribed events**, select the events your transformation handles. Discord rejects a message that has no `content` or `embeds`, so an event the transformation doesn't convert fails to deliver. **6. Edit Transformation Code** Under **Transformation code**, tailor how each event maps to a Discord embed, or start from the [examples](#transformation-code-examples). **7. Test & Create** Under **Test this code**, click **Simulate** to preview the embed for a sample payload. Then click **Create endpoint**. **8. Done** Your Discord channel now receives a message for each subscribed event. ## Transformation Code Examples Each handler replaces `webhook.payload` with a Discord message that contains one embed. Dodo Payments amounts are in the smallest currency unit, so the examples divide by 100 and show the currency code. ### Minimal Payment Embed Post an embed when a payment succeeds (`payment.succeeded`): ```javascript payment_embed.js icon="js" expandable theme={null} function handler(webhook) { if (webhook.eventType === "payment.succeeded") { const p = webhook.payload.data; webhook.payload = { embeds: [{ title: "✅ Payment Successful", description: `**Amount:** ${(p.total_amount / 100).toFixed(2)} ${p.currency}\n**Customer:** ${p.customer.email}`, color: 0x2ecc71 // green }] }; } return webhook; } ``` ### Subscription Events Post an embed when a subscription becomes active (`subscription.active`) or is cancelled (`subscription.cancelled`): ```javascript subscription_embed.js icon="js" expandable theme={null} function handler(webhook) { const s = webhook.payload.data; switch (webhook.eventType) { case "subscription.active": webhook.payload = { embeds: [{ title: "📄 Subscription Activated", fields: [ { name: "Customer", value: s.customer.email, inline: true }, { name: "Product", value: s.product_id, inline: true }, { name: "Next Billing", value: new Date(s.next_billing_date).toLocaleDateString(), inline: true } ], color: 0x2ecc71 }] }; break; case "subscription.cancelled": webhook.payload = { embeds: [{ title: "⚠️ Subscription Cancelled", fields: [ { name: "Customer", value: s.customer.email, inline: true }, { name: "Product", value: s.product_id, inline: true } ], color: 0xf1c40f }] }; break; } return webhook; } ``` ### Dispute Alerts Post an embed for every dispute event, such as `dispute.opened`, `dispute.won`, and `dispute.lost`. The title and color follow the dispute's `dispute_status`: ```javascript dispute_embed.js icon="js" expandable theme={null} function handler(webhook) { if (webhook.eventType.startsWith("dispute.")) { const d = webhook.payload.data; webhook.payload = { embeds: [{ title: d.dispute_status === "dispute_won" ? "🏆 Dispute Won" : d.dispute_status === "dispute_lost" ? "❌ Dispute Lost" : "🚨 Dispute Update", fields: [ { name: "Payment ID", value: d.payment_id, inline: true }, { name: "Amount", value: `${(d.amount / 100).toFixed(2)} ${d.currency}`, inline: true }, { name: "Status", value: d.dispute_status, inline: true } ], color: d.dispute_status === "dispute_won" ? 0x2ecc71 : d.dispute_status === "dispute_lost" ? 0xe74c3c : 0xe67e22 }] }; } return webhook; } ``` ## Tips * Use embeds for rich formatting and colors. * Keep titles short, and put details in fields. * Use colors that signal the outcome: green for success, red for failure, and orange for warnings. ## Troubleshooting > [accordion] No Messages in Discord > > * Confirm that the webhook still exists under the channel's **Integrations → Webhooks**, and that **Endpoint URL** matches its URL. > * Check that the transformation returns a JSON object with `embeds`. > * Check that **Subscribed events** includes the events you expect. > * Open the endpoint's delivery attempts in the **Logs** tab of **Developer → Webhooks** to see Discord's response code. > [accordion] Transformation Errors > > * Validate your code in the editor. Syntax errors block delivery. > * Check that field names match the webhook payload structure. # Fernand Source: https://docs.dodopayments.com/integrations/fernand See Dodo Payments customer, plan, and purchase details on support conversations in Fernand, and route conversations with rules based on whether a contact pays. ## Introduction [Fernand](https://getfernand.com/integrations/dodo-payments/) is a customer support tool with a native Dodo Payments integration. When someone writes in, Fernand matches them to their Dodo Payments customer record and shows their customer status, plan, and purchases on the conversation. Your team can answer billing questions without switching to the Dodo Payments dashboard. ![Illustration of the Fernand and Dodo Payments logos connected by sync arrows](https://mintcdn.com/dodopayments/pL7JQ_1IYARyJsKr/images/integrations/fernand/connect.png?fit=max\&auto=format\&n=pL7JQ_1IYARyJsKr\&q=85\&s=4f0629b8421f551a776d1ee4c4de66fa) ## What You Can Do After you connect, Fernand uses your Dodo Payments data in three places: * **Conversation list**: A paying customer is marked before you open the conversation, so you can tell customers from prospects in the queue. * **Conversation sidebar**: The sidebar shows the contact's customer status, plan, and purchases. * **Rules**: The **Contact is a customer** and **Contact has paid plan** conditions route conversations. A matching rule can reply, tag, assign, change the conversation status, or send a webhook. Fernand can also refund payments and manage subscriptions from the conversation, which is why the API key needs **Write** access to those resources. ![Fernand inbox with a conversation from a paying Dodo Payments customer marked with a dollar badge and a Long Term Customer tag](https://mintcdn.com/dodopayments/pL7JQ_1IYARyJsKr/images/integrations/fernand/sidebar.png?fit=max\&auto=format\&n=pL7JQ_1IYARyJsKr\&q=85\&s=457cdb22b2687d8def09e832c2896d39) ## Prerequisites Before you start, you need: * A [Dodo Payments account](https://app.dodopayments.com) in live mode. * A [Fernand account](https://app.getfernand.com/create). The integration is included on every Fernand plan, including the free plan. ## Getting Started **1. Open the Dodo Payments Integration in Fernand** In Fernand, go to **Settings → Integrations**. You can also press `G`, then `S`. Select **Dodo Payments** and click **Connect**. A dialog asks for an API key. **2. Create an API Key in Live Mode** In the Dodo Payments dashboard, turn on the **Live Mode** switch. Fernand matches your real customers, so the key must be a live mode key. Go to **Developer → API Keys** and click **Create New Key**. Name the key `Fernand`, then set the access for each resource: | Resource | Access | | :- | :- | | Payments | Write | | Refunds | Write | | Subscriptions | Write | | Webhooks | Write | | Products | Read | | Customers | Read | Leave every other resource on **None**. For details on key access, see [Authentication](/api-reference/introduction#authentication). **3. Paste the Key into Fernand** Copy the key when Dodo Payments shows it, because the dashboard shows it only once. Paste it into the Fernand dialog and click **Connect to Dodo**. > [!TIP] > > Fernand starts syncing customer and subscription data. Conversations from your Dodo Payments customers show their status, plan, and purchases. To disconnect, go to **Settings → Integrations** in Fernand. To revoke Fernand's access completely, also delete the key under **Developer → API Keys** in Dodo Payments. ## Routing Conversations with Rules Fernand rules can use Dodo Payments data as conditions. For example: * Tag conversations from paying customers, or assign them to a priority inbox, with **Contact has paid plan**. * Send a different auto-reply to contacts who aren't customers, with **Contact is a customer**. * Send a webhook to your own system when a paying customer writes in. For how rules work, see Fernand's [Rules guide](https://help.getfernand.com/features/automation-rules/rules). ## Additional Resources > [card] [Fernand's Dodo Payments Guide](https://help.getfernand.com/integrations/dodo-payments-integration) > > The setup guide in Fernand's help center. > [card] [API Keys and Authentication](/api-reference/introduction#authentication) > > How Dodo Payments API keys, modes, and resource access work. > [!NOTE] > > For help with the integration, contact Fernand support at [support@getfernand.com](mailto:support@getfernand.com) or Dodo Payments support at [support@dodopayments.com](mailto:support@dodopayments.com). # Framer Plugin Source: https://docs.dodopayments.com/integrations/framer-plugin Add Dodo Payments buy buttons to your Framer site with the official plugin. Sell one-time and subscription products with overlay or hosted checkout. ## Overview The Dodo Payments Framer plugin adds buy buttons for your Dodo Payments products to a Framer site. Each button opens checkout as an overlay on your page or sends the customer to the hosted checkout page, in test mode or live mode. > [card] [Official Plugin](https://www.framer.com/marketplace/plugins/dodo-payments) > > Install the Dodo Payments plugin from the Framer Marketplace. ## Features > [card] Hosted or Overlay Checkout > > Open checkout as an overlay on your page, or send customers to the hosted checkout page. > [card] Drag-and-Drop Setup > > Paste your API key into the plugin, add a buy button to the canvas, and publish. > [card] Digital Delivery > > Deliver download links or license keys to customers by email after payment. > [card] Worldwide Coverage > > Sell to customers in 220+ countries with cards, wallets, and local payment methods. > [card] Automatic Tax & Invoicing > > As Merchant of Record, Dodo Payments calculates and remits VAT, GST, and sales tax, and issues an invoice for each payment. > [card] No-Code Subscriptions > > Subscription products get the same buy button as one-time products, with no code. ## Setup Guide **1. Generate API Key** In the Dodo Payments dashboard, go to **Developer → API Keys** and click **Create New Key**. You can also open the [API Keys page](https://app.dodopayments.com/developer/api-keys) directly. Enter a **Key Name**, then use **Select all** and choose **Write**. An API key works in one mode only. Before you create the key, use the **Live Mode** switch in the sidebar to choose the mode: > [tab] Live Mode > > For production. Customers pay with real payment methods. > [tab] Test Mode > > For development and testing. No real charges are made. > [!TIP] > > Copy the API key and store it securely. The dashboard shows it only once, and you paste it into the plugin in the next step. **2. Authenticate Plugin** > [!WARNING] > > Keep your API key secret. Never share it or publish it. 1. Open the Dodo Payments plugin in Framer. It opens on the **Authenticate** page. 2. Under **API Mode**, select **Test Mode** or **Live Mode** to match your API key. 3. Paste your API key into **API Key**. 4. Click **Continue**. **3. Manage Products** After you authenticate, the plugin lists the products from the mode you selected under **Products**: * **Existing products** appear automatically, each marked **One-time** or **Subscription**. * **No products yet**: click the **Plus (+)** button next to **Products**. > [!NOTE] > > The **Plus (+)** button opens the Dodo Payments dashboard, where you create a product and set its price, description, and other settings. **4. Add Buy Buttons** 1. Select a product from the list. 2. Click **Add Buy Button**. The plugin adds a buy button with the label `Buy {product_name}` to your canvas. On the same product screen, **Edit** opens the product in the Dodo Payments dashboard, and **Show Preview** opens its checkout preview. > [!WARNING] > > **Add Buy Button** is disabled if you don't have permission to add components and change their properties in the Framer project. ## Customization To change how a buy button works, select it on the canvas and edit its properties in Framer. **1. Select Checkout Experience** Set **Type** to choose how checkout opens: * **Overlay**: Checkout opens as an overlay on your Framer page, so customers stay on your site. The plugin uses this type for new buttons. * **Hosted**: The button links to the Dodo Payments hosted checkout page. **Link Target** sets whether the page opens in a new tab or the same tab. **2. Customize Appearance Options** Match the button and checkout to your site with these properties: * **Checkout Theme**: A light or dark checkout. * **Label**: The button text, such as "Buy Now", "Purchase", or "Get Started". * Button styling: The background color, text color, font, font size, border radius, and padding. * **Return URL**: The Framer page or URL that customers return to after checkout. * **Environment**: **Live** or **Test**. The plugin sets it to the mode you authenticated with. ## Troubleshooting > [accordion] Authentication Issues > > **Problem**: The plugin doesn't authenticate. > > **Solutions**: > > * Check that you pasted the complete API key. > * Check that **API Mode** matches the mode the key was created in. A test mode key doesn't work in live mode, and a live mode key doesn't work in test mode. > * Check your internet connection. > [accordion] Button Creation Issues > > **Problem**: **Add Buy Button** is disabled. > > **Solutions**: > > * Check that your role in the Framer project lets you add components and change their properties. > * Check that the plugin is authenticated. > * Close and reopen the plugin. > [accordion] Product Display Issues > > **Problem**: Products don't appear in the plugin. > > **Solutions**: > > * Check that you created products in your Dodo Payments dashboard. > * Check that the products exist in the same mode as your API key. The plugin lists only the products from the mode you authenticated with. > * Authenticate the plugin again. # GoHighLevel Source: https://docs.dodopayments.com/integrations/gohighlevel Integrate Dodo Payments with GoHighLevel (GHL) using no-code payment links, overlay checkout, or inline checkout, and automate fulfillment with webhooks. ## Introduction Connect Dodo Payments to [GoHighLevel](https://www.gohighlevel.com/) (GHL) to sell from your GHL funnels, websites, emails, and SMS, and to fulfill orders with GHL automation. GHL is a CRM and marketing platform with funnels, websites, email and SMS, and automation (**Workflows**). GHL doesn't list Dodo Payments as a built-in payment processor, so you connect the two in one of three ways. Pick one based on how embedded you want checkout to be and how much code you can write. Every approach handles fulfillment the same way: Dodo Payments sends [webhook events](/developer-resources/webhooks) to a GHL **Inbound Webhook** workflow, which tags the contact, grants access, and sends confirmations. ## Choose Your Approach The three approaches differ in the code they need and in where the customer pays: | Approach | Code needed | Checkout experience | Best for | | - | - | - | - | | **A. Payment Links** | None (no-code) | The customer goes to the Dodo Payments hosted checkout | Most GHL users, fastest to launch | | **B. Overlay Checkout** | Custom code plus a backend | A modal opens over your GHL page | Teams who want checkout on the page without leaving the funnel | | **C. Inline Checkout** | Custom code plus a backend | The checkout form is embedded in the page | A fully embedded, branded checkout | > [!NOTE] > > If you're new to Dodo Payments, start with **Approach A (Payment Links)**. It needs no code and works for every GHL user. Approaches B and C need a backend that creates [checkout sessions](/api-reference/checkout-sessions/create), so they suit teams that are comfortable with code. ## Prerequisites Before you start, you need: * A Dodo Payments account with at least one **product**. * A GoHighLevel account with a funnel, website, or workflow. * Access to **Developer → Webhooks** in the Dodo Payments dashboard, and to **Developer → API Keys** if you need an API key. * For Approaches B and C: a small **backend or serverless endpoint** that creates checkout sessions. > [!NOTE] > > GHL requires a **connected domain** to *publish* a funnel. While you build, use the funnel's **Preview** to test. Custom JavaScript (Approaches B and C) generally runs only on the **published page on a real domain**, not in Preview. ## Fulfillment with Webhooks (All Approaches) The webhook workflow is the automation layer. Set it up once, and it works with every checkout approach. **1. Create the Workflow** In your GHL **sub-account**, open **Automation** in the left menu. It opens on the **Workflows** tab. Click **Create workflow**, then choose **Start from Scratch**. **2. Add the Inbound Webhook Trigger** In the builder, click **Add new trigger**. In the **Add trigger** panel, search for **webhook** and select **Inbound webhook**, listed under **Triggers → Events**. Copy the **Webhook URL** that it generates. **3. Register the Webhook in Dodo Payments** In the Dodo Payments dashboard, go to **Developer → Webhooks** and click **Add endpoint**. Paste the GHL Inbound Webhook URL into **Endpoint URL** and click **Create endpoint**. Then give GHL a sample payload to map fields from, such as the customer email, product, amount, and status. Either make a test purchase, or open the endpoint's **Testing** tab, select an event type, and click **Send example**. **4. Add Fulfillment Actions** In the GHL workflow, add actions for the event, such as **find/create contact by email**, **add a tag**, **grant course/membership access**, and **send a confirmation email**. Then **Publish** the workflow. > [!WARNING] > > Dodo Payments processes the payments, so they **don't** appear in the GHL **Payments** tab. Record them in GHL with the webhook workflow above. Grant access from the **webhook**, not from the browser redirect, because a customer can close the tab before the redirect completes. ## Approach A: Payment Links (No-Code) Add a Dodo Payments payment link to any GHL button, funnel call to action, order page button, email, or SMS. Customers pay on the Dodo Payments hosted checkout. For what the checkout supports, see [Checkout Features](/features/checkout). **1. Create a Product and Copy Its Payment Link** In the Dodo Payments dashboard, go to **Products** and click **Add Product**. Set the **name** and **price**, choose **one-time** or **subscription**, and save the product. On the product's row, click **Share**, then click **Copy payment link**. The link has the format `https://checkout.dodopayments.com/buy/{product_id}`. **2. Add the Link to Your GHL Button** Edit your funnel or website page and select the **Buy / Checkout button**. Set its action to **Open URL / Website** and paste your payment link. **3. Set a Success Page (Optional)** To bring customers back to your funnel after they pay, enter your GHL thank-you page in **Redirect URL** in the product's **Share** sheet before you copy the link. The link then carries it as the `redirect_url` parameter. > [!TIP] > > Payment link query parameters can prefill and lock customer details, or add tracking. For example, pass a funnel or offer ID as a `metadata_*` parameter and read it back from the webhook. See [Static Payment Links](/developer-resources/integration-guide#static-payment-links) for every parameter. ## Approach B: Overlay Checkout (Custom Code) Approach B opens Dodo Payments checkout as a **modal overlay** on your GHL page, using the [Checkout SDK](/developer-resources/overlay-checkout) from a CDN. It needs a backend that creates a [checkout session](/api-reference/checkout-sessions/create) and returns its `checkoutUrl`. **1. Create a Backend Endpoint That Calls the Checkout Sessions API** This step is **required**. The SDK needs a checkout session URL, and creating a session requires your **secret API key**. GHL hosts pages only and can't make this server-side call for you. Never call the [Create Checkout Session API](/api-reference/checkout-sessions/create) from the browser, because that exposes your secret key in the page source. Overlay and inline checkout therefore **can't work with GHL alone**: you need a backend you control that creates the session and returns only the URL. Any small backend works: a serverless function (Cloudflare Workers, Vercel Functions, AWS Lambda, Supabase Edge Functions, and similar), or an endpoint on a server you already run. The logic is the same on every platform: receive the request, call the Dodo Payments API with your secret key, and return the `checkout_url`. Example handler logic, to adapt to your platform: ```js theme={null} async function createCheckout(env) { const res = await fetch("https://test.dodopayments.com/checkouts", { method: "POST", headers: { "Authorization": `Bearer ${env.DODO_PAYMENTS_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ product_cart: [{ product_id: "pdt_your_product_id", quantity: 1 }], }), }); const data = await res.json(); return { checkoutUrl: data.checkout_url }; } ``` Store your API key as a secret in the `DODO_PAYMENTS_API_KEY` environment variable on the platform you deploy to, and never commit it to code. Allow requests from your GHL domain (CORS), and serve the endpoint from a domain you control, for example `https://api.example.com/create-checkout`. When you move to live mode, switch the URL to `https://live.dodopayments.com/checkouts`. **2. Add a Custom Code Element in the GHL Page Builder** Open your funnel step or website page in the GHL page builder, then: 1. Click the **+** icon at the top left of the builder to open **Quick Add**. 2. Select **Elements** from the category list on the left. 3. Find **Custom Code** (also shown as HTML) and drag it onto the page. 4. Paste the code below into the element's code editor, then save it. ```html theme={null} ``` **3. Publish and Test on Your Domain** Custom JavaScript runs on the **published** page on your connected domain, and may not run in Preview. Publish the page, then click **Pay Now** to confirm that the overlay opens. ## Approach C: Inline (Embedded) Checkout Approach C embeds the checkout form **inside** your GHL page, with no redirect and no popup. It uses the same SDK with a container element to mount into. Like Approach B, it needs a backend to create the session. **1. Create a Backend Endpoint That Calls the Checkout Sessions API** This step is **required**, as it is for overlay checkout. Creating a session needs your secret API key, so it must happen on a server, and GHL can't do this on its own. Reuse the backend endpoint from the **Overlay Checkout** section above: any small serverless function or server you control that calls the [Create Checkout Session API](/api-reference/checkout-sessions/create) and returns `{ checkoutUrl }`. **2. Add a Container and SDK via Custom Code** In the GHL page builder: 1. Click the **+** icon at the top left of the builder to open **Quick Add**. 2. Select **Elements** from the category list on the left. 3. Find **Custom Code** (also shown as HTML) and drag it onto the page where you want the checkout form to appear. 4. Paste the code below into the element's code editor, then save it. ```html theme={null}
``` **3. Verify Your Domain for Wallets (Apple Pay)** To offer Apple Pay in inline checkout, [verify your domain](/features/payment-methods/digital-wallets#apple-pay). In the Dodo Payments dashboard, go to **Settings → Payment Methods** and click **Manage domains** on the **Apple Pay** row. Download the domain association file, host it on your domain, and register the domain. Apple Pay isn't available in overlay checkout (Approach B). A GHL-hosted domain can't host the domain association file. Apple Pay in inline checkout needs a domain you control that can serve `/.well-known/apple-developer-merchantid-domain-association`. On GHL-hosted pages, use the hosted checkout from Payment Links (Approach A) or skip Apple Pay. > [!WARNING] > > Inline checkout is the most involved option in GHL. It needs custom code, a backend, a published page on a real domain, and, for Apple Pay, domain verification. If you don't need a fully embedded form, use Approach A or B instead. ## Events to Handle Subscribe the GHL endpoint to the events your workflow acts on. The table suggests a GHL action for each: | Dodo Payments event | When it fires | Suggested GHL action | | - | - | - | | `payment.succeeded` | A payment succeeds | Tag the contact as paid, grant access, send a confirmation | | `subscription.active` | A subscription is activated | Grant membership, start the onboarding workflow | | `subscription.renewed` | A subscription renews for the next billing period | Extend access for the next cycle | | `subscription.past_due` | A renewal fails and the grace period opens. The customer keeps access until the deadline | Start the dunning or reminder workflow while the customer still has access | | `subscription.on_hold` | The subscription is put on hold after a failed renewal | Pause access, escalate the reminder sequence | | `subscription.cancelled` / `subscription.expired` | The subscription ends | Remove access, tag as churned | Payment and subscription events include the **customer email** in `data.customer.email`. Use GHL's **find/create contact by email** action to match the payment to the right contact. For every event, see the [Webhook Event Guide](/developer-resources/webhooks/intents/webhook-events-guide). ## Testing & Going Live **1. Test in Test Mode** Keep the **Live Mode** switch in the Dodo Payments sidebar off, so you work in test mode. Complete a purchase with the test card `4242 4242 4242 4242` (expiry `06/32`, CVV `123`), and confirm that the GHL workflow runs and applies the tag or access. **2. Go Live** Turn on the **Live Mode** switch and add the GHL Inbound Webhook URL as an endpoint in live mode. What else changes depends on your approach: * **Payment Links (A):** Replace the link with the product's **live** payment link. * **Overlay checkout (B):** Point your backend at `https://live.dodopayments.com/checkouts` with your **live** API key, and set `mode` to `"live"` in the SDK's `Initialize` call. * **Inline checkout (C):** Make the same changes as for overlay checkout, since it uses the same backend endpoint and SDK initialization. Then make one real purchase from start to finish to confirm the setup. ## Tips > [!TIP] > > Treat the **webhook as the source of truth** for granting access. Act on `payment.succeeded` or `subscription.active`, not on the browser redirect. > [!TIP] > > A GHL Inbound Webhook can't verify the `webhook-signature` header. So that only genuine Dodo Payments events trigger fulfillment in GHL, point the Dodo Payments webhook endpoint at your own backend, verify each event there ([Webhooks](/developer-resources/webhooks)), and then forward it to the GHL Inbound Webhook URL. ## Troubleshooting > [accordion] Payment succeeded but nothing happened in GHL > > Check that the Dodo Payments webhook endpoint points to the correct GHL Inbound Webhook URL, that the workflow is **published**, and that the trigger captured a sample payload, so the field mapping exists. > [accordion] Overlay or inline button does nothing > > Custom JavaScript usually runs only on the **published page on a real domain**, not in Preview. Confirm that the page is published, that the SDK ` ``` **4. Pass the Referral into Checkout** Attach the captured referral to each payment as `rekomi_ref` metadata. The [Implementation Guide](#implementation-guide) shows how for each checkout type. **5. Done** Sales, renewals, refunds, and disputes now credit and claw back affiliate commissions automatically, and Rekomi pays your affiliates. ## Implementation Guide ### Checkout Sessions via the API On your frontend, read the referral with `window.Rekomi.getReferral()` and send it to your backend with the checkout request. On the backend, set it in `metadata`: ```typescript Node.js theme={null} import DodoPayments from 'dodopayments'; // Reads DODO_PAYMENTS_API_KEY from the environment and defaults to live mode. const client = new DodoPayments(); export async function createCheckout(productId: string, rekomiRef?: string) { const session = await client.checkoutSessions.create({ product_cart: [{ product_id: productId, quantity: 1 }], customer: { email: 'customer@example.com', name: 'John Doe', }, return_url: 'https://yoursite.com/success', metadata: { ...(rekomiRef ? { rekomi_ref: rekomiRef } : {}), }, }); return session.checkout_url; } ``` The same `metadata.rekomi_ref` field works on subscription products, so the first charge and every renewal credit the same affiliate. ### Static Payment Links Add the referral to the link as a flat `metadata_rekomi_ref` query parameter, not the bracket form: ```javascript theme={null} const ref = window.Rekomi?.getReferral?.(); let url = 'https://checkout.dodopayments.com/buy/YOUR_PRODUCT_ID'; if (ref) url += `?metadata_rekomi_ref=${encodeURIComponent(ref)}`; // use url as the href on your Buy button ``` Dodo Payments adds `metadata_*` query parameters to the payment's metadata, where Rekomi reads them. ## What Gets Tracked Rekomi handles each type of sale event as follows: | Event | What happens | | - | - | | One-time payment | Commission credited on the pre-tax sale amount | | Subscription renewal | Recurring commission, every charge arrives as its own payment event | | Refund | Commission clawed back automatically, up to the amount credited | | Dispute | Commission clawed back as soon as the dispute opens | > [!TIP] > > Rekomi calculates commissions on the pre-tax sale amount. Dodo Payments is the Merchant of Record and collects the tax, so your affiliates earn on the sale itself, not on the tax that the buyer's country adds. ## Important Notes * Rekomi registers the webhook endpoint with exactly the events it needs. Don't edit that endpoint's event list in the Dodo Payments dashboard: Rekomi's health checks flag the connection if events are removed. * A free trial creates no payment until the trial ends, so no commission exists until the first charge. A [paid trial](/features/subscription#paid-trials) charges the trial amount upfront. * Disconnecting in Rekomi deletes the webhook endpoint from your Dodo Payments account. ## Additional Resources > [card] [Rekomi's Dodo Payments Guide](https://rekomi.com/docs/brands/install/dodo) > > The full setup walkthrough, troubleshooting, and security details in Rekomi's docs. > [card] [Affiliates Feature Guide](/features/affiliates) > > All affiliate integration options for Dodo Payments. > [!NOTE] > > For help with the integration, contact Rekomi support at [support@rekomi.com](mailto:support@rekomi.com) or Dodo Payments support at [support@dodopayments.com](mailto:support@dodopayments.com).